]>
git.p6c8.net - jirafeau_project.git/blob - lib/functions.php
e23727413f7d4c35efb36c6479c852411d5c5142
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 '/'
29 for ($i = 0; $i < strlen($s); $i++
) {
36 * Convert base 16 to base 64
37 * @returns A string based on 64 characters (0-9, a-z, A-Z, "-" and "_")
39 function base_16_to_64($num)
41 $m = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_';
42 $hex2bin = array('0000', # 0
61 # Convert long hex string to bin.
63 for ($i = 0; $i < $size; $i++
) {
64 $b .= $hex2bin{hexdec($num{$i})};
66 # Convert long bin to base 64.
68 for ($i = $size - 6; $i >= 0; $i -= 6) {
69 $o = $m{bindec(substr($b, $i, 6))} . $o;
71 # Some few bits remaining ?
72 if ($i < 0 && $i > -6) {
73 $o = $m{bindec(substr($b, 0, $i +
6))} . $o;
79 * Generate a random code.
80 * @param $l code length
81 * @return random code.
83 function jirafeau_gen_random($l)
90 for ($i = 0; $i < $l; $i++
) {
91 $code .= dechex(rand(0, 15));
99 if (isset($_SERVER['HTTPS'])) {
100 if ('on' == strtolower($_SERVER['HTTPS']) ||
101 '1' == $_SERVER['HTTPS']) {
104 } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
106 } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
107 if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
114 function jirafeau_human_size($octets)
116 $u = array('B', 'KB', 'MB', 'GB', 'TB');
117 $o = max($octets, 0);
118 $p = min(floor(($o ?
log($o) : 0) / log(1024)), count($u) - 1);
120 return round($o, 1) . $u[$p];
123 // Convert UTC timestamp to a datetime field
124 function jirafeau_get_datetimefield($timestamp)
126 $content = '<span class="datetime" data-datetime="' . strftime('%Y-%m-%d %H:%M', $timestamp) . '">'
127 . strftime('%Y-%m-%d %H:%M', $timestamp) . ' (GMT)</span>';
131 function jirafeau_fatal_error($errorText, $cfg = array())
133 echo '<div class="error"><h2>Error</h2><p>' . $errorText . '</p></div>';
134 require(JIRAFEAU_ROOT
. 'lib/template/footer.php');
138 function jirafeau_clean_rm_link($link)
141 if (file_exists(VAR_LINKS
. $p . $link)) {
142 unlink(VAR_LINKS
. $p . $link);
144 $parse = VAR_LINKS
. $p;
146 while (file_exists($parse)
147 && ($scan = scandir($parse))
148 && count($scan) == 2 // '.' and '..' folders => empty.
149 && basename($parse) != basename(VAR_LINKS
)) {
151 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
155 function jirafeau_clean_rm_file($md5)
158 $f = VAR_FILES
. $p . $md5;
159 if (file_exists($f) && is_file($f)) {
162 if (file_exists($f . '_count') && is_file($f . '_count')) {
163 unlink($f . '_count');
165 $parse = VAR_FILES
. $p;
167 while (file_exists($parse)
168 && ($scan = scandir($parse))
169 && count($scan) == 2 // '.' and '..' folders => empty.
170 && basename($parse) != basename(VAR_FILES
)) {
172 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
177 * transforms a php.ini string representing a value in an integer
178 * @param $value the value from php.ini
179 * @returns an integer for this value
181 function jirafeau_ini_to_bytes($value)
183 $modifier = substr($value, -1);
184 $bytes = substr($value, 0, -1);
185 switch (strtoupper($modifier)) {
201 * gets the maximum upload size according to php.ini
202 * @returns the maximum upload size in bytes
204 function jirafeau_get_max_upload_size_bytes()
206 return min(jirafeau_ini_to_bytes(ini_get('post_max_size')),
207 jirafeau_ini_to_bytes(ini_get('upload_max_filesize')));
211 * gets the maximum upload size according to php.ini
212 * @returns the maximum upload size string
214 function jirafeau_get_max_upload_size()
216 return jirafeau_human_size(
217 min(jirafeau_ini_to_bytes(ini_get('post_max_size')),
218 jirafeau_ini_to_bytes(ini_get('upload_max_filesize'))));
222 * gets a string explaining the error
223 * @param $code the error code
224 * @returns a string explaining the error
226 function jirafeau_upload_errstr($code)
229 case UPLOAD_ERR_INI_SIZE
:
230 case UPLOAD_ERR_FORM_SIZE
:
231 return t('Your file exceeds the maximum authorized file size. ');
233 case UPLOAD_ERR_PARTIAL
:
234 case UPLOAD_ERR_NO_FILE
:
236 t('Your file was not uploaded correctly. You may succeed in retrying. ');
238 case UPLOAD_ERR_NO_TMP_DIR
:
239 case UPLOAD_ERR_CANT_WRITE
:
240 case UPLOAD_ERR_EXTENSION
:
241 return t('Internal error. You may not succeed in retrying. ');
243 return t('Unknown error. ');
246 /** Remove link and it's file
247 * @param $link the link's name (hash)
250 function jirafeau_delete_link($link)
252 $l = jirafeau_get_link($link);
257 jirafeau_clean_rm_link($link);
263 if (file_exists(VAR_FILES
. $p . $md5. '_count')) {
264 $content = file(VAR_FILES
. $p . $md5. '_count');
265 $counter = trim($content[0]);
270 $handle = fopen(VAR_FILES
. $p . $md5. '_count', 'w');
271 fwrite($handle, $counter);
276 jirafeau_clean_rm_file($md5);
281 * Delete a file and it's links.
283 function jirafeau_delete_file($md5)
286 /* Get all links files. */
287 $stack = array(VAR_LINKS
);
288 while (($d = array_shift($stack)) && $d != null) {
291 foreach ($dir as $node) {
292 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
293 preg_match('/\.tmp/i', "$node")) {
297 if (is_dir($d . $node)) {
298 /* Push new found directory. */
299 $stack[] = $d . $node . '/';
300 } elseif (is_file($d . $node)) {
301 /* Read link informations. */
302 $l = jirafeau_get_link(basename($node));
306 if ($l['md5'] == $md5) {
308 jirafeau_delete_link($node);
313 jirafeau_clean_rm_file($md5);
318 * handles an uploaded file
319 * @param $file the file struct given by $_FILE[]
320 * @param $one_time_download is the file a one time download ?
321 * @param $key if not empty, protect the file with this key
322 * @param $time the time of validity of the file
323 * @param $ip uploader's ip
324 * @param $crypt boolean asking to crypt or not
325 * @param $link_name_length size of the link name
326 * @returns an array containing some information
327 * 'error' => information on possible errors
328 * 'link' => the link name of the uploaded file
329 * 'delete_link' => the link code to delete file
331 function jirafeau_upload($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length)
333 if (empty($file['tmp_name']) ||
!is_uploaded_file($file['tmp_name'])) {
336 array('has_error' => true,
337 'why' => jirafeau_upload_errstr($file['error'])),
339 'delete_link' => ''));
342 /* array representing no error */
343 $noerr = array('has_error' => false, 'why' => '');
345 /* Crypt file if option is enabled. */
348 if ($crypt == true && !(extension_loaded('mcrypt') == true)) {
349 error_log("PHP extension mcrypt not loaded, won't encrypt in Jirafeau");
351 if ($crypt == true && extension_loaded('mcrypt') == true) {
352 $crypt_key = jirafeau_encrypt_file($file['tmp_name'], $file['tmp_name']);
353 if (strlen($crypt_key) > 0) {
358 /* file informations */
359 $md5 = md5_file($file['tmp_name']);
360 $name = str_replace(NL
, '', trim($file['name']));
361 $mime_type = $file['type'];
362 $size = $file['size'];
364 /* does file already exist ? */
367 if (file_exists(VAR_FILES
. $p . $md5)) {
368 $rc = unlink($file['tmp_name']);
369 } elseif ((file_exists(VAR_FILES
. $p) || @mkdir
(VAR_FILES
. $p, 0755, true))
370 && move_uploaded_file($file['tmp_name'], VAR_FILES
. $p . $md5)) {
376 array('has_error' => true,
377 'why' => t('INTERNAL_ERROR_DEL')),
379 'delete_link' => ''));
382 /* Increment or create count file. */
384 if (file_exists(VAR_FILES
. $p . $md5 . '_count')) {
385 $content = file(VAR_FILES
. $p . $md5. '_count');
386 $counter = trim($content[0]);
389 $handle = fopen(VAR_FILES
. $p . $md5. '_count', 'w');
390 fwrite($handle, $counter);
393 /* Create delete code. */
394 $delete_link_code = jirafeau_gen_random(5);
396 /* md5 password or empty. */
399 $password = md5($key);
402 /* create link file */
403 $link_tmp_name = VAR_LINKS
. $md5 . rand(0, 10000) . '.tmp';
404 $handle = fopen($link_tmp_name, 'w');
406 $name . NL
. $mime_type . NL
. $size . NL
. $password . NL
. $time .
407 NL
. $md5. NL
. ($one_time_download ?
'O' : 'R') . NL
. time() .
408 NL
. $ip . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
410 $md5_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
411 $l = s2p("$md5_link");
412 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
413 !rename($link_tmp_name, VAR_LINKS
. $l . $md5_link)) {
414 if (file_exists($link_tmp_name)) {
415 unlink($link_tmp_name);
420 $handle = fopen(VAR_FILES
. $p . $md5. '_count', 'w');
421 fwrite($handle, $counter);
424 jirafeau_clean_rm_file($md5_link);
428 array('has_error' => true,
429 'why' => t('Internal error during file creation. ')),
431 'delete_link' => '');
433 return array( 'error' => $noerr,
435 'delete_link' => $delete_link_code,
436 'crypt_key' => $crypt_key);
440 * Tells if a mime-type is viewable in a browser
441 * @param $mime the mime type
442 * @returns a boolean telling if a mime type is viewable
444 function jirafeau_is_viewable($mime)
447 /* Actually, verify if mime-type is an image or a text. */
448 $viewable = array('image', 'text', 'video', 'audio');
449 $decomposed = explode('/', $mime);
450 return in_array($decomposed[0], $viewable);
455 // Error handling functions.
456 //! Global array that contains all registered errors.
457 $error_list = array();
460 * Adds an error to the list of errors.
461 * @param $title the error's title
462 * @param $description is a human-friendly description of the problem.
464 function add_error($title, $description)
467 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
471 * Informs whether any error has been registered yet.
472 * @return true if there are errors.
477 return !empty($error_list);
481 * Displays all the errors.
483 function show_errors()
487 echo '<div class="error">';
488 foreach ($error_list as $error) {
495 function check_errors($cfg)
497 if (file_exists(JIRAFEAU_ROOT
. 'install.php')
498 && !($cfg['installation_done'] === true)) {
499 header('Location: install.php');
503 /* check if the destination dirs are writable */
504 $writable = is_writable(VAR_FILES
) && is_writable(VAR_LINKS
);
506 /* Checking for errors. */
507 if (!is_writable(VAR_FILES
)) {
508 add_error(t('The file directory is not writable!'), VAR_FILES
);
511 if (!is_writable(VAR_LINKS
)) {
512 add_error(t('The link directory is not writable!'), VAR_LINKS
);
515 if (!is_writable(VAR_ASYNC
)) {
516 add_error(t('ASYNC_DIR_W'), VAR_ASYNC
);
521 * Read link informations
522 * @return array containing informations.
524 function jirafeau_get_link($hash)
527 $link = VAR_LINKS
. s2p("$hash") . $hash;
529 if (!file_exists($link)) {
534 $out['file_name'] = trim($c[0]);
535 $out['mime_type'] = trim($c[1]);
536 $out['file_size'] = trim($c[2]);
537 $out['key'] = trim($c[3], NL
);
538 $out['time'] = trim($c[4]);
539 $out['md5'] = trim($c[5]);
540 $out['onetime'] = trim($c[6]);
541 $out['upload_date'] = trim($c[7]);
542 $out['ip'] = trim($c[8]);
543 $out['link_code'] = trim($c[9]);
544 $out['crypted'] = trim($c[10]) == 'C';
550 * List files in admin interface.
552 function jirafeau_admin_list($name, $file_hash, $link_hash)
554 echo '<fieldset><legend>';
556 echo t('FILENAME') . ": " . jirafeau_escape($name);
558 if (!empty($file_hash)) {
559 echo t('FILE') . ": " . jirafeau_escape($file_hash);
561 if (!empty($link_hash)) {
562 echo t('LINK') . ": " . jirafeau_escape($link_hash);
564 if (empty($name) && empty($file_hash) && empty($link_hash)) {
570 echo '<td>' . t('FILENAME') . '</td>';
571 echo '<td>' . t('TYPE') . '</td>';
572 echo '<td>' . t('SIZE') . '</td>';
573 echo '<td>' . t('EXPIRE') . '</td>';
574 echo '<td>' . t('ONETIME') . '</td>';
575 echo '<td>' . t('UPLOAD_DATE') . '</td>';
576 echo '<td>' . t('ORIGIN') . '</td>';
577 echo '<td>' . t('ACTION') . '</td>';
580 /* Get all links files. */
581 $stack = array(VAR_LINKS
);
582 while (($d = array_shift($stack)) && $d != null) {
584 foreach ($dir as $node) {
585 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
586 preg_match('/\.tmp/i', "$node")) {
589 if (is_dir($d . $node)) {
590 /* Push new found directory. */
591 $stack[] = $d . $node . '/';
592 } elseif (is_file($d . $node)) {
593 /* Read link informations. */
594 $l = jirafeau_get_link($node);
600 if (!empty($name) && !preg_match("/$name/i", jirafeau_escape($l['file_name']))) {
603 if (!empty($file_hash) && $file_hash != $l['md5']) {
606 if (!empty($link_hash) && $link_hash != $node) {
609 /* Print link informations. */
612 '<strong><a id="upload_link" href="f.php?h='. jirafeau_escape($node) .'" title="' .
613 t('DL_PAGE') . '">' . jirafeau_escape($l['file_name']) . '</a></strong>';
615 echo '<td>' . jirafeau_escape($l['mime_type']) . '</td>';
616 echo '<td>' . jirafeau_human_size($l['file_size']) . '</td>';
617 echo '<td>' . ($l['time'] == -1 ?
'∞' : jirafeau_get_datetimefield($l['time'])) . '</td>';
619 if ($l['onetime'] == 'O') {
625 echo '<td>' . jirafeau_get_datetimefield($l['upload_date']) . '</td>';
626 echo '<td>' . $l['ip'] . '</td>';
628 '<form method="post">' .
629 '<input type = "hidden" name = "action" value = "download"/>' .
630 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
631 jirafeau_admin_csrf_field() .
632 '<input type = "submit" value = "' . t('DL') . '" />' .
634 '<form method="post">' .
635 '<input type = "hidden" name = "action" value = "delete_link"/>' .
636 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
637 jirafeau_admin_csrf_field() .
638 '<input type = "submit" value = "' . t('DEL_LINK') . '" />' .
640 '<form method="post">' .
641 '<input type = "hidden" name = "action" value = "delete_file"/>' .
642 '<input type = "hidden" name = "md5" value = "' . $l['md5'] . '"/>' .
643 jirafeau_admin_csrf_field() .
644 '<input type = "submit" value = "' . t('DEL_FILE_LINKS') . '" />' .
651 echo '</table></fieldset>';
655 * Clean expired files.
656 * @return number of cleaned files.
658 function jirafeau_admin_clean()
661 /* Get all links files. */
662 $stack = array(VAR_LINKS
);
663 while (($d = array_shift($stack)) && $d != null) {
666 foreach ($dir as $node) {
667 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
668 preg_match('/\.tmp/i', "$node")) {
672 if (is_dir($d . $node)) {
673 /* Push new found directory. */
674 $stack[] = $d . $node . '/';
675 } elseif (is_file($d . $node)) {
676 /* Read link informations. */
677 $l = jirafeau_get_link(basename($node));
682 if ($l['time'] > 0 && $l['time'] < time() ||
// expired
683 !file_exists(VAR_FILES
. $p . $l['md5']) ||
// invalid
684 !file_exists(VAR_FILES
. $p . $l['md5'] . '_count')) { // invalid
685 jirafeau_delete_link($node);
696 * Clean old async transferts.
697 * @return number of cleaned files.
699 function jirafeau_admin_clean_async()
702 /* Get all links files. */
703 $stack = array(VAR_ASYNC
);
704 while (($d = array_shift($stack)) && $d != null) {
707 foreach ($dir as $node) {
708 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
709 preg_match('/\.tmp/i', "$node")) {
713 if (is_dir($d . $node)) {
714 /* Push new found directory. */
715 $stack[] = $d . $node . '/';
716 } elseif (is_file($d . $node)) {
717 /* Read async informations. */
718 $a = jirafeau_get_async_ref(basename($node));
722 /* Delete transferts older than 1 hour. */
723 if (time() - $a['last_edited'] > 3600) {
724 jirafeau_async_delete(basename($node));
733 * Read async transfert informations
734 * @return array containing informations.
736 function jirafeau_get_async_ref($ref)
739 $refinfos = VAR_ASYNC
. s2p("$ref") . "$ref";
741 if (!file_exists($refinfos)) {
745 $c = file($refinfos);
746 $out['file_name'] = trim($c[0]);
747 $out['mime_type'] = trim($c[1]);
748 $out['key'] = trim($c[2], NL
);
749 $out['time'] = trim($c[3]);
750 $out['onetime'] = trim($c[4]);
751 $out['ip'] = trim($c[5]);
752 $out['last_edited'] = trim($c[6]);
753 $out['next_code'] = trim($c[7]);
758 * Delete async transfert informations
760 function jirafeau_async_delete($ref)
763 if (file_exists(VAR_ASYNC
. $p . $ref)) {
764 unlink(VAR_ASYNC
. $p . $ref);
766 if (file_exists(VAR_ASYNC
. $p . $ref . '_data')) {
767 unlink(VAR_ASYNC
. $p . $ref . '_data');
769 $parse = VAR_ASYNC
. $p;
771 while (file_exists($parse)
772 && ($scan = scandir($parse))
773 && count($scan) == 2 // '.' and '..' folders => empty.
774 && basename($parse) != basename(VAR_ASYNC
)) {
776 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
781 * Init a new asynchronous upload.
782 * @param $finename Name of the file to send
783 * @param $one_time One time upload parameter
784 * @param $key eventual password (or blank)
785 * @param $time time limit
786 * @param $ip ip address of the client
787 * @return a string containing a temporary reference followed by a code or the string 'Error'
789 function jirafeau_async_init($filename, $type, $one_time, $key, $time, $ip)
793 /* Create temporary folder. */
796 $code = jirafeau_gen_random(4);
798 $ref = jirafeau_gen_random(32);
799 $p = VAR_ASYNC
. s2p($ref);
800 } while (file_exists($p));
801 @mkdir
($p, 0755, true);
802 if (!file_exists($p)) {
807 /* md5 password or empty */
810 $password = md5($key);
813 /* Store informations. */
815 $handle = fopen($p, 'w');
817 str_replace(NL
, '', trim($filename)) . NL
.
818 str_replace(NL
, '', trim($type)) . NL
. $password . NL
.
819 $time . NL
. ($one_time ?
'O' : 'R') . NL
. $ip . NL
.
820 time() . NL
. $code . NL
);
823 return $ref . NL
. $code ;
827 * Append a piece of file on the asynchronous upload.
828 * @param $ref asynchronous upload reference
829 * @param $file piece of data
830 * @param $code client code for this operation
831 * @param $max_file_size maximum allowed file size
832 * @return a string containing a next code to use or the string "Error"
834 function jirafeau_async_push($ref, $data, $code, $max_file_size)
836 /* Get async infos. */
837 $a = jirafeau_get_async_ref($ref);
839 /* Check some errors. */
841 ||
$a['next_code'] != "$code"
842 ||
empty($data['tmp_name'])
843 ||
!is_uploaded_file($data['tmp_name'])) {
850 $r_path = $data['tmp_name'];
851 $w_path = VAR_ASYNC
. $p . $ref . '_data';
853 /* Check that file size is not above upload limit. */
854 if ($max_file_size > 0 &&
855 filesize($r_path) +
filesize($w_path) > $max_file_size * 1024 * 1024) {
856 jirafeau_async_delete($ref);
860 /* Concatenate data. */
861 $r = fopen($r_path, 'r');
862 $w = fopen($w_path, 'a');
864 if (fwrite($w, fread($r, 1024)) === false) {
867 jirafeau_async_delete($ref);
875 /* Update async file. */
876 $code = jirafeau_gen_random(4);
877 $handle = fopen(VAR_ASYNC
. $p . $ref, 'w');
879 $a['file_name'] . NL
. $a['mime_type'] . NL
. $a['key'] . NL
.
880 $a['time'] . NL
. $a['onetime'] . NL
. $a['ip'] . NL
.
881 time() . NL
. $code . NL
);
887 * Finalyze an asynchronous upload.
888 * @param $ref asynchronous upload reference
889 * @param $code client code for this operation
890 * @param $crypt boolean asking to crypt or not
891 * @param $link_name_length link name length
892 * @return a string containing the download reference followed by a delete code or the string 'Error'
894 function jirafeau_async_end($ref, $code, $crypt, $link_name_length)
896 /* Get async infos. */
897 $a = jirafeau_get_async_ref($ref);
899 ||
$a['next_code'] != "$code") {
903 /* Generate link infos. */
904 $p = VAR_ASYNC
. s2p($ref) . $ref . "_data";
905 if (!file_exists($p)) {
911 if ($crypt == true && extension_loaded('mcrypt') == true) {
912 $crypt_key = jirafeau_encrypt_file($p, $p);
913 if (strlen($crypt_key) > 0) {
919 $size = filesize($p);
921 $delete_link_code = jirafeau_gen_random(5);
923 /* File already exist ? */
924 if (!file_exists(VAR_FILES
. $np)) {
925 @mkdir
(VAR_FILES
. $np, 0755, true);
927 if (!file_exists(VAR_FILES
. $np . $md5)) {
928 rename($p, VAR_FILES
. $np . $md5);
931 /* Increment or create count file. */
933 if (file_exists(VAR_FILES
. $np . $md5 . '_count')) {
934 $content = file(VAR_FILES
. $np . $md5. '_count');
935 $counter = trim($content[0]);
938 $handle = fopen(VAR_FILES
. $np . $md5. '_count', 'w');
939 fwrite($handle, $counter);
943 $link_tmp_name = VAR_LINKS
. $md5 . rand(0, 10000) . '.tmp';
944 $handle = fopen($link_tmp_name, 'w');
946 $a['file_name'] . NL
. $a['mime_type'] . NL
. $size . NL
.
947 $a['key'] . NL
. $a['time'] . NL
. $md5 . NL
. $a['onetime'] . NL
.
948 time() . NL
. $a['ip'] . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
950 $md5_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
951 $l = s2p("$md5_link");
952 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
953 !rename($link_tmp_name, VAR_LINKS
. $l . $md5_link)) {
957 /* Clean async upload. */
958 jirafeau_async_delete($ref);
959 return $md5_link . NL
. $delete_link_code . NL
. urlencode($crypt_key);
962 function jirafeau_crypt_create_iv($base, $size)
965 while (strlen($iv) < $size) {
968 $iv = substr($iv, 0, $size);
973 * Crypt file and returns decrypt key.
974 * @param $fp_src file path to the file to crypt.
975 * @param $fp_dst file path to the file to write crypted file (could be the same).
976 * @return decrypt key composed of the key and the iv separated by a point ('.')
978 function jirafeau_encrypt_file($fp_src, $fp_dst)
980 $fs = filesize($fp_src);
981 if ($fs === false ||
$fs == 0 ||
!(extension_loaded('mcrypt') == true)) {
985 /* Prepare module. */
986 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
988 $crypt_key = jirafeau_gen_random(10);
989 $md5_key = md5($crypt_key);
990 $iv = jirafeau_crypt_create_iv($md5_key, mcrypt_enc_get_iv_size($m));
992 mcrypt_generic_init($m, $md5_key, $iv);
994 $r = fopen($fp_src, 'r');
995 $w = fopen($fp_dst, 'c');
997 $enc = mcrypt_generic($m, fread($r, 1024));
998 if (fwrite($w, $enc) === false) {
1005 mcrypt_generic_deinit($m);
1006 mcrypt_module_close($m);
1012 * @param $fp_src file path to the file to decrypt.
1013 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1014 * @param $k string composed of the key and the iv separated by a point ('.')
1015 * @return key used to decrypt. a string of length 0 is returned if failed.
1017 function jirafeau_decrypt_file($fp_src, $fp_dst, $k)
1019 $fs = filesize($fp_src);
1020 if ($fs === false ||
$fs == 0 ||
extension_loaded('mcrypt') == false) {
1025 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1026 /* Extract key and iv. */
1028 $md5_key = md5($crypt_key);
1029 $iv = jirafeau_crypt_create_iv($md5_key, mcrypt_enc_get_iv_size($m));
1031 $r = fopen($fp_src, 'r');
1032 $w = fopen($fp_dst, 'c');
1034 $dec = mdecrypt_generic($m, fread($r, 1024));
1035 if (fwrite($w, $dec) === false) {
1042 mcrypt_generic_deinit($m);
1043 mcrypt_module_close($m);
1048 * Check if Jirafeau is password protected for visitors.
1049 * @return true if Jirafeau is password protected, false otherwise.
1051 function jirafeau_has_upload_password($cfg)
1053 return count($cfg['upload_password']) > 0;
1057 * Challenge password for a visitor.
1058 * @param $password password to be challenged
1059 * @return true if password is valid, false otherwise.
1061 function jirafeau_challenge_upload_password($cfg, $password)
1063 if (!jirafeau_has_upload_password($cfg)) {
1066 foreach ($cfg['upload_password'] as $p) {
1067 if ($password == $p) {
1075 * Test if visitor's IP is authorized to upload.
1077 * @param $allowedIpList array of allowed IPs
1078 * @param $challengedIp IP to be challenged
1079 * @return true if IP is authorized, false otherwise.
1081 function jirafeau_challenge_upload_ip($allowedIpList, $challengedIp)
1083 // skip if list is empty = all IPs allowed
1084 if (count($allowedIpList) == 0) {
1087 // test given IP against each allowed IP
1088 foreach ($allowedIpList as $i) {
1089 if ($i == $challengedIp) {
1092 // CIDR test for IPv4 only.
1093 if (strpos($i, '/') !== false) {
1094 list($subnet, $mask) = explode('/', $i);
1095 if ((ip2long($challengedIp) & ~
((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
1104 * Test if visitor's IP is authorized or password is supplied and authorized
1105 * @param $ip IP to be challenged
1106 * @param $password password to be challenged
1107 * @return true if access is valid, false otherwise.
1109 function jirafeau_challenge_upload ($cfg, $ip, $password)
1111 // Allow if no ip restrictaion and no password restriction
1112 if ((count ($cfg['upload_ip']) == 0) and (count ($cfg['upload_password']) == 0)) {
1116 // Allow if ip is in array
1117 foreach ($cfg['upload_ip'] as $i) {
1121 // CIDR test for IPv4 only.
1122 if (strpos ($i, '/') !== false)
1124 list ($subnet, $mask) = explode('/', $i);
1125 if ((ip2long ($ip) & ~
((1 << (32 - $mask)) - 1) ) == ip2long ($subnet)) {
1130 if (!jirafeau_has_upload_password($cfg)) {
1134 foreach ($cfg['upload_password'] as $p) {
1135 if ($password == $p) {
1142 /** Tell if we have some HTTP headers generated by a proxy */
1143 function has_http_forwarded()
1146 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1147 !empty($_SERVER['http_X_forwarded_for']);
1151 * Generate IP list from HTTP headers generated by a proxy
1152 * @return array of IP strings
1154 function get_ip_list_http_forwarded()
1157 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1158 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1162 foreach ($l as $ip) {
1163 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1166 if (!empty($_SERVER['http_X_forwarded_for'])) {
1167 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1168 foreach ($l as $ip) {
1169 // Separate IP from port
1170 $ipa = explode(':', $ip);
1171 if ($ipa === false) {
1175 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1182 * Get the ip address of the client from REMOTE_ADDR
1183 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1184 * @returns the client ip address
1186 function get_ip_address($cfg)
1188 $remote = $_SERVER['REMOTE_ADDR'];
1189 if (count($cfg['proxy_ip']) == 0 ||
!has_http_forwarded()) {
1193 $ip_list = get_ip_list_http_forwarded();
1194 if (count($ip_list) == 0) {
1198 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1199 if ($remote != $proxy_ip) {
1202 // Take the last IP (the one which has been set by the defined proxy).
1203 return end($ip_list);
1209 * Convert hexadecimal string to base64
1211 function hex_to_base64($hex)
1214 foreach (str_split($hex, 2) as $pair) {
1215 $b .= chr(hexdec($pair));
1217 return base64_encode($b);
1221 * Replace markers in templates.
1223 * Available markers have the scheme "###MARKERNAME###".
1225 * @param $content string Template text with markers
1226 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1227 * @return Template with replaced markers
1229 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1232 '/###ORGANISATION###/',
1233 '/###CONTACTPERSON###/',
1236 $replacements = array(
1237 $GLOBALS['cfg']['organisation'],
1238 $GLOBALS['cfg']['contactperson'],
1239 $GLOBALS['cfg']['web_root']
1241 $content = preg_replace($patterns, $replacements, $content);
1243 if (true === $htmllinebreaks) {
1244 $content = nl2br($content);
1250 function jirafeau_escape($string)
1252 return htmlspecialchars($string, ENT_QUOTES
);
1255 function jirafeau_admin_session_start()
1257 $_SESSION['admin_auth'] = true;
1258 $_SESSION['admin_csrf'] = md5(uniqid(mt_rand(), true));
1261 function jirafeau_admin_session_end()
1263 $_SESSION = array();
1267 function jirafeau_admin_session_logged()
1269 return isset($_SESSION['admin_auth']) &&
1270 isset($_SESSION['admin_csrf']) &&
1271 isset($_POST['admin_csrf']) &&
1272 $_SESSION['admin_auth'] === true &&
1273 $_SESSION['admin_csrf'] === $_POST['admin_csrf'];
1276 function jirafeau_admin_csrf_field()
1278 return "<input type='hidden' name='admin_csrf' value='". $_SESSION['admin_csrf'] . "'/>";
patrick-canterino.de