]>
git.p6c8.net - jirafeau.git/blob - lib/functions.php
2817aa1e241b543ab782dc20ed7669e3172182c5
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 /* Checking for errors. */
502 if (!is_writable(VAR_FILES
)) {
503 add_error(t('FILE_DIR_W'), VAR_FILES
);
506 if (!is_writable(VAR_LINKS
)) {
507 add_error(t('LINK_DIR_W'), VAR_LINKS
);
510 if (!is_writable(VAR_ASYNC
)) {
511 add_error(t('ASYNC_DIR_W'), VAR_ASYNC
);
516 * Read link informations
517 * @return array containing informations.
519 function jirafeau_get_link($hash)
522 $link = VAR_LINKS
. s2p("$hash") . $hash;
524 if (!file_exists($link)) {
529 $out['file_name'] = trim($c[0]);
530 $out['mime_type'] = trim($c[1]);
531 $out['file_size'] = trim($c[2]);
532 $out['key'] = trim($c[3], NL
);
533 $out['time'] = trim($c[4]);
534 $out['md5'] = trim($c[5]);
535 $out['onetime'] = trim($c[6]);
536 $out['upload_date'] = trim($c[7]);
537 $out['ip'] = trim($c[8]);
538 $out['link_code'] = trim($c[9]);
539 $out['crypted'] = trim($c[10]) == 'C';
545 * List files in admin interface.
547 function jirafeau_admin_list($name, $file_hash, $link_hash)
549 echo '<fieldset><legend>';
551 echo t('FILENAME') . ": " . jirafeau_escape($name);
553 if (!empty($file_hash)) {
554 echo t('FILE') . ": " . jirafeau_escape($file_hash);
556 if (!empty($link_hash)) {
557 echo t('LINK') . ": " . jirafeau_escape($link_hash);
559 if (empty($name) && empty($file_hash) && empty($link_hash)) {
565 echo '<td>' . t('FILENAME') . '</td>';
566 echo '<td>' . t('TYPE') . '</td>';
567 echo '<td>' . t('SIZE') . '</td>';
568 echo '<td>' . t('EXPIRE') . '</td>';
569 echo '<td>' . t('ONETIME') . '</td>';
570 echo '<td>' . t('UPLOAD_DATE') . '</td>';
571 echo '<td>' . t('ORIGIN') . '</td>';
572 echo '<td>' . t('ACTION') . '</td>';
575 /* Get all links files. */
576 $stack = array(VAR_LINKS
);
577 while (($d = array_shift($stack)) && $d != null) {
579 foreach ($dir as $node) {
580 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
581 preg_match('/\.tmp/i', "$node")) {
584 if (is_dir($d . $node)) {
585 /* Push new found directory. */
586 $stack[] = $d . $node . '/';
587 } elseif (is_file($d . $node)) {
588 /* Read link informations. */
589 $l = jirafeau_get_link($node);
595 if (!empty($name) && !@preg_match
("/$name/i", jirafeau_escape($l['file_name']))) {
598 if (!empty($file_hash) && $file_hash != $l['md5']) {
601 if (!empty($link_hash) && $link_hash != $node) {
604 /* Print link informations. */
607 '<strong><a id="upload_link" href="f.php?h='. jirafeau_escape($node) .'" title="' .
608 t('DL_PAGE') . '">' . jirafeau_escape($l['file_name']) . '</a></strong>';
610 echo '<td>' . jirafeau_escape($l['mime_type']) . '</td>';
611 echo '<td>' . jirafeau_human_size($l['file_size']) . '</td>';
612 echo '<td>' . ($l['time'] == -1 ?
'∞' : jirafeau_get_datetimefield($l['time'])) . '</td>';
614 if ($l['onetime'] == 'O') {
620 echo '<td>' . jirafeau_get_datetimefield($l['upload_date']) . '</td>';
621 echo '<td>' . $l['ip'] . '</td>';
623 '<form method="post">' .
624 '<input type = "hidden" name = "action" value = "download"/>' .
625 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
626 jirafeau_admin_csrf_field() .
627 '<input type = "submit" value = "' . t('DL') . '" />' .
629 '<form method="post">' .
630 '<input type = "hidden" name = "action" value = "delete_link"/>' .
631 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
632 jirafeau_admin_csrf_field() .
633 '<input type = "submit" value = "' . t('DEL_LINK') . '" />' .
635 '<form method="post">' .
636 '<input type = "hidden" name = "action" value = "delete_file"/>' .
637 '<input type = "hidden" name = "md5" value = "' . $l['md5'] . '"/>' .
638 jirafeau_admin_csrf_field() .
639 '<input type = "submit" value = "' . t('DEL_FILE_LINKS') . '" />' .
646 echo '</table></fieldset>';
650 * Clean expired files.
651 * @return number of cleaned files.
653 function jirafeau_admin_clean()
656 /* Get all links files. */
657 $stack = array(VAR_LINKS
);
658 while (($d = array_shift($stack)) && $d != null) {
661 foreach ($dir as $node) {
662 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
663 preg_match('/\.tmp/i', "$node")) {
667 if (is_dir($d . $node)) {
668 /* Push new found directory. */
669 $stack[] = $d . $node . '/';
670 } elseif (is_file($d . $node)) {
671 /* Read link informations. */
672 $l = jirafeau_get_link(basename($node));
677 if ($l['time'] > 0 && $l['time'] < time() ||
// expired
678 !file_exists(VAR_FILES
. $p . $l['md5']) ||
// invalid
679 !file_exists(VAR_FILES
. $p . $l['md5'] . '_count')) { // invalid
680 jirafeau_delete_link($node);
691 * Clean old async transferts.
692 * @return number of cleaned files.
694 function jirafeau_admin_clean_async()
697 /* Get all links files. */
698 $stack = array(VAR_ASYNC
);
699 while (($d = array_shift($stack)) && $d != null) {
702 foreach ($dir as $node) {
703 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
704 preg_match('/\.tmp/i', "$node")) {
708 if (is_dir($d . $node)) {
709 /* Push new found directory. */
710 $stack[] = $d . $node . '/';
711 } elseif (is_file($d . $node)) {
712 /* Read async informations. */
713 $a = jirafeau_get_async_ref(basename($node));
717 /* Delete transferts older than 1 hour. */
718 if (time() - $a['last_edited'] > 3600) {
719 jirafeau_async_delete(basename($node));
728 * Read async transfert informations
729 * @return array containing informations.
731 function jirafeau_get_async_ref($ref)
734 $refinfos = VAR_ASYNC
. s2p("$ref") . "$ref";
736 if (!file_exists($refinfos)) {
740 $c = file($refinfos);
741 $out['file_name'] = trim($c[0]);
742 $out['mime_type'] = trim($c[1]);
743 $out['key'] = trim($c[2], NL
);
744 $out['time'] = trim($c[3]);
745 $out['onetime'] = trim($c[4]);
746 $out['ip'] = trim($c[5]);
747 $out['last_edited'] = trim($c[6]);
748 $out['next_code'] = trim($c[7]);
753 * Delete async transfert informations
755 function jirafeau_async_delete($ref)
758 if (file_exists(VAR_ASYNC
. $p . $ref)) {
759 unlink(VAR_ASYNC
. $p . $ref);
761 if (file_exists(VAR_ASYNC
. $p . $ref . '_data')) {
762 unlink(VAR_ASYNC
. $p . $ref . '_data');
764 $parse = VAR_ASYNC
. $p;
766 while (file_exists($parse)
767 && ($scan = scandir($parse))
768 && count($scan) == 2 // '.' and '..' folders => empty.
769 && basename($parse) != basename(VAR_ASYNC
)) {
771 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
776 * Init a new asynchronous upload.
777 * @param $finename Name of the file to send
778 * @param $one_time One time upload parameter
779 * @param $key eventual password (or blank)
780 * @param $time time limit
781 * @param $ip ip address of the client
782 * @return a string containing a temporary reference followed by a code or the string 'Error'
784 function jirafeau_async_init($filename, $type, $one_time, $key, $time, $ip)
788 /* Create temporary folder. */
791 $code = jirafeau_gen_random(4);
793 $ref = jirafeau_gen_random(32);
794 $p = VAR_ASYNC
. s2p($ref);
795 } while (file_exists($p));
796 @mkdir
($p, 0755, true);
797 if (!file_exists($p)) {
802 /* md5 password or empty */
805 $password = md5($key);
808 /* Store informations. */
810 $handle = fopen($p, 'w');
812 str_replace(NL
, '', trim($filename)) . NL
.
813 str_replace(NL
, '', trim($type)) . NL
. $password . NL
.
814 $time . NL
. ($one_time ?
'O' : 'R') . NL
. $ip . NL
.
815 time() . NL
. $code . NL
);
818 return $ref . NL
. $code ;
822 * Append a piece of file on the asynchronous upload.
823 * @param $ref asynchronous upload reference
824 * @param $file piece of data
825 * @param $code client code for this operation
826 * @param $max_file_size maximum allowed file size
827 * @return a string containing a next code to use or the string "Error"
829 function jirafeau_async_push($ref, $data, $code, $max_file_size)
831 /* Get async infos. */
832 $a = jirafeau_get_async_ref($ref);
834 /* Check some errors. */
836 ||
$a['next_code'] != "$code"
837 ||
empty($data['tmp_name'])
838 ||
!is_uploaded_file($data['tmp_name'])) {
845 $r_path = $data['tmp_name'];
846 $w_path = VAR_ASYNC
. $p . $ref . '_data';
848 /* Check that file size is not above upload limit. */
849 if ($max_file_size > 0 &&
850 filesize($r_path) +
filesize($w_path) > $max_file_size * 1024 * 1024) {
851 jirafeau_async_delete($ref);
855 /* Concatenate data. */
856 $r = fopen($r_path, 'r');
857 $w = fopen($w_path, 'a');
859 if (fwrite($w, fread($r, 1024)) === false) {
862 jirafeau_async_delete($ref);
870 /* Update async file. */
871 $code = jirafeau_gen_random(4);
872 $handle = fopen(VAR_ASYNC
. $p . $ref, 'w');
874 $a['file_name'] . NL
. $a['mime_type'] . NL
. $a['key'] . NL
.
875 $a['time'] . NL
. $a['onetime'] . NL
. $a['ip'] . NL
.
876 time() . NL
. $code . NL
);
882 * Finalyze an asynchronous upload.
883 * @param $ref asynchronous upload reference
884 * @param $code client code for this operation
885 * @param $crypt boolean asking to crypt or not
886 * @param $link_name_length link name length
887 * @return a string containing the download reference followed by a delete code or the string 'Error'
889 function jirafeau_async_end($ref, $code, $crypt, $link_name_length)
891 /* Get async infos. */
892 $a = jirafeau_get_async_ref($ref);
894 ||
$a['next_code'] != "$code") {
898 /* Generate link infos. */
899 $p = VAR_ASYNC
. s2p($ref) . $ref . "_data";
900 if (!file_exists($p)) {
906 if ($crypt == true && extension_loaded('mcrypt') == true) {
907 $crypt_key = jirafeau_encrypt_file($p, $p);
908 if (strlen($crypt_key) > 0) {
914 $size = filesize($p);
916 $delete_link_code = jirafeau_gen_random(5);
918 /* File already exist ? */
919 if (!file_exists(VAR_FILES
. $np)) {
920 @mkdir
(VAR_FILES
. $np, 0755, true);
922 if (!file_exists(VAR_FILES
. $np . $md5)) {
923 rename($p, VAR_FILES
. $np . $md5);
926 /* Increment or create count file. */
928 if (file_exists(VAR_FILES
. $np . $md5 . '_count')) {
929 $content = file(VAR_FILES
. $np . $md5. '_count');
930 $counter = trim($content[0]);
933 $handle = fopen(VAR_FILES
. $np . $md5. '_count', 'w');
934 fwrite($handle, $counter);
938 $link_tmp_name = VAR_LINKS
. $md5 . rand(0, 10000) . '.tmp';
939 $handle = fopen($link_tmp_name, 'w');
941 $a['file_name'] . NL
. $a['mime_type'] . NL
. $size . NL
.
942 $a['key'] . NL
. $a['time'] . NL
. $md5 . NL
. $a['onetime'] . NL
.
943 time() . NL
. $a['ip'] . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
945 $md5_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
946 $l = s2p("$md5_link");
947 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
948 !rename($link_tmp_name, VAR_LINKS
. $l . $md5_link)) {
952 /* Clean async upload. */
953 jirafeau_async_delete($ref);
954 return $md5_link . NL
. $delete_link_code . NL
. urlencode($crypt_key);
957 function jirafeau_crypt_create_iv($base, $size)
960 while (strlen($iv) < $size) {
963 $iv = substr($iv, 0, $size);
968 * Crypt file and returns decrypt key.
969 * @param $fp_src file path to the file to crypt.
970 * @param $fp_dst file path to the file to write crypted file (could be the same).
971 * @return decrypt key composed of the key and the iv separated by a point ('.')
973 function jirafeau_encrypt_file($fp_src, $fp_dst)
975 $fs = filesize($fp_src);
976 if ($fs === false ||
$fs == 0 ||
!(extension_loaded('mcrypt') == true)) {
980 /* Prepare module. */
981 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
983 $crypt_key = jirafeau_gen_random(10);
984 $md5_key = md5($crypt_key);
985 $iv = jirafeau_crypt_create_iv($md5_key, mcrypt_enc_get_iv_size($m));
987 mcrypt_generic_init($m, $md5_key, $iv);
989 $r = fopen($fp_src, 'r');
990 $w = fopen($fp_dst, 'c');
992 $enc = mcrypt_generic($m, fread($r, 1024));
993 if (fwrite($w, $enc) === false) {
1000 mcrypt_generic_deinit($m);
1001 mcrypt_module_close($m);
1007 * @param $fp_src file path to the file to decrypt.
1008 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1009 * @param $k string composed of the key and the iv separated by a point ('.')
1010 * @return key used to decrypt. a string of length 0 is returned if failed.
1012 function jirafeau_decrypt_file($fp_src, $fp_dst, $k)
1014 $fs = filesize($fp_src);
1015 if ($fs === false ||
$fs == 0 ||
extension_loaded('mcrypt') == false) {
1020 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1021 /* Extract key and iv. */
1023 $md5_key = md5($crypt_key);
1024 $iv = jirafeau_crypt_create_iv($md5_key, mcrypt_enc_get_iv_size($m));
1026 $r = fopen($fp_src, 'r');
1027 $w = fopen($fp_dst, 'c');
1029 $dec = mdecrypt_generic($m, fread($r, 1024));
1030 if (fwrite($w, $dec) === false) {
1037 mcrypt_generic_deinit($m);
1038 mcrypt_module_close($m);
1043 * Check if Jirafeau is password protected for visitors.
1044 * @return true if Jirafeau is password protected, false otherwise.
1046 function jirafeau_has_upload_password($cfg)
1048 return count($cfg['upload_password']) > 0;
1052 * Challenge password for a visitor.
1053 * @param $password password to be challenged
1054 * @return true if password is valid, false otherwise.
1056 function jirafeau_challenge_upload_password($cfg, $password)
1058 if (!jirafeau_has_upload_password($cfg)) {
1061 foreach ($cfg['upload_password'] as $p) {
1062 if ($password == $p) {
1070 * Test if visitor's IP is authorized to upload.
1072 * @param $allowedIpList array of allowed IPs
1073 * @param $challengedIp IP to be challenged
1074 * @return true if IP is authorized, false otherwise.
1076 function jirafeau_challenge_upload_ip($allowedIpList, $challengedIp)
1078 // skip if list is empty = all IPs allowed
1079 if (count($allowedIpList) == 0) {
1082 // test given IP against each allowed IP
1083 foreach ($allowedIpList as $i) {
1084 if ($i == $challengedIp) {
1087 // CIDR test for IPv4 only.
1088 if (strpos($i, '/') !== false) {
1089 list($subnet, $mask) = explode('/', $i);
1090 if ((ip2long($challengedIp) & ~
((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
1099 * Test if visitor's IP is authorized or password is supplied and authorized
1100 * @param $ip IP to be challenged
1101 * @param $password password to be challenged
1102 * @return true if access is valid, false otherwise.
1104 function jirafeau_challenge_upload ($cfg, $ip, $password)
1106 // Allow if no ip restrictaion and no password restriction
1107 if ((count ($cfg['upload_ip']) == 0) and (count ($cfg['upload_password']) == 0)) {
1111 // Allow if ip is in array (no password)
1112 foreach ($cfg['upload_ip_nopassword'] as $i) {
1116 // CIDR test for IPv4 only.
1117 if (strpos ($i, '/') !== false)
1119 list ($subnet, $mask) = explode('/', $i);
1120 if ((ip2long ($ip) & ~
((1 << (32 - $mask)) - 1) ) == ip2long ($subnet)) {
1126 // Allow if ip is in array
1127 foreach ($cfg['upload_ip'] as $i) {
1131 // CIDR test for IPv4 only.
1132 if (strpos ($i, '/') !== false)
1134 list ($subnet, $mask) = explode('/', $i);
1135 if ((ip2long ($ip) & ~
((1 << (32 - $mask)) - 1) ) == ip2long ($subnet)) {
1140 if (!jirafeau_has_upload_password($cfg)) {
1144 foreach ($cfg['upload_password'] as $p) {
1145 if ($password == $p) {
1152 /** Tell if we have some HTTP headers generated by a proxy */
1153 function has_http_forwarded()
1156 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1157 !empty($_SERVER['http_X_forwarded_for']);
1161 * Generate IP list from HTTP headers generated by a proxy
1162 * @return array of IP strings
1164 function get_ip_list_http_forwarded()
1167 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1168 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1172 foreach ($l as $ip) {
1173 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1176 if (!empty($_SERVER['http_X_forwarded_for'])) {
1177 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1178 foreach ($l as $ip) {
1179 // Separate IP from port
1180 $ipa = explode(':', $ip);
1181 if ($ipa === false) {
1185 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1192 * Get the ip address of the client from REMOTE_ADDR
1193 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1194 * @returns the client ip address
1196 function get_ip_address($cfg)
1198 $remote = $_SERVER['REMOTE_ADDR'];
1199 if (count($cfg['proxy_ip']) == 0 ||
!has_http_forwarded()) {
1203 $ip_list = get_ip_list_http_forwarded();
1204 if (count($ip_list) == 0) {
1208 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1209 if ($remote != $proxy_ip) {
1212 // Take the last IP (the one which has been set by the defined proxy).
1213 return end($ip_list);
1219 * Convert hexadecimal string to base64
1221 function hex_to_base64($hex)
1224 foreach (str_split($hex, 2) as $pair) {
1225 $b .= chr(hexdec($pair));
1227 return base64_encode($b);
1231 * Replace markers in templates.
1233 * Available markers have the scheme "###MARKERNAME###".
1235 * @param $content string Template text with markers
1236 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1237 * @return Template with replaced markers
1239 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1242 '/###ORGANISATION###/',
1243 '/###CONTACTPERSON###/',
1246 $replacements = array(
1247 $GLOBALS['cfg']['organisation'],
1248 $GLOBALS['cfg']['contactperson'],
1249 $GLOBALS['cfg']['web_root']
1251 $content = preg_replace($patterns, $replacements, $content);
1253 if (true === $htmllinebreaks) {
1254 $content = nl2br($content);
1260 function jirafeau_escape($string)
1262 return htmlspecialchars($string, ENT_QUOTES
);
1265 function jirafeau_admin_session_start()
1267 $_SESSION['admin_auth'] = true;
1268 $_SESSION['admin_csrf'] = md5(uniqid(mt_rand(), true));
1271 function jirafeau_admin_session_end()
1273 $_SESSION = array();
1277 function jirafeau_admin_session_logged()
1279 return isset($_SESSION['admin_auth']) &&
1280 isset($_SESSION['admin_csrf']) &&
1281 isset($_POST['admin_csrf']) &&
1282 $_SESSION['admin_auth'] === true &&
1283 $_SESSION['admin_csrf'] === $_POST['admin_csrf'];
1286 function jirafeau_admin_csrf_field()
1288 return "<input type='hidden' name='admin_csrf' value='". $_SESSION['admin_csrf'] . "'/>";
patrick-canterino.de