]>
git.p6c8.net - jirafeau_mojo42.git/blob - lib/functions.php
01d0638d2db57e4a587959375aaa98530ab0c7e5
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(jirafeau_get_max_upload_size_bytes());
220 * gets a string explaining the error
221 * @param $code the error code
222 * @returns a string explaining the error
224 function jirafeau_upload_errstr($code)
227 case UPLOAD_ERR_INI_SIZE
:
228 case UPLOAD_ERR_FORM_SIZE
:
229 return t('Your file exceeds the maximum authorized file size. ');
231 case UPLOAD_ERR_PARTIAL
:
232 case UPLOAD_ERR_NO_FILE
:
234 t('Your file was not uploaded correctly. You may succeed in retrying. ');
236 case UPLOAD_ERR_NO_TMP_DIR
:
237 case UPLOAD_ERR_CANT_WRITE
:
238 case UPLOAD_ERR_EXTENSION
:
239 return t('Internal error. You may not succeed in retrying. ');
241 return t('Unknown error. ');
244 /** Remove link and it's file
245 * @param $link the link's name (hash)
248 function jirafeau_delete_link($link)
250 $l = jirafeau_get_link($link);
255 jirafeau_clean_rm_link($link);
261 if (file_exists(VAR_FILES
. $p . $md5. '_count')) {
262 $content = file(VAR_FILES
. $p . $md5. '_count');
263 $counter = trim($content[0]);
268 $handle = fopen(VAR_FILES
. $p . $md5. '_count', 'w');
269 fwrite($handle, $counter);
274 jirafeau_clean_rm_file($md5);
279 * Delete a file and it's links.
281 function jirafeau_delete_file($md5)
284 /* Get all links files. */
285 $stack = array(VAR_LINKS
);
286 while (($d = array_shift($stack)) && $d != null) {
289 foreach ($dir as $node) {
290 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
291 preg_match('/\.tmp/i', "$node")) {
295 if (is_dir($d . $node)) {
296 /* Push new found directory. */
297 $stack[] = $d . $node . '/';
298 } elseif (is_file($d . $node)) {
299 /* Read link informations. */
300 $l = jirafeau_get_link(basename($node));
304 if ($l['md5'] == $md5) {
306 jirafeau_delete_link($node);
311 jirafeau_clean_rm_file($md5);
316 * handles an uploaded file
317 * @param $file the file struct given by $_FILE[]
318 * @param $one_time_download is the file a one time download ?
319 * @param $key if not empty, protect the file with this key
320 * @param $time the time of validity of the file
321 * @param $ip uploader's ip
322 * @param $crypt boolean asking to crypt or not
323 * @param $link_name_length size of the link name
324 * @returns an array containing some information
325 * 'error' => information on possible errors
326 * 'link' => the link name of the uploaded file
327 * 'delete_link' => the link code to delete file
329 function jirafeau_upload($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length)
331 if (empty($file['tmp_name']) ||
!is_uploaded_file($file['tmp_name'])) {
334 array('has_error' => true,
335 'why' => jirafeau_upload_errstr($file['error'])),
337 'delete_link' => ''));
340 /* array representing no error */
341 $noerr = array('has_error' => false, 'why' => '');
343 /* Crypt file if option is enabled. */
346 if ($crypt == true && !(extension_loaded('mcrypt') == true)) {
347 error_log("PHP extension mcrypt not loaded, won't encrypt in Jirafeau");
349 if ($crypt == true && extension_loaded('mcrypt') == true) {
350 $crypt_key = jirafeau_encrypt_file($file['tmp_name'], $file['tmp_name']);
351 if (strlen($crypt_key) > 0) {
356 /* file informations */
357 $md5 = md5_file($file['tmp_name']);
358 $name = str_replace(NL
, '', trim($file['name']));
359 $mime_type = $file['type'];
360 $size = $file['size'];
362 /* does file already exist ? */
365 if (file_exists(VAR_FILES
. $p . $md5)) {
366 $rc = unlink($file['tmp_name']);
367 } elseif ((file_exists(VAR_FILES
. $p) || @mkdir
(VAR_FILES
. $p, 0755, true))
368 && move_uploaded_file($file['tmp_name'], VAR_FILES
. $p . $md5)) {
374 array('has_error' => true,
375 'why' => t('INTERNAL_ERROR_DEL')),
377 'delete_link' => ''));
380 /* Increment or create count file. */
382 if (file_exists(VAR_FILES
. $p . $md5 . '_count')) {
383 $content = file(VAR_FILES
. $p . $md5. '_count');
384 $counter = trim($content[0]);
387 $handle = fopen(VAR_FILES
. $p . $md5. '_count', 'w');
388 fwrite($handle, $counter);
391 /* Create delete code. */
392 $delete_link_code = jirafeau_gen_random(5);
394 /* md5 password or empty. */
397 $password = md5($key);
400 /* create link file */
401 $link_tmp_name = VAR_LINKS
. $md5 . rand(0, 10000) . '.tmp';
402 $handle = fopen($link_tmp_name, 'w');
404 $name . NL
. $mime_type . NL
. $size . NL
. $password . NL
. $time .
405 NL
. $md5. NL
. ($one_time_download ?
'O' : 'R') . NL
. time() .
406 NL
. $ip . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
408 $md5_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
409 $l = s2p("$md5_link");
410 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
411 !rename($link_tmp_name, VAR_LINKS
. $l . $md5_link)) {
412 if (file_exists($link_tmp_name)) {
413 unlink($link_tmp_name);
418 $handle = fopen(VAR_FILES
. $p . $md5. '_count', 'w');
419 fwrite($handle, $counter);
422 jirafeau_clean_rm_file($md5_link);
426 array('has_error' => true,
427 'why' => t('Internal error during file creation. ')),
429 'delete_link' => '');
431 return array( 'error' => $noerr,
433 'delete_link' => $delete_link_code,
434 'crypt_key' => $crypt_key);
438 * Tells if a mime-type is viewable in a browser
439 * @param $mime the mime type
440 * @returns a boolean telling if a mime type is viewable
442 function jirafeau_is_viewable($mime)
445 /* Actually, verify if mime-type is an image or a text. */
446 $viewable = array('image', 'text', 'video', 'audio');
447 $decomposed = explode('/', $mime);
448 return in_array($decomposed[0], $viewable);
453 // Error handling functions.
454 //! Global array that contains all registered errors.
455 $error_list = array();
458 * Adds an error to the list of errors.
459 * @param $title the error's title
460 * @param $description is a human-friendly description of the problem.
462 function add_error($title, $description)
465 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
469 * Informs whether any error has been registered yet.
470 * @return true if there are errors.
475 return !empty($error_list);
479 * Displays all the errors.
481 function show_errors()
485 echo '<div class="error">';
486 foreach ($error_list as $error) {
493 function check_errors($cfg)
495 if (file_exists(JIRAFEAU_ROOT
. 'install.php')
496 && !($cfg['installation_done'] === true)) {
497 header('Location: install.php');
501 /* check if the destination dirs are writable */
502 $writable = is_writable(VAR_FILES
) && is_writable(VAR_LINKS
);
504 /* Checking for errors. */
505 if (!is_writable(VAR_FILES
)) {
506 add_error(t('The file directory is not writable!'), VAR_FILES
);
509 if (!is_writable(VAR_LINKS
)) {
510 add_error(t('The link directory is not writable!'), VAR_LINKS
);
513 if (!is_writable(VAR_ASYNC
)) {
514 add_error(t('ASYNC_DIR_W'), VAR_ASYNC
);
519 * Read link informations
520 * @return array containing informations.
522 function jirafeau_get_link($hash)
525 $link = VAR_LINKS
. s2p("$hash") . $hash;
527 if (!file_exists($link)) {
532 $out['file_name'] = trim($c[0]);
533 $out['mime_type'] = trim($c[1]);
534 $out['file_size'] = trim($c[2]);
535 $out['key'] = trim($c[3], NL
);
536 $out['time'] = trim($c[4]);
537 $out['md5'] = trim($c[5]);
538 $out['onetime'] = trim($c[6]);
539 $out['upload_date'] = trim($c[7]);
540 $out['ip'] = trim($c[8]);
541 $out['link_code'] = trim($c[9]);
542 $out['crypted'] = trim($c[10]) == 'C';
548 * List files in admin interface.
550 function jirafeau_admin_list($name, $file_hash, $link_hash)
552 echo '<fieldset><legend>';
554 echo t('FILENAME') . ": " . jirafeau_escape($name);
556 if (!empty($file_hash)) {
557 echo t('FILE') . ": " . jirafeau_escape($file_hash);
559 if (!empty($link_hash)) {
560 echo t('LINK') . ": " . jirafeau_escape($link_hash);
562 if (empty($name) && empty($file_hash) && empty($link_hash)) {
568 echo '<td>' . t('FILENAME') . '</td>';
569 echo '<td>' . t('TYPE') . '</td>';
570 echo '<td>' . t('SIZE') . '</td>';
571 echo '<td>' . t('EXPIRE') . '</td>';
572 echo '<td>' . t('ONETIME') . '</td>';
573 echo '<td>' . t('UPLOAD_DATE') . '</td>';
574 echo '<td>' . t('ORIGIN') . '</td>';
575 echo '<td>' . t('ACTION') . '</td>';
578 /* Get all links files. */
579 $stack = array(VAR_LINKS
);
580 while (($d = array_shift($stack)) && $d != null) {
582 foreach ($dir as $node) {
583 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
584 preg_match('/\.tmp/i', "$node")) {
587 if (is_dir($d . $node)) {
588 /* Push new found directory. */
589 $stack[] = $d . $node . '/';
590 } elseif (is_file($d . $node)) {
591 /* Read link informations. */
592 $l = jirafeau_get_link($node);
598 if (!empty($name) && !@preg_match
("/$name/i", jirafeau_escape($l['file_name']))) {
601 if (!empty($file_hash) && $file_hash != $l['md5']) {
604 if (!empty($link_hash) && $link_hash != $node) {
607 /* Print link informations. */
610 '<strong><a id="upload_link" href="f.php?h='. jirafeau_escape($node) .'" title="' .
611 t('DL_PAGE') . '">' . jirafeau_escape($l['file_name']) . '</a></strong>';
613 echo '<td>' . jirafeau_escape($l['mime_type']) . '</td>';
614 echo '<td>' . jirafeau_human_size($l['file_size']) . '</td>';
615 echo '<td>' . ($l['time'] == -1 ?
'∞' : jirafeau_get_datetimefield($l['time'])) . '</td>';
617 if ($l['onetime'] == 'O') {
623 echo '<td>' . jirafeau_get_datetimefield($l['upload_date']) . '</td>';
624 echo '<td>' . $l['ip'] . '</td>';
626 '<form method="post">' .
627 '<input type = "hidden" name = "action" value = "download"/>' .
628 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
629 jirafeau_admin_csrf_field() .
630 '<input type = "submit" value = "' . t('DL') . '" />' .
632 '<form method="post">' .
633 '<input type = "hidden" name = "action" value = "delete_link"/>' .
634 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
635 jirafeau_admin_csrf_field() .
636 '<input type = "submit" value = "' . t('DEL_LINK') . '" />' .
638 '<form method="post">' .
639 '<input type = "hidden" name = "action" value = "delete_file"/>' .
640 '<input type = "hidden" name = "md5" value = "' . $l['md5'] . '"/>' .
641 jirafeau_admin_csrf_field() .
642 '<input type = "submit" value = "' . t('DEL_FILE_LINKS') . '" />' .
649 echo '</table></fieldset>';
653 * Clean expired files.
654 * @return number of cleaned files.
656 function jirafeau_admin_clean()
659 /* Get all links files. */
660 $stack = array(VAR_LINKS
);
661 while (($d = array_shift($stack)) && $d != null) {
664 foreach ($dir as $node) {
665 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
666 preg_match('/\.tmp/i', "$node")) {
670 if (is_dir($d . $node)) {
671 /* Push new found directory. */
672 $stack[] = $d . $node . '/';
673 } elseif (is_file($d . $node)) {
674 /* Read link informations. */
675 $l = jirafeau_get_link(basename($node));
680 if ($l['time'] > 0 && $l['time'] < time() ||
// expired
681 !file_exists(VAR_FILES
. $p . $l['md5']) ||
// invalid
682 !file_exists(VAR_FILES
. $p . $l['md5'] . '_count')) { // invalid
683 jirafeau_delete_link($node);
694 * Clean old async transferts.
695 * @return number of cleaned files.
697 function jirafeau_admin_clean_async()
700 /* Get all links files. */
701 $stack = array(VAR_ASYNC
);
702 while (($d = array_shift($stack)) && $d != null) {
705 foreach ($dir as $node) {
706 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
707 preg_match('/\.tmp/i', "$node")) {
711 if (is_dir($d . $node)) {
712 /* Push new found directory. */
713 $stack[] = $d . $node . '/';
714 } elseif (is_file($d . $node)) {
715 /* Read async informations. */
716 $a = jirafeau_get_async_ref(basename($node));
720 /* Delete transferts older than 1 hour. */
721 if (time() - $a['last_edited'] > 3600) {
722 jirafeau_async_delete(basename($node));
731 * Read async transfert informations
732 * @return array containing informations.
734 function jirafeau_get_async_ref($ref)
737 $refinfos = VAR_ASYNC
. s2p("$ref") . "$ref";
739 if (!file_exists($refinfos)) {
743 $c = file($refinfos);
744 $out['file_name'] = trim($c[0]);
745 $out['mime_type'] = trim($c[1]);
746 $out['key'] = trim($c[2], NL
);
747 $out['time'] = trim($c[3]);
748 $out['onetime'] = trim($c[4]);
749 $out['ip'] = trim($c[5]);
750 $out['last_edited'] = trim($c[6]);
751 $out['next_code'] = trim($c[7]);
756 * Delete async transfert informations
758 function jirafeau_async_delete($ref)
761 if (file_exists(VAR_ASYNC
. $p . $ref)) {
762 unlink(VAR_ASYNC
. $p . $ref);
764 if (file_exists(VAR_ASYNC
. $p . $ref . '_data')) {
765 unlink(VAR_ASYNC
. $p . $ref . '_data');
767 $parse = VAR_ASYNC
. $p;
769 while (file_exists($parse)
770 && ($scan = scandir($parse))
771 && count($scan) == 2 // '.' and '..' folders => empty.
772 && basename($parse) != basename(VAR_ASYNC
)) {
774 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
779 * Init a new asynchronous upload.
780 * @param $finename Name of the file to send
781 * @param $one_time One time upload parameter
782 * @param $key eventual password (or blank)
783 * @param $time time limit
784 * @param $ip ip address of the client
785 * @return a string containing a temporary reference followed by a code or the string 'Error'
787 function jirafeau_async_init($filename, $type, $one_time, $key, $time, $ip)
791 /* Create temporary folder. */
794 $code = jirafeau_gen_random(4);
796 $ref = jirafeau_gen_random(32);
797 $p = VAR_ASYNC
. s2p($ref);
798 } while (file_exists($p));
799 @mkdir
($p, 0755, true);
800 if (!file_exists($p)) {
805 /* md5 password or empty */
808 $password = md5($key);
811 /* Store informations. */
813 $handle = fopen($p, 'w');
815 str_replace(NL
, '', trim($filename)) . NL
.
816 str_replace(NL
, '', trim($type)) . NL
. $password . NL
.
817 $time . NL
. ($one_time ?
'O' : 'R') . NL
. $ip . NL
.
818 time() . NL
. $code . NL
);
821 return $ref . NL
. $code ;
825 * Append a piece of file on the asynchronous upload.
826 * @param $ref asynchronous upload reference
827 * @param $file piece of data
828 * @param $code client code for this operation
829 * @param $max_file_size maximum allowed file size
830 * @return a string containing a next code to use or the string "Error"
832 function jirafeau_async_push($ref, $data, $code, $max_file_size)
834 /* Get async infos. */
835 $a = jirafeau_get_async_ref($ref);
837 /* Check some errors. */
839 ||
$a['next_code'] != "$code"
840 ||
empty($data['tmp_name'])
841 ||
!is_uploaded_file($data['tmp_name'])) {
848 $r_path = $data['tmp_name'];
849 $w_path = VAR_ASYNC
. $p . $ref . '_data';
851 /* Check that file size is not above upload limit. */
852 if ($max_file_size > 0 &&
853 filesize($r_path) +
filesize($w_path) > $max_file_size * 1024 * 1024) {
854 jirafeau_async_delete($ref);
858 /* Concatenate data. */
859 $r = fopen($r_path, 'r');
860 $w = fopen($w_path, 'a');
862 if (fwrite($w, fread($r, 1024)) === false) {
865 jirafeau_async_delete($ref);
873 /* Update async file. */
874 $code = jirafeau_gen_random(4);
875 $handle = fopen(VAR_ASYNC
. $p . $ref, 'w');
877 $a['file_name'] . NL
. $a['mime_type'] . NL
. $a['key'] . NL
.
878 $a['time'] . NL
. $a['onetime'] . NL
. $a['ip'] . NL
.
879 time() . NL
. $code . NL
);
885 * Finalyze an asynchronous upload.
886 * @param $ref asynchronous upload reference
887 * @param $code client code for this operation
888 * @param $crypt boolean asking to crypt or not
889 * @param $link_name_length link name length
890 * @return a string containing the download reference followed by a delete code or the string 'Error'
892 function jirafeau_async_end($ref, $code, $crypt, $link_name_length)
894 /* Get async infos. */
895 $a = jirafeau_get_async_ref($ref);
897 ||
$a['next_code'] != "$code") {
901 /* Generate link infos. */
902 $p = VAR_ASYNC
. s2p($ref) . $ref . "_data";
903 if (!file_exists($p)) {
909 if ($crypt == true && extension_loaded('mcrypt') == true) {
910 $crypt_key = jirafeau_encrypt_file($p, $p);
911 if (strlen($crypt_key) > 0) {
917 $size = filesize($p);
919 $delete_link_code = jirafeau_gen_random(5);
921 /* File already exist ? */
922 if (!file_exists(VAR_FILES
. $np)) {
923 @mkdir
(VAR_FILES
. $np, 0755, true);
925 if (!file_exists(VAR_FILES
. $np . $md5)) {
926 rename($p, VAR_FILES
. $np . $md5);
929 /* Increment or create count file. */
931 if (file_exists(VAR_FILES
. $np . $md5 . '_count')) {
932 $content = file(VAR_FILES
. $np . $md5. '_count');
933 $counter = trim($content[0]);
936 $handle = fopen(VAR_FILES
. $np . $md5. '_count', 'w');
937 fwrite($handle, $counter);
941 $link_tmp_name = VAR_LINKS
. $md5 . rand(0, 10000) . '.tmp';
942 $handle = fopen($link_tmp_name, 'w');
944 $a['file_name'] . NL
. $a['mime_type'] . NL
. $size . NL
.
945 $a['key'] . NL
. $a['time'] . NL
. $md5 . NL
. $a['onetime'] . NL
.
946 time() . NL
. $a['ip'] . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
948 $md5_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
949 $l = s2p("$md5_link");
950 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
951 !rename($link_tmp_name, VAR_LINKS
. $l . $md5_link)) {
955 /* Clean async upload. */
956 jirafeau_async_delete($ref);
957 return $md5_link . NL
. $delete_link_code . NL
. urlencode($crypt_key);
960 function jirafeau_crypt_create_iv($base, $size)
963 while (strlen($iv) < $size) {
966 $iv = substr($iv, 0, $size);
971 * Crypt file and returns decrypt key.
972 * @param $fp_src file path to the file to crypt.
973 * @param $fp_dst file path to the file to write crypted file (could be the same).
974 * @return decrypt key composed of the key and the iv separated by a point ('.')
976 function jirafeau_encrypt_file($fp_src, $fp_dst)
978 $fs = filesize($fp_src);
979 if ($fs === false ||
$fs == 0 ||
!(extension_loaded('mcrypt') == true)) {
983 /* Prepare module. */
984 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
986 $crypt_key = jirafeau_gen_random(10);
987 $md5_key = md5($crypt_key);
988 $iv = jirafeau_crypt_create_iv($md5_key, mcrypt_enc_get_iv_size($m));
990 mcrypt_generic_init($m, $md5_key, $iv);
992 $r = fopen($fp_src, 'r');
993 $w = fopen($fp_dst, 'c');
995 $enc = mcrypt_generic($m, fread($r, 1024));
996 if (fwrite($w, $enc) === false) {
1003 mcrypt_generic_deinit($m);
1004 mcrypt_module_close($m);
1010 * @param $fp_src file path to the file to decrypt.
1011 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1012 * @param $k string composed of the key and the iv separated by a point ('.')
1013 * @return key used to decrypt. a string of length 0 is returned if failed.
1015 function jirafeau_decrypt_file($fp_src, $fp_dst, $k)
1017 $fs = filesize($fp_src);
1018 if ($fs === false ||
$fs == 0 ||
extension_loaded('mcrypt') == false) {
1023 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1024 /* Extract key and iv. */
1026 $md5_key = md5($crypt_key);
1027 $iv = jirafeau_crypt_create_iv($md5_key, mcrypt_enc_get_iv_size($m));
1029 $r = fopen($fp_src, 'r');
1030 $w = fopen($fp_dst, 'c');
1032 $dec = mdecrypt_generic($m, fread($r, 1024));
1033 if (fwrite($w, $dec) === false) {
1040 mcrypt_generic_deinit($m);
1041 mcrypt_module_close($m);
1046 * Check if Jirafeau is password protected for visitors.
1047 * @return true if Jirafeau is password protected, false otherwise.
1049 function jirafeau_has_upload_password($cfg)
1051 return count($cfg['upload_password']) > 0;
1055 * Challenge password for a visitor.
1056 * @param $password password to be challenged
1057 * @return true if password is valid, false otherwise.
1059 function jirafeau_challenge_upload_password($cfg, $password)
1061 if (!jirafeau_has_upload_password($cfg)) {
1064 foreach ($cfg['upload_password'] as $p) {
1065 if ($password == $p) {
1073 * Test if visitor's IP is authorized to upload.
1075 * @param $allowedIpList array of allowed IPs
1076 * @param $challengedIp IP to be challenged
1077 * @return true if IP is authorized, false otherwise.
1079 function jirafeau_challenge_upload_ip($allowedIpList, $challengedIp)
1081 // skip if list is empty = all IPs allowed
1082 if (count($allowedIpList) == 0) {
1085 // test given IP against each allowed IP
1086 foreach ($allowedIpList as $i) {
1087 if ($i == $challengedIp) {
1090 // CIDR test for IPv4 only.
1091 if (strpos($i, '/') !== false) {
1092 list($subnet, $mask) = explode('/', $i);
1093 if ((ip2long($challengedIp) & ~
((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
1102 * Test if visitor's IP is authorized or password is supplied and authorized
1103 * @param $ip IP to be challenged
1104 * @param $password password to be challenged
1105 * @return true if access is valid, false otherwise.
1107 function jirafeau_challenge_upload ($cfg, $ip, $password)
1109 // Allow if no ip restrictaion and no password restriction
1110 if ((count ($cfg['upload_ip']) == 0) and (count ($cfg['upload_password']) == 0)) {
1114 // Allow if ip is in array
1115 foreach ($cfg['upload_ip'] as $i) {
1119 // CIDR test for IPv4 only.
1120 if (strpos ($i, '/') !== false)
1122 list ($subnet, $mask) = explode('/', $i);
1123 if ((ip2long ($ip) & ~
((1 << (32 - $mask)) - 1) ) == ip2long ($subnet)) {
1128 if (!jirafeau_has_upload_password($cfg)) {
1132 foreach ($cfg['upload_password'] as $p) {
1133 if ($password == $p) {
1140 /** Tell if we have some HTTP headers generated by a proxy */
1141 function has_http_forwarded()
1144 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1145 !empty($_SERVER['http_X_forwarded_for']);
1149 * Generate IP list from HTTP headers generated by a proxy
1150 * @return array of IP strings
1152 function get_ip_list_http_forwarded()
1155 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1156 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1160 foreach ($l as $ip) {
1161 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1164 if (!empty($_SERVER['http_X_forwarded_for'])) {
1165 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1166 foreach ($l as $ip) {
1167 // Separate IP from port
1168 $ipa = explode(':', $ip);
1169 if ($ipa === false) {
1173 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1180 * Get the ip address of the client from REMOTE_ADDR
1181 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1182 * @returns the client ip address
1184 function get_ip_address($cfg)
1186 $remote = $_SERVER['REMOTE_ADDR'];
1187 if (count($cfg['proxy_ip']) == 0 ||
!has_http_forwarded()) {
1191 $ip_list = get_ip_list_http_forwarded();
1192 if (count($ip_list) == 0) {
1196 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1197 if ($remote != $proxy_ip) {
1200 // Take the last IP (the one which has been set by the defined proxy).
1201 return end($ip_list);
1207 * Convert hexadecimal string to base64
1209 function hex_to_base64($hex)
1212 foreach (str_split($hex, 2) as $pair) {
1213 $b .= chr(hexdec($pair));
1215 return base64_encode($b);
1219 * Replace markers in templates.
1221 * Available markers have the scheme "###MARKERNAME###".
1223 * @param $content string Template text with markers
1224 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1225 * @return Template with replaced markers
1227 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1230 '/###ORGANISATION###/',
1231 '/###CONTACTPERSON###/',
1234 $replacements = array(
1235 $GLOBALS['cfg']['organisation'],
1236 $GLOBALS['cfg']['contactperson'],
1237 $GLOBALS['cfg']['web_root']
1239 $content = preg_replace($patterns, $replacements, $content);
1241 if (true === $htmllinebreaks) {
1242 $content = nl2br($content);
1248 function jirafeau_escape($string)
1250 return htmlspecialchars($string, ENT_QUOTES
);
1253 function jirafeau_admin_session_start()
1255 $_SESSION['admin_auth'] = true;
1256 $_SESSION['admin_csrf'] = md5(uniqid(mt_rand(), true));
1259 function jirafeau_admin_session_end()
1261 $_SESSION = array();
1265 function jirafeau_admin_session_logged()
1267 return isset($_SESSION['admin_auth']) &&
1268 isset($_SESSION['admin_csrf']) &&
1269 isset($_POST['admin_csrf']) &&
1270 $_SESSION['admin_auth'] === true &&
1271 $_SESSION['admin_csrf'] === $_POST['admin_csrf'];
1274 function jirafeau_admin_csrf_field()
1276 return "<input type='hidden' name='admin_csrf' value='". $_SESSION['admin_csrf'] . "'/>";
patrick-canterino.de