]>
git.p6c8.net - jirafeau_mojo42.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 <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 function jirafeau_clean_rm_link($link)
126 if (file_exists(VAR_LINKS
. $p . $link)) {
127 unlink(VAR_LINKS
. $p . $link);
129 $parse = VAR_LINKS
. $p;
131 while (file_exists($parse)
132 && ($scan = scandir($parse))
133 && count($scan) == 2 // '.' and '..' folders => empty.
134 && basename($parse) != basename(VAR_LINKS
)) {
136 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
140 function jirafeau_clean_rm_file($md5)
143 $f = VAR_FILES
. $p . $md5;
144 if (file_exists($f) && is_file($f)) {
147 if (file_exists($f . '_count') && is_file($f . '_count')) {
148 unlink($f . '_count');
150 $parse = VAR_FILES
. $p;
152 while (file_exists($parse)
153 && ($scan = scandir($parse))
154 && count($scan) == 2 // '.' and '..' folders => empty.
155 && basename($parse) != basename(VAR_FILES
)) {
157 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
162 * transforms a php.ini string representing a value in an integer
163 * @param $value the value from php.ini
164 * @returns an integer for this value
166 function jirafeau_ini_to_bytes($value)
168 $modifier = substr($value, -1);
169 $bytes = substr($value, 0, -1);
170 switch (strtoupper($modifier)) {
186 * gets the maximum upload size according to php.ini
187 * @returns the maximum upload size in bytes
189 function jirafeau_get_max_upload_size_bytes()
191 return min(jirafeau_ini_to_bytes(ini_get('post_max_size')),
192 jirafeau_ini_to_bytes(ini_get('upload_max_filesize')));
196 * gets the maximum upload size according to php.ini
197 * @returns the maximum upload size string
199 function jirafeau_get_max_upload_size()
201 return jirafeau_human_size(
202 min(jirafeau_ini_to_bytes(ini_get('post_max_size')),
203 jirafeau_ini_to_bytes(ini_get('upload_max_filesize'))));
207 * gets a string explaining the error
208 * @param $code the error code
209 * @returns a string explaining the error
211 function jirafeau_upload_errstr($code)
214 case UPLOAD_ERR_INI_SIZE
:
215 case UPLOAD_ERR_FORM_SIZE
:
216 return t('Your file exceeds the maximum authorized file size. ');
218 case UPLOAD_ERR_PARTIAL
:
219 case UPLOAD_ERR_NO_FILE
:
221 t('Your file was not uploaded correctly. You may succeed in retrying. ');
223 case UPLOAD_ERR_NO_TMP_DIR
:
224 case UPLOAD_ERR_CANT_WRITE
:
225 case UPLOAD_ERR_EXTENSION
:
226 return t('Internal error. You may not succeed in retrying. ');
228 return t('Unknown error. ');
231 /** Remove link and it's file
232 * @param $link the link's name (hash)
235 function jirafeau_delete_link($link)
237 $l = jirafeau_get_link($link);
242 jirafeau_clean_rm_link($link);
248 if (file_exists(VAR_FILES
. $p . $md5. '_count')) {
249 $content = file(VAR_FILES
. $p . $md5. '_count');
250 $counter = trim($content[0]);
255 $handle = fopen(VAR_FILES
. $p . $md5. '_count', 'w');
256 fwrite($handle, $counter);
261 jirafeau_clean_rm_file($md5);
266 * Delete a file and it's links.
268 function jirafeau_delete_file($md5)
271 /* Get all links files. */
272 $stack = array(VAR_LINKS
);
273 while (($d = array_shift($stack)) && $d != null) {
276 foreach ($dir as $node) {
277 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
278 preg_match('/\.tmp/i', "$node")) {
282 if (is_dir($d . $node)) {
283 /* Push new found directory. */
284 $stack[] = $d . $node . '/';
285 } elseif (is_file($d . $node)) {
286 /* Read link informations. */
287 $l = jirafeau_get_link(basename($node));
291 if ($l['md5'] == $md5) {
293 jirafeau_delete_link($node);
298 jirafeau_clean_rm_file($md5);
303 * handles an uploaded file
304 * @param $file the file struct given by $_FILE[]
305 * @param $one_time_download is the file a one time download ?
306 * @param $key if not empty, protect the file with this key
307 * @param $time the time of validity of the file
308 * @param $ip uploader's ip
309 * @param $crypt boolean asking to crypt or not
310 * @param $link_name_length size of the link name
311 * @returns an array containing some information
312 * 'error' => information on possible errors
313 * 'link' => the link name of the uploaded file
314 * 'delete_link' => the link code to delete file
316 function jirafeau_upload($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length)
318 if (empty($file['tmp_name']) ||
!is_uploaded_file($file['tmp_name'])) {
321 array('has_error' => true,
322 'why' => jirafeau_upload_errstr($file['error'])),
324 'delete_link' => ''));
327 /* array representing no error */
328 $noerr = array('has_error' => false, 'why' => '');
330 /* Crypt file if option is enabled. */
333 if ($crypt == true && !(extension_loaded('mcrypt') == true)) {
334 error_log("PHP extension mcrypt not loaded, won't encrypt in Jirafeau");
336 if ($crypt == true && extension_loaded('mcrypt') == true) {
337 $crypt_key = jirafeau_encrypt_file($file['tmp_name'], $file['tmp_name']);
338 if (strlen($crypt_key) > 0) {
343 /* file informations */
344 $md5 = md5_file($file['tmp_name']);
345 $name = str_replace(NL
, '', trim($file['name']));
346 $mime_type = $file['type'];
347 $size = $file['size'];
349 /* does file already exist ? */
352 if (file_exists(VAR_FILES
. $p . $md5)) {
353 $rc = unlink($file['tmp_name']);
354 } elseif ((file_exists(VAR_FILES
. $p) || @mkdir
(VAR_FILES
. $p, 0755, true))
355 && move_uploaded_file($file['tmp_name'], VAR_FILES
. $p . $md5)) {
361 array('has_error' => true,
362 'why' => t('Internal error during file creation.')),
364 'delete_link' => ''));
367 /* Increment or create count file. */
369 if (file_exists(VAR_FILES
. $p . $md5 . '_count')) {
370 $content = file(VAR_FILES
. $p . $md5. '_count');
371 $counter = trim($content[0]);
374 $handle = fopen(VAR_FILES
. $p . $md5. '_count', 'w');
375 fwrite($handle, $counter);
378 /* Create delete code. */
379 $delete_link_code = jirafeau_gen_random(5);
381 /* md5 password or empty. */
384 $password = md5($key);
387 /* create link file */
388 $link_tmp_name = VAR_LINKS
. $md5 . rand(0, 10000) . '.tmp';
389 $handle = fopen($link_tmp_name, 'w');
391 $name . NL
. $mime_type . NL
. $size . NL
. $password . NL
. $time .
392 NL
. $md5. NL
. ($one_time_download ?
'O' : 'R') . NL
. time() .
393 NL
. $ip . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
395 $md5_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
396 $l = s2p("$md5_link");
397 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
398 !rename($link_tmp_name, VAR_LINKS
. $l . $md5_link)) {
399 if (file_exists($link_tmp_name)) {
400 unlink($link_tmp_name);
405 $handle = fopen(VAR_FILES
. $p . $md5. '_count', 'w');
406 fwrite($handle, $counter);
409 jirafeau_clean_rm_file($md5_link);
413 array('has_error' => true,
414 'why' => t('Internal error during file creation. ')),
416 'delete_link' => '');
418 return array( 'error' => $noerr,
420 'delete_link' => $delete_link_code,
421 'crypt_key' => $crypt_key);
425 * Tells if a mime-type is viewable in a browser
426 * @param $mime the mime type
427 * @returns a boolean telling if a mime type is viewable
429 function jirafeau_is_viewable($mime)
432 /* Actually, verify if mime-type is an image or a text. */
433 $viewable = array('image', 'text', 'video', 'audio');
434 $decomposed = explode('/', $mime);
435 return in_array($decomposed[0], $viewable);
440 // Error handling functions.
441 //! Global array that contains all registered errors.
442 $error_list = array();
445 * Adds an error to the list of errors.
446 * @param $title the error's title
447 * @param $description is a human-friendly description of the problem.
449 function add_error($title, $description)
452 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
456 * Informs whether any error has been registered yet.
457 * @return true if there are errors.
462 return !empty($error_list);
466 * Displays all the errors.
468 function show_errors()
472 echo '<div class="error">';
473 foreach ($error_list as $error) {
480 function check_errors($cfg)
482 if (file_exists(JIRAFEAU_ROOT
. 'install.php')
483 && !($cfg['installation_done'] === true)) {
484 header('Location: install.php');
488 /* check if the destination dirs are writable */
489 $writable = is_writable(VAR_FILES
) && is_writable(VAR_LINKS
);
491 /* Checking for errors. */
492 if (!is_writable(VAR_FILES
)) {
493 add_error(t('The file directory is not writable!'), VAR_FILES
);
496 if (!is_writable(VAR_LINKS
)) {
497 add_error(t('The link directory is not writable!'), VAR_LINKS
);
500 if (!is_writable(VAR_ASYNC
)) {
501 add_error(t('The async directory is not writable!'), VAR_ASYNC
);
506 * Read link informations
507 * @return array containing informations.
509 function jirafeau_get_link($hash)
512 $link = VAR_LINKS
. s2p("$hash") . $hash;
514 if (!file_exists($link)) {
519 $out['file_name'] = trim($c[0]);
520 $out['mime_type'] = trim($c[1]);
521 $out['file_size'] = trim($c[2]);
522 $out['key'] = trim($c[3], NL
);
523 $out['time'] = trim($c[4]);
524 $out['md5'] = trim($c[5]);
525 $out['onetime'] = trim($c[6]);
526 $out['upload_date'] = trim($c[7]);
527 $out['ip'] = trim($c[8]);
528 $out['link_code'] = trim($c[9]);
529 $out['crypted'] = trim($c[10]) == 'C';
535 * List files in admin interface.
537 function jirafeau_admin_list($name, $file_hash, $link_hash)
539 echo '<fieldset><legend>';
541 echo t('Filename') . ": $name ";
543 if (!empty($file_hash)) {
544 echo t('file') . ": $file_hash ";
546 if (!empty($link_hash)) {
547 echo t('link') . ": $link_hash ";
549 if (empty($name) && empty($file_hash) && empty($link_hash)) {
550 echo t('List all files');
555 echo '<td>' . t('Filename') . '</td>';
556 echo '<td>' . t('Type') . '</td>';
557 echo '<td>' . t('Size') . '</td>';
558 echo '<td>' . t('Expire') . '</td>';
559 echo '<td>' . t('Onetime') . '</td>';
560 echo '<td>' . t('Upload date') . '</td>';
561 echo '<td>' . t('Origin') . '</td>';
562 echo '<td>' . t('Action') . '</td>';
565 /* Get all links files. */
566 $stack = array(VAR_LINKS
);
567 while (($d = array_shift($stack)) && $d != null) {
569 foreach ($dir as $node) {
570 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
571 preg_match('/\.tmp/i', "$node")) {
574 if (is_dir($d . $node)) {
575 /* Push new found directory. */
576 $stack[] = $d . $node . '/';
577 } elseif (is_file($d . $node)) {
578 /* Read link informations. */
579 $l = jirafeau_get_link($node);
585 if (!empty($name) && !preg_match("/$name/i", htmlspecialchars($l['file_name']))) {
588 if (!empty($file_hash) && $file_hash != $l['md5']) {
591 if (!empty($link_hash) && $link_hash != $node) {
594 /* Print link informations. */
597 '<strong><a id="upload_link" href="/f.php?h='. htmlspecialchars($node) .'" title="' .
598 t('Download page') . '">' . htmlspecialchars($l['file_name']) . '</a></strong>';
600 echo '<td>' . $l['mime_type'] . '</td>';
601 echo '<td>' . jirafeau_human_size($l['file_size']) . '</td>';
602 echo '<td>' . ($l['time'] == -1 ?
'' : strftime('%c', $l['time'])) .
605 if ($l['onetime'] == 'O') {
611 echo '<td>' . strftime('%c', $l['upload_date']) . '</td>';
612 echo '<td>' . $l['ip'] . '</td>';
614 '<form action = "admin.php" method = "post">' .
615 '<input type = "hidden" name = "action" value = "download"/>' .
616 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
617 '<input type = "submit" value = "' . t('Download') . '" />' .
619 '<form action = "admin.php" method = "post">' .
620 '<input type = "hidden" name = "action" value = "delete_link"/>' .
621 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
622 '<input type = "submit" value = "' . t('Del link') . '" />' .
624 '<form action = "admin.php" method = "post">' .
625 '<input type = "hidden" name = "action" value = "delete_file"/>' .
626 '<input type = "hidden" name = "md5" value = "' . $l['md5'] . '"/>' .
627 '<input type = "submit" value = "' . t('Del file and links') . '" />' .
634 echo '</table></fieldset>';
638 * Clean expired files.
639 * @return number of cleaned files.
641 function jirafeau_admin_clean()
644 /* Get all links files. */
645 $stack = array(VAR_LINKS
);
646 while (($d = array_shift($stack)) && $d != null) {
649 foreach ($dir as $node) {
650 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
651 preg_match('/\.tmp/i', "$node")) {
655 if (is_dir($d . $node)) {
656 /* Push new found directory. */
657 $stack[] = $d . $node . '/';
658 } elseif (is_file($d . $node)) {
659 /* Read link informations. */
660 $l = jirafeau_get_link(basename($node));
665 if ($l['time'] > 0 && $l['time'] < time() ||
// expired
666 !file_exists(VAR_FILES
. $p . $l['md5']) ||
// invalid
667 !file_exists(VAR_FILES
. $p . $l['md5'] . '_count')) { // invalid
668 jirafeau_delete_link($node);
679 * Clean old async transferts.
680 * @return number of cleaned files.
682 function jirafeau_admin_clean_async()
685 /* Get all links files. */
686 $stack = array(VAR_ASYNC
);
687 while (($d = array_shift($stack)) && $d != null) {
690 foreach ($dir as $node) {
691 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
692 preg_match('/\.tmp/i', "$node")) {
696 if (is_dir($d . $node)) {
697 /* Push new found directory. */
698 $stack[] = $d . $node . '/';
699 } elseif (is_file($d . $node)) {
700 /* Read async informations. */
701 $a = jirafeau_get_async_ref(basename($node));
705 /* Delete transferts older than 1 hour. */
706 if (time() - $a['last_edited'] > 3600) {
707 jirafeau_async_delete(basename($node));
716 * Read async transfert informations
717 * @return array containing informations.
719 function jirafeau_get_async_ref($ref)
722 $refinfos = VAR_ASYNC
. s2p("$ref") . "$ref";
724 if (!file_exists($refinfos)) {
728 $c = file($refinfos);
729 $out['file_name'] = trim($c[0]);
730 $out['mime_type'] = trim($c[1]);
731 $out['key'] = trim($c[2], NL
);
732 $out['time'] = trim($c[3]);
733 $out['onetime'] = trim($c[4]);
734 $out['ip'] = trim($c[5]);
735 $out['last_edited'] = trim($c[6]);
736 $out['next_code'] = trim($c[7]);
741 * Delete async transfert informations
743 function jirafeau_async_delete($ref)
746 if (file_exists(VAR_ASYNC
. $p . $ref)) {
747 unlink(VAR_ASYNC
. $p . $ref);
749 if (file_exists(VAR_ASYNC
. $p . $ref . '_data')) {
750 unlink(VAR_ASYNC
. $p . $ref . '_data');
752 $parse = VAR_ASYNC
. $p;
754 while (file_exists($parse)
755 && ($scan = scandir($parse))
756 && count($scan) == 2 // '.' and '..' folders => empty.
757 && basename($parse) != basename(VAR_ASYNC
)) {
759 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
764 * Init a new asynchronous upload.
765 * @param $finename Name of the file to send
766 * @param $one_time One time upload parameter
767 * @param $key eventual password (or blank)
768 * @param $time time limit
769 * @param $ip ip address of the client
770 * @return a string containing a temporary reference followed by a code or the string 'Error'
772 function jirafeau_async_init($filename, $type, $one_time, $key, $time, $ip)
776 /* Create temporary folder. */
779 $code = jirafeau_gen_random(4);
781 $ref = jirafeau_gen_random(32);
782 $p = VAR_ASYNC
. s2p($ref);
783 } while (file_exists($p));
784 @mkdir
($p, 0755, true);
785 if (!file_exists($p)) {
790 /* md5 password or empty */
793 $password = md5($key);
796 /* Store informations. */
798 $handle = fopen($p, 'w');
800 str_replace(NL
, '', trim($filename)) . NL
.
801 str_replace(NL
, '', trim($type)) . NL
. $password . NL
.
802 $time . NL
. ($one_time ?
'O' : 'R') . NL
. $ip . NL
.
803 time() . NL
. $code . NL
);
806 return $ref . NL
. $code ;
810 * Append a piece of file on the asynchronous upload.
811 * @param $ref asynchronous upload reference
812 * @param $file piece of data
813 * @param $code client code for this operation
814 * @param $max_file_size maximum allowed file size
815 * @return a string containing a next code to use or the string "Error"
817 function jirafeau_async_push($ref, $data, $code, $max_file_size)
819 /* Get async infos. */
820 $a = jirafeau_get_async_ref($ref);
822 /* Check some errors. */
824 ||
$a['next_code'] != "$code"
825 ||
empty($data['tmp_name'])
826 ||
!is_uploaded_file($data['tmp_name'])) {
833 $r_path = $data['tmp_name'];
834 $w_path = VAR_ASYNC
. $p . $ref . '_data';
836 /* Check that file size is not above upload limit. */
837 if ($max_file_size > 0 &&
838 filesize($r_path) +
filesize($w_path) > $max_file_size * 1024 * 1024) {
839 jirafeau_async_delete($ref);
843 /* Concatenate data. */
844 $r = fopen($r_path, 'r');
845 $w = fopen($w_path, 'a');
847 if (fwrite($w, fread($r, 1024)) === false) {
850 jirafeau_async_delete($ref);
858 /* Update async file. */
859 $code = jirafeau_gen_random(4);
860 $handle = fopen(VAR_ASYNC
. $p . $ref, 'w');
862 $a['file_name'] . NL
. $a['mime_type'] . NL
. $a['key'] . NL
.
863 $a['time'] . NL
. $a['onetime'] . NL
. $a['ip'] . NL
.
864 time() . NL
. $code . NL
);
870 * Finalyze an asynchronous upload.
871 * @param $ref asynchronous upload reference
872 * @param $code client code for this operation
873 * @param $crypt boolean asking to crypt or not
874 * @param $link_name_length link name length
875 * @return a string containing the download reference followed by a delete code or the string 'Error'
877 function jirafeau_async_end($ref, $code, $crypt, $link_name_length)
879 /* Get async infos. */
880 $a = jirafeau_get_async_ref($ref);
882 ||
$a['next_code'] != "$code") {
886 /* Generate link infos. */
887 $p = VAR_ASYNC
. s2p($ref) . $ref . "_data";
888 if (!file_exists($p)) {
894 if ($crypt == true && extension_loaded('mcrypt') == true) {
895 $crypt_key = jirafeau_encrypt_file($p, $p);
896 if (strlen($crypt_key) > 0) {
902 $size = filesize($p);
904 $delete_link_code = jirafeau_gen_random(5);
906 /* File already exist ? */
907 if (!file_exists(VAR_FILES
. $np)) {
908 @mkdir
(VAR_FILES
. $np, 0755, true);
910 if (!file_exists(VAR_FILES
. $np . $md5)) {
911 rename($p, VAR_FILES
. $np . $md5);
914 /* Increment or create count file. */
916 if (file_exists(VAR_FILES
. $np . $md5 . '_count')) {
917 $content = file(VAR_FILES
. $np . $md5. '_count');
918 $counter = trim($content[0]);
921 $handle = fopen(VAR_FILES
. $np . $md5. '_count', 'w');
922 fwrite($handle, $counter);
926 $link_tmp_name = VAR_LINKS
. $md5 . rand(0, 10000) . '.tmp';
927 $handle = fopen($link_tmp_name, 'w');
929 $a['file_name'] . NL
. $a['mime_type'] . NL
. $size . NL
.
930 $a['key'] . NL
. $a['time'] . NL
. $md5 . NL
. $a['onetime'] . NL
.
931 time() . NL
. $a['ip'] . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
933 $md5_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
934 $l = s2p("$md5_link");
935 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
936 !rename($link_tmp_name, VAR_LINKS
. $l . $md5_link)) {
940 /* Clean async upload. */
941 jirafeau_async_delete($ref);
942 return $md5_link . NL
. $delete_link_code . NL
. urlencode($crypt_key);
945 function jirafeau_crypt_create_iv($base, $size)
948 while (strlen($iv) < $size) {
951 $iv = substr($iv, 0, $size);
956 * Crypt file and returns decrypt key.
957 * @param $fp_src file path to the file to crypt.
958 * @param $fp_dst file path to the file to write crypted file (could be the same).
959 * @return decrypt key composed of the key and the iv separated by a point ('.')
961 function jirafeau_encrypt_file($fp_src, $fp_dst)
963 $fs = filesize($fp_src);
964 if ($fs === false ||
$fs == 0 ||
!(extension_loaded('mcrypt') == true)) {
968 /* Prepare module. */
969 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
971 $crypt_key = jirafeau_gen_random(10);
972 $md5_key = md5($crypt_key);
973 $iv = jirafeau_crypt_create_iv($md5_key, mcrypt_enc_get_iv_size($m));
975 mcrypt_generic_init($m, $md5_key, $iv);
977 $r = fopen($fp_src, 'r');
978 $w = fopen($fp_dst, 'c');
980 $enc = mcrypt_generic($m, fread($r, 1024));
981 if (fwrite($w, $enc) === false) {
988 mcrypt_generic_deinit($m);
989 mcrypt_module_close($m);
995 * @param $fp_src file path to the file to decrypt.
996 * @param $fp_dst file path to the file to write decrypted file (could be the same).
997 * @param $k string composed of the key and the iv separated by a point ('.')
998 * @return key used to decrypt. a string of length 0 is returned if failed.
1000 function jirafeau_decrypt_file($fp_src, $fp_dst, $k)
1002 $fs = filesize($fp_src);
1003 if ($fs === false ||
$fs == 0 ||
extension_loaded('mcrypt') == false) {
1008 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1009 /* Extract key and iv. */
1011 $md5_key = md5($crypt_key);
1012 $iv = jirafeau_crypt_create_iv($md5_key, mcrypt_enc_get_iv_size($m));
1014 $r = fopen($fp_src, 'r');
1015 $w = fopen($fp_dst, 'c');
1017 $dec = mdecrypt_generic($m, fread($r, 1024));
1018 if (fwrite($w, $dec) === false) {
1025 mcrypt_generic_deinit($m);
1026 mcrypt_module_close($m);
1031 * Check if Jirafeau is password protected for visitors.
1032 * @return true if Jirafeau is password protected, false otherwise.
1034 function jirafeau_has_upload_password($cfg)
1036 return count($cfg['upload_password']) > 0;
1040 * Challenge password for a visitor.
1041 * @param $password password to be challenged
1042 * @return true if password is valid, false otherwise.
1044 function jirafeau_challenge_upload_password($cfg, $password)
1046 if (!jirafeau_has_upload_password($cfg)) {
1049 foreach ($cfg['upload_password'] as $p) {
1050 if ($password == $p) {
1058 * Test if visitor's IP is authorized to upload.
1059 * @param $ip IP to be challenged
1060 * @return true if IP is authorized, false otherwise.
1062 function jirafeau_challenge_upload_ip($cfg, $ip)
1064 if (count($cfg['upload_ip']) == 0) {
1067 foreach ($cfg['upload_ip'] as $i) {
1071 // CIDR test for IPv4 only.
1072 if (strpos($i, '/') !== false) {
1073 list($subnet, $mask) = explode('/', $i);
1074 if ((ip2long($ip) & ~
((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
1083 * Test if visitor's IP is authorized or password is supplied and authorized
1084 * @param $ip IP to be challenged
1085 * @param $password password to be challenged
1086 * @return true if access is valid, false otherwise.
1088 function jirafeau_challenge_upload ($cfg, $ip, $password)
1090 // Allow if no ip restrictaion and no password restriction
1091 if ((count ($cfg['upload_ip']) == 0) and (count ($cfg['upload_password']) == 0)) {
1095 // Allow if ip is in array
1096 foreach ($cfg['upload_ip'] as $i) {
1100 // CIDR test for IPv4 only.
1101 if (strpos ($i, '/') !== false)
1103 list ($subnet, $mask) = explode('/', $i);
1104 if ((ip2long ($ip) & ~
((1 << (32 - $mask)) - 1) ) == ip2long ($subnet)) {
1109 if (!jirafeau_has_upload_password($cfg)) {
1113 foreach ($cfg['upload_password'] as $p) {
1114 if ($password == $p) {
1121 /** Tell if we have some HTTP headers generated by a proxy */
1122 function has_http_forwarded()
1125 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1126 !empty($_SERVER['http_X_forwarded_for']);
1130 * Generate IP list from HTTP headers generated by a proxy
1131 * @return array of IP strings
1133 function get_ip_list_http_forwarded()
1136 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1137 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1141 foreach ($l as $ip) {
1142 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1145 if (!empty($_SERVER['http_X_forwarded_for'])) {
1146 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1147 foreach ($l as $ip) {
1148 // Separate IP from port
1149 $ipa = explode(':', $ip);
1150 if ($ipa === false) {
1154 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1161 * Get the ip address of the client from REMOTE_ADDR
1162 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1163 * @returns the client ip address
1165 function get_ip_address($cfg)
1167 $remote = $_SERVER['REMOTE_ADDR'];
1168 if (count($cfg['proxy_ip']) == 0 ||
!has_http_forwarded()) {
1172 $ip_list = get_ip_list_http_forwarded();
1173 if (count($ip_list) == 0) {
1177 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1178 if ($remote != $proxy_ip) {
1181 // Take the last IP (the one which has been set by the defined proxy).
1182 return end($ip_list);
1188 * Convert hexadecimal string to base64
1190 function hex_to_base64($hex)
1193 foreach (str_split($hex, 2) as $pair) {
1194 $b .= chr(hexdec($pair));
1196 return base64_encode($b);
1200 * Read alias informations
1201 * @return array containing informations.
1203 function jirafeau_get_alias($hash)
1206 $link = VAR_ALIAS
. s2p("$hash") . $hash;
1208 if (!file_exists($link)) {
1213 $out['md5_password'] = trim($c[0]);
1214 $out['ip'] = trim($c[1]);
1215 $out['update_date'] = trim($c[2]);
1216 $out['destination'] = trim($c[3], NL
);
1221 /** Create an alias to a jirafeau's link.
1222 * @param $alias alias name
1223 * @param $destination reference of the destination
1224 * @param $password password to protect alias
1225 * @param $ip client's IP
1226 * @return a string containing the edit code of the alias or the string "Error"
1228 function jirafeau_alias_create($alias, $destination, $password, $ip)
1230 /* Check that alias and password are long enough. */
1231 if (strlen($alias) < 8 ||
1232 strlen($alias) > 32 ||
1233 strlen($password) < 8 ||
1234 strlen($password) > 32) {
1238 /* Check that destination exists. */
1239 $l = jirafeau_get_link($destination);
1244 /* Check that alias does not already exists. */
1245 $alias = md5($alias);
1246 $p = VAR_ALIAS
. s2p($alias);
1247 if (file_exists($p)) {
1251 /* Create alias folder. */
1252 @mkdir
($p, 0755, true);
1253 if (!file_exists($p)) {
1257 /* Generate password. */
1258 $md5_password = md5($password);
1260 /* Store informations. */
1262 $handle = fopen($p, 'w');
1264 $md5_password . NL
.
1273 /** Update an alias.
1274 * @param $alias alias to update
1275 * @param $destination reference of the new destination
1276 * @param $password password to protect alias
1277 * @param $new_password optional new password to protect alias
1278 * @param $ip client's IP
1279 * @return "Ok" or "Error" string
1281 function jirafeau_alias_update($alias, $destination, $password,
1284 $alias = md5($alias);
1285 /* Check that alias exits. */
1286 $a = jirafeau_get_alias($alias);
1291 /* Check that destination exists. */
1292 $l = jirafeau_get_link($a["destination"]);
1297 /* Check password. */
1298 if ($a["md5_password"] != md5($password)) {
1302 $p = $a['md5_password'];
1303 if (strlen($new_password) >= 8 &&
1304 strlen($new_password) <= 32) {
1305 $p = md5($new_password);
1306 } elseif (strlen($new_password) > 0) {
1310 /* Rewrite informations. */
1311 $p = VAR_ALIAS
. s2p($alias) . $alias;
1312 $handle = fopen($p, 'w');
1323 * @param $alias alias to get
1324 * @return alias destination or "Error" string
1326 function jirafeau_alias_get($alias)
1328 $alias = md5($alias);
1329 /* Check that alias exits. */
1330 $a = jirafeau_get_alias($alias);
1335 return $a['destination'];
1338 function jirafeau_clean_rm_alias($alias)
1341 if (file_exists(VAR_ALIAS
. $p . $alias)) {
1342 unlink(VAR_ALIAS
. $p . $alias);
1344 $parse = VAR_ALIAS
. $p;
1346 while (file_exists($parse)
1347 && ($scan = scandir($parse))
1348 && count($scan) == 2 // '.' and '..' folders => empty.
1349 && basename($parse) != basename(VAR_ALIAS
)) {
1351 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
1355 /** Delete an alias.
1356 * @param $alias alias to delete
1357 * @param $password password to protect alias
1358 * @return "Ok" or "Error" string
1360 function jirafeau_alias_delete($alias, $password)
1362 $alias = md5($alias);
1363 /* Check that alias exits. */
1364 $a = jirafeau_get_alias($alias);
1369 /* Check password. */
1370 if ($a["md5_password"] != md5($password)) {
1374 jirafeau_clean_rm_alias($alias);
1379 * Replace markers in templates.
1381 * Available markers have the scheme "###MARKERNAME###".
1383 * @param $content string Template text with markers
1384 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1385 * @return Template with replaced markers
1387 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1390 '/###ORGANISATION###/',
1391 '/###CONTACTPERSON###/',
1394 $replacements = array(
1395 $GLOBALS['cfg']['organisation'],
1396 $GLOBALS['cfg']['contactperson'],
1397 $GLOBALS['cfg']['web_root']
1399 $content = preg_replace($patterns, $replacements, $content);
1401 if (true === $htmllinebreaks) {
1402 $content = nl2br($content);
patrick-canterino.de