]>
git.p6c8.net - jirafeau_mojo42.git/blob - lib/functions.php
50ab345197cb508416bca35a6507829c3f24ce9a
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_clean_rm_link($link)
134 if (file_exists(VAR_LINKS
. $p . $link)) {
135 unlink(VAR_LINKS
. $p . $link);
137 $parse = VAR_LINKS
. $p;
139 while (file_exists($parse)
140 && ($scan = scandir($parse))
141 && count($scan) == 2 // '.' and '..' folders => empty.
142 && basename($parse) != basename(VAR_LINKS
)) {
144 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
148 function jirafeau_clean_rm_file($md5)
151 $f = VAR_FILES
. $p . $md5;
152 if (file_exists($f) && is_file($f)) {
155 if (file_exists($f . '_count') && is_file($f . '_count')) {
156 unlink($f . '_count');
158 $parse = VAR_FILES
. $p;
160 while (file_exists($parse)
161 && ($scan = scandir($parse))
162 && count($scan) == 2 // '.' and '..' folders => empty.
163 && basename($parse) != basename(VAR_FILES
)) {
165 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
170 * transforms a php.ini string representing a value in an integer
171 * @param $value the value from php.ini
172 * @returns an integer for this value
174 function jirafeau_ini_to_bytes($value)
176 $modifier = substr($value, -1);
177 $bytes = substr($value, 0, -1);
178 switch (strtoupper($modifier)) {
194 * gets the maximum upload size according to php.ini
195 * @returns the maximum upload size in bytes
197 function jirafeau_get_max_upload_size_bytes()
199 return min(jirafeau_ini_to_bytes(ini_get('post_max_size')),
200 jirafeau_ini_to_bytes(ini_get('upload_max_filesize')));
204 * gets the maximum upload size according to php.ini
205 * @returns the maximum upload size string
207 function jirafeau_get_max_upload_size()
209 return jirafeau_human_size(
210 min(jirafeau_ini_to_bytes(ini_get('post_max_size')),
211 jirafeau_ini_to_bytes(ini_get('upload_max_filesize'))));
215 * gets a string explaining the error
216 * @param $code the error code
217 * @returns a string explaining the error
219 function jirafeau_upload_errstr($code)
222 case UPLOAD_ERR_INI_SIZE
:
223 case UPLOAD_ERR_FORM_SIZE
:
224 return t('Your file exceeds the maximum authorized file size. ');
226 case UPLOAD_ERR_PARTIAL
:
227 case UPLOAD_ERR_NO_FILE
:
229 t('Your file was not uploaded correctly. You may succeed in retrying. ');
231 case UPLOAD_ERR_NO_TMP_DIR
:
232 case UPLOAD_ERR_CANT_WRITE
:
233 case UPLOAD_ERR_EXTENSION
:
234 return t('Internal error. You may not succeed in retrying. ');
236 return t('Unknown error. ');
239 /** Remove link and it's file
240 * @param $link the link's name (hash)
243 function jirafeau_delete_link($link)
245 $l = jirafeau_get_link($link);
250 jirafeau_clean_rm_link($link);
256 if (file_exists(VAR_FILES
. $p . $md5. '_count')) {
257 $content = file(VAR_FILES
. $p . $md5. '_count');
258 $counter = trim($content[0]);
263 $handle = fopen(VAR_FILES
. $p . $md5. '_count', 'w');
264 fwrite($handle, $counter);
269 jirafeau_clean_rm_file($md5);
274 * Delete a file and it's links.
276 function jirafeau_delete_file($md5)
279 /* Get all links files. */
280 $stack = array(VAR_LINKS
);
281 while (($d = array_shift($stack)) && $d != null) {
284 foreach ($dir as $node) {
285 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
286 preg_match('/\.tmp/i', "$node")) {
290 if (is_dir($d . $node)) {
291 /* Push new found directory. */
292 $stack[] = $d . $node . '/';
293 } elseif (is_file($d . $node)) {
294 /* Read link informations. */
295 $l = jirafeau_get_link(basename($node));
299 if ($l['md5'] == $md5) {
301 jirafeau_delete_link($node);
306 jirafeau_clean_rm_file($md5);
311 * handles an uploaded file
312 * @param $file the file struct given by $_FILE[]
313 * @param $one_time_download is the file a one time download ?
314 * @param $key if not empty, protect the file with this key
315 * @param $time the time of validity of the file
316 * @param $ip uploader's ip
317 * @param $crypt boolean asking to crypt or not
318 * @param $link_name_length size of the link name
319 * @returns an array containing some information
320 * 'error' => information on possible errors
321 * 'link' => the link name of the uploaded file
322 * 'delete_link' => the link code to delete file
324 function jirafeau_upload($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length)
326 if (empty($file['tmp_name']) ||
!is_uploaded_file($file['tmp_name'])) {
329 array('has_error' => true,
330 'why' => jirafeau_upload_errstr($file['error'])),
332 'delete_link' => ''));
335 /* array representing no error */
336 $noerr = array('has_error' => false, 'why' => '');
338 /* Crypt file if option is enabled. */
341 if ($crypt == true && !(extension_loaded('mcrypt') == true)) {
342 error_log("PHP extension mcrypt not loaded, won't encrypt in Jirafeau");
344 if ($crypt == true && extension_loaded('mcrypt') == true) {
345 $crypt_key = jirafeau_encrypt_file($file['tmp_name'], $file['tmp_name']);
346 if (strlen($crypt_key) > 0) {
351 /* file informations */
352 $md5 = md5_file($file['tmp_name']);
353 $name = str_replace(NL
, '', trim($file['name']));
354 $mime_type = $file['type'];
355 $size = $file['size'];
357 /* does file already exist ? */
360 if (file_exists(VAR_FILES
. $p . $md5)) {
361 $rc = unlink($file['tmp_name']);
362 } elseif ((file_exists(VAR_FILES
. $p) || @mkdir
(VAR_FILES
. $p, 0755, true))
363 && move_uploaded_file($file['tmp_name'], VAR_FILES
. $p . $md5)) {
369 array('has_error' => true,
370 'why' => t('Internal error during file creation.')),
372 'delete_link' => ''));
375 /* Increment or create count file. */
377 if (file_exists(VAR_FILES
. $p . $md5 . '_count')) {
378 $content = file(VAR_FILES
. $p . $md5. '_count');
379 $counter = trim($content[0]);
382 $handle = fopen(VAR_FILES
. $p . $md5. '_count', 'w');
383 fwrite($handle, $counter);
386 /* Create delete code. */
387 $delete_link_code = jirafeau_gen_random(5);
389 /* md5 password or empty. */
392 $password = md5($key);
395 /* create link file */
396 $link_tmp_name = VAR_LINKS
. $md5 . rand(0, 10000) . '.tmp';
397 $handle = fopen($link_tmp_name, 'w');
399 $name . NL
. $mime_type . NL
. $size . NL
. $password . NL
. $time .
400 NL
. $md5. NL
. ($one_time_download ?
'O' : 'R') . NL
. time() .
401 NL
. $ip . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
403 $md5_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
404 $l = s2p("$md5_link");
405 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
406 !rename($link_tmp_name, VAR_LINKS
. $l . $md5_link)) {
407 if (file_exists($link_tmp_name)) {
408 unlink($link_tmp_name);
413 $handle = fopen(VAR_FILES
. $p . $md5. '_count', 'w');
414 fwrite($handle, $counter);
417 jirafeau_clean_rm_file($md5_link);
421 array('has_error' => true,
422 'why' => t('Internal error during file creation. ')),
424 'delete_link' => '');
426 return array( 'error' => $noerr,
428 'delete_link' => $delete_link_code,
429 'crypt_key' => $crypt_key);
433 * Tells if a mime-type is viewable in a browser
434 * @param $mime the mime type
435 * @returns a boolean telling if a mime type is viewable
437 function jirafeau_is_viewable($mime)
440 /* Actually, verify if mime-type is an image or a text. */
441 $viewable = array('image', 'text', 'video', 'audio');
442 $decomposed = explode('/', $mime);
443 return in_array($decomposed[0], $viewable);
448 // Error handling functions.
449 //! Global array that contains all registered errors.
450 $error_list = array();
453 * Adds an error to the list of errors.
454 * @param $title the error's title
455 * @param $description is a human-friendly description of the problem.
457 function add_error($title, $description)
460 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
464 * Informs whether any error has been registered yet.
465 * @return true if there are errors.
470 return !empty($error_list);
474 * Displays all the errors.
476 function show_errors()
480 echo '<div class="error">';
481 foreach ($error_list as $error) {
488 function check_errors($cfg)
490 if (file_exists(JIRAFEAU_ROOT
. 'install.php')
491 && !($cfg['installation_done'] === true)) {
492 header('Location: install.php');
496 /* check if the destination dirs are writable */
497 $writable = is_writable(VAR_FILES
) && is_writable(VAR_LINKS
);
499 /* Checking for errors. */
500 if (!is_writable(VAR_FILES
)) {
501 add_error(t('The file directory is not writable!'), VAR_FILES
);
504 if (!is_writable(VAR_LINKS
)) {
505 add_error(t('The link directory is not writable!'), VAR_LINKS
);
508 if (!is_writable(VAR_ASYNC
)) {
509 add_error(t('The async directory is not writable!'), VAR_ASYNC
);
514 * Read link informations
515 * @return array containing informations.
517 function jirafeau_get_link($hash)
520 $link = VAR_LINKS
. s2p("$hash") . $hash;
522 if (!file_exists($link)) {
527 $out['file_name'] = trim($c[0]);
528 $out['mime_type'] = trim($c[1]);
529 $out['file_size'] = trim($c[2]);
530 $out['key'] = trim($c[3], NL
);
531 $out['time'] = trim($c[4]);
532 $out['md5'] = trim($c[5]);
533 $out['onetime'] = trim($c[6]);
534 $out['upload_date'] = trim($c[7]);
535 $out['ip'] = trim($c[8]);
536 $out['link_code'] = trim($c[9]);
537 $out['crypted'] = trim($c[10]) == 'C';
543 * List files in admin interface.
545 function jirafeau_admin_list($name, $file_hash, $link_hash)
547 echo '<fieldset><legend>';
549 echo t('Filename') . ": $name ";
551 if (!empty($file_hash)) {
552 echo t('file') . ": $file_hash ";
554 if (!empty($link_hash)) {
555 echo t('link') . ": $link_hash ";
557 if (empty($name) && empty($file_hash) && empty($link_hash)) {
558 echo t('List all files');
563 echo '<td>' . t('Filename') . '</td>';
564 echo '<td>' . t('Type') . '</td>';
565 echo '<td>' . t('Size') . '</td>';
566 echo '<td>' . t('Expire') . '</td>';
567 echo '<td>' . t('Onetime') . '</td>';
568 echo '<td>' . t('Upload date') . '</td>';
569 echo '<td>' . t('Origin') . '</td>';
570 echo '<td>' . t('Action') . '</td>';
573 /* Get all links files. */
574 $stack = array(VAR_LINKS
);
575 while (($d = array_shift($stack)) && $d != null) {
577 foreach ($dir as $node) {
578 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
579 preg_match('/\.tmp/i', "$node")) {
582 if (is_dir($d . $node)) {
583 /* Push new found directory. */
584 $stack[] = $d . $node . '/';
585 } elseif (is_file($d . $node)) {
586 /* Read link informations. */
587 $l = jirafeau_get_link($node);
593 if (!empty($name) && !preg_match("/$name/i", htmlspecialchars($l['file_name']))) {
596 if (!empty($file_hash) && $file_hash != $l['md5']) {
599 if (!empty($link_hash) && $link_hash != $node) {
602 /* Print link informations. */
605 '<strong><a id="upload_link" href="' . JIRAFEAU_ABSPREFIX
. 'f.php?h='. htmlspecialchars($node) .'" title="' .
606 t('Download page') . '">' . htmlspecialchars($l['file_name']) . '</a></strong>';
608 echo '<td>' . $l['mime_type'] . '</td>';
609 echo '<td>' . jirafeau_human_size($l['file_size']) . '</td>';
610 echo '<td>' . ($l['time'] == -1 ?
'∞' : jirafeau_get_datetimefield($l['time'])) . '</td>';
612 if ($l['onetime'] == 'O') {
618 echo '<td>' . jirafeau_get_datetimefield($l['upload_date']) . '</td>';
619 echo '<td>' . $l['ip'] . '</td>';
621 '<form method="post">' .
622 '<input type = "hidden" name = "action" value = "download"/>' .
623 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
624 '<input type = "submit" value = "' . t('Download') . '" />' .
626 '<form method="post">' .
627 '<input type = "hidden" name = "action" value = "delete_link"/>' .
628 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
629 '<input type = "submit" value = "' . t('Del link') . '" />' .
631 '<form method="post">' .
632 '<input type = "hidden" name = "action" value = "delete_file"/>' .
633 '<input type = "hidden" name = "md5" value = "' . $l['md5'] . '"/>' .
634 '<input type = "submit" value = "' . t('Del file and links') . '" />' .
641 echo '</table></fieldset>';
645 * Clean expired files.
646 * @return number of cleaned files.
648 function jirafeau_admin_clean()
651 /* Get all links files. */
652 $stack = array(VAR_LINKS
);
653 while (($d = array_shift($stack)) && $d != null) {
656 foreach ($dir as $node) {
657 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
658 preg_match('/\.tmp/i', "$node")) {
662 if (is_dir($d . $node)) {
663 /* Push new found directory. */
664 $stack[] = $d . $node . '/';
665 } elseif (is_file($d . $node)) {
666 /* Read link informations. */
667 $l = jirafeau_get_link(basename($node));
672 if ($l['time'] > 0 && $l['time'] < time() ||
// expired
673 !file_exists(VAR_FILES
. $p . $l['md5']) ||
// invalid
674 !file_exists(VAR_FILES
. $p . $l['md5'] . '_count')) { // invalid
675 jirafeau_delete_link($node);
686 * Clean old async transferts.
687 * @return number of cleaned files.
689 function jirafeau_admin_clean_async()
692 /* Get all links files. */
693 $stack = array(VAR_ASYNC
);
694 while (($d = array_shift($stack)) && $d != null) {
697 foreach ($dir as $node) {
698 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
699 preg_match('/\.tmp/i', "$node")) {
703 if (is_dir($d . $node)) {
704 /* Push new found directory. */
705 $stack[] = $d . $node . '/';
706 } elseif (is_file($d . $node)) {
707 /* Read async informations. */
708 $a = jirafeau_get_async_ref(basename($node));
712 /* Delete transferts older than 1 hour. */
713 if (time() - $a['last_edited'] > 3600) {
714 jirafeau_async_delete(basename($node));
723 * Read async transfert informations
724 * @return array containing informations.
726 function jirafeau_get_async_ref($ref)
729 $refinfos = VAR_ASYNC
. s2p("$ref") . "$ref";
731 if (!file_exists($refinfos)) {
735 $c = file($refinfos);
736 $out['file_name'] = trim($c[0]);
737 $out['mime_type'] = trim($c[1]);
738 $out['key'] = trim($c[2], NL
);
739 $out['time'] = trim($c[3]);
740 $out['onetime'] = trim($c[4]);
741 $out['ip'] = trim($c[5]);
742 $out['last_edited'] = trim($c[6]);
743 $out['next_code'] = trim($c[7]);
748 * Delete async transfert informations
750 function jirafeau_async_delete($ref)
753 if (file_exists(VAR_ASYNC
. $p . $ref)) {
754 unlink(VAR_ASYNC
. $p . $ref);
756 if (file_exists(VAR_ASYNC
. $p . $ref . '_data')) {
757 unlink(VAR_ASYNC
. $p . $ref . '_data');
759 $parse = VAR_ASYNC
. $p;
761 while (file_exists($parse)
762 && ($scan = scandir($parse))
763 && count($scan) == 2 // '.' and '..' folders => empty.
764 && basename($parse) != basename(VAR_ASYNC
)) {
766 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
771 * Init a new asynchronous upload.
772 * @param $finename Name of the file to send
773 * @param $one_time One time upload parameter
774 * @param $key eventual password (or blank)
775 * @param $time time limit
776 * @param $ip ip address of the client
777 * @return a string containing a temporary reference followed by a code or the string 'Error'
779 function jirafeau_async_init($filename, $type, $one_time, $key, $time, $ip)
783 /* Create temporary folder. */
786 $code = jirafeau_gen_random(4);
788 $ref = jirafeau_gen_random(32);
789 $p = VAR_ASYNC
. s2p($ref);
790 } while (file_exists($p));
791 @mkdir
($p, 0755, true);
792 if (!file_exists($p)) {
797 /* md5 password or empty */
800 $password = md5($key);
803 /* Store informations. */
805 $handle = fopen($p, 'w');
807 str_replace(NL
, '', trim($filename)) . NL
.
808 str_replace(NL
, '', trim($type)) . NL
. $password . NL
.
809 $time . NL
. ($one_time ?
'O' : 'R') . NL
. $ip . NL
.
810 time() . NL
. $code . NL
);
813 return $ref . NL
. $code ;
817 * Append a piece of file on the asynchronous upload.
818 * @param $ref asynchronous upload reference
819 * @param $file piece of data
820 * @param $code client code for this operation
821 * @param $max_file_size maximum allowed file size
822 * @return a string containing a next code to use or the string "Error"
824 function jirafeau_async_push($ref, $data, $code, $max_file_size)
826 /* Get async infos. */
827 $a = jirafeau_get_async_ref($ref);
829 /* Check some errors. */
831 ||
$a['next_code'] != "$code"
832 ||
empty($data['tmp_name'])
833 ||
!is_uploaded_file($data['tmp_name'])) {
840 $r_path = $data['tmp_name'];
841 $w_path = VAR_ASYNC
. $p . $ref . '_data';
843 /* Check that file size is not above upload limit. */
844 if ($max_file_size > 0 &&
845 filesize($r_path) +
filesize($w_path) > $max_file_size * 1024 * 1024) {
846 jirafeau_async_delete($ref);
850 /* Concatenate data. */
851 $r = fopen($r_path, 'r');
852 $w = fopen($w_path, 'a');
854 if (fwrite($w, fread($r, 1024)) === false) {
857 jirafeau_async_delete($ref);
865 /* Update async file. */
866 $code = jirafeau_gen_random(4);
867 $handle = fopen(VAR_ASYNC
. $p . $ref, 'w');
869 $a['file_name'] . NL
. $a['mime_type'] . NL
. $a['key'] . NL
.
870 $a['time'] . NL
. $a['onetime'] . NL
. $a['ip'] . NL
.
871 time() . NL
. $code . NL
);
877 * Finalyze an asynchronous upload.
878 * @param $ref asynchronous upload reference
879 * @param $code client code for this operation
880 * @param $crypt boolean asking to crypt or not
881 * @param $link_name_length link name length
882 * @return a string containing the download reference followed by a delete code or the string 'Error'
884 function jirafeau_async_end($ref, $code, $crypt, $link_name_length)
886 /* Get async infos. */
887 $a = jirafeau_get_async_ref($ref);
889 ||
$a['next_code'] != "$code") {
893 /* Generate link infos. */
894 $p = VAR_ASYNC
. s2p($ref) . $ref . "_data";
895 if (!file_exists($p)) {
901 if ($crypt == true && extension_loaded('mcrypt') == true) {
902 $crypt_key = jirafeau_encrypt_file($p, $p);
903 if (strlen($crypt_key) > 0) {
909 $size = filesize($p);
911 $delete_link_code = jirafeau_gen_random(5);
913 /* File already exist ? */
914 if (!file_exists(VAR_FILES
. $np)) {
915 @mkdir
(VAR_FILES
. $np, 0755, true);
917 if (!file_exists(VAR_FILES
. $np . $md5)) {
918 rename($p, VAR_FILES
. $np . $md5);
921 /* Increment or create count file. */
923 if (file_exists(VAR_FILES
. $np . $md5 . '_count')) {
924 $content = file(VAR_FILES
. $np . $md5. '_count');
925 $counter = trim($content[0]);
928 $handle = fopen(VAR_FILES
. $np . $md5. '_count', 'w');
929 fwrite($handle, $counter);
933 $link_tmp_name = VAR_LINKS
. $md5 . rand(0, 10000) . '.tmp';
934 $handle = fopen($link_tmp_name, 'w');
936 $a['file_name'] . NL
. $a['mime_type'] . NL
. $size . NL
.
937 $a['key'] . NL
. $a['time'] . NL
. $md5 . NL
. $a['onetime'] . NL
.
938 time() . NL
. $a['ip'] . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
940 $md5_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
941 $l = s2p("$md5_link");
942 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
943 !rename($link_tmp_name, VAR_LINKS
. $l . $md5_link)) {
947 /* Clean async upload. */
948 jirafeau_async_delete($ref);
949 return $md5_link . NL
. $delete_link_code . NL
. urlencode($crypt_key);
952 function jirafeau_crypt_create_iv($base, $size)
955 while (strlen($iv) < $size) {
958 $iv = substr($iv, 0, $size);
963 * Crypt file and returns decrypt key.
964 * @param $fp_src file path to the file to crypt.
965 * @param $fp_dst file path to the file to write crypted file (could be the same).
966 * @return decrypt key composed of the key and the iv separated by a point ('.')
968 function jirafeau_encrypt_file($fp_src, $fp_dst)
970 $fs = filesize($fp_src);
971 if ($fs === false ||
$fs == 0 ||
!(extension_loaded('mcrypt') == true)) {
975 /* Prepare module. */
976 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
978 $crypt_key = jirafeau_gen_random(10);
979 $md5_key = md5($crypt_key);
980 $iv = jirafeau_crypt_create_iv($md5_key, mcrypt_enc_get_iv_size($m));
982 mcrypt_generic_init($m, $md5_key, $iv);
984 $r = fopen($fp_src, 'r');
985 $w = fopen($fp_dst, 'c');
987 $enc = mcrypt_generic($m, fread($r, 1024));
988 if (fwrite($w, $enc) === false) {
995 mcrypt_generic_deinit($m);
996 mcrypt_module_close($m);
1002 * @param $fp_src file path to the file to decrypt.
1003 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1004 * @param $k string composed of the key and the iv separated by a point ('.')
1005 * @return key used to decrypt. a string of length 0 is returned if failed.
1007 function jirafeau_decrypt_file($fp_src, $fp_dst, $k)
1009 $fs = filesize($fp_src);
1010 if ($fs === false ||
$fs == 0 ||
extension_loaded('mcrypt') == false) {
1015 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1016 /* Extract key and iv. */
1018 $md5_key = md5($crypt_key);
1019 $iv = jirafeau_crypt_create_iv($md5_key, mcrypt_enc_get_iv_size($m));
1021 $r = fopen($fp_src, 'r');
1022 $w = fopen($fp_dst, 'c');
1024 $dec = mdecrypt_generic($m, fread($r, 1024));
1025 if (fwrite($w, $dec) === false) {
1032 mcrypt_generic_deinit($m);
1033 mcrypt_module_close($m);
1038 * Check if Jirafeau is password protected for visitors.
1039 * @return true if Jirafeau is password protected, false otherwise.
1041 function jirafeau_has_upload_password($cfg)
1043 return count($cfg['upload_password']) > 0;
1047 * Challenge password for a visitor.
1048 * @param $password password to be challenged
1049 * @return true if password is valid, false otherwise.
1051 function jirafeau_challenge_upload_password($cfg, $password)
1053 if (!jirafeau_has_upload_password($cfg)) {
1056 foreach ($cfg['upload_password'] as $p) {
1057 if ($password == $p) {
1065 * Test if visitor's IP is authorized to upload.
1066 * @param $ip IP to be challenged
1067 * @return true if IP is authorized, false otherwise.
1069 function jirafeau_challenge_upload_ip($cfg, $ip)
1071 if (count($cfg['upload_ip']) == 0) {
1074 foreach ($cfg['upload_ip'] as $i) {
1078 // CIDR test for IPv4 only.
1079 if (strpos($i, '/') !== false) {
1080 list($subnet, $mask) = explode('/', $i);
1081 if ((ip2long($ip) & ~
((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
1090 * Test if visitor's IP is authorized or password is supplied and authorized
1091 * @param $ip IP to be challenged
1092 * @param $password password to be challenged
1093 * @return true if access is valid, false otherwise.
1095 function jirafeau_challenge_upload ($cfg, $ip, $password)
1097 // Allow if no ip restrictaion and no password restriction
1098 if ((count ($cfg['upload_ip']) == 0) and (count ($cfg['upload_password']) == 0)) {
1102 // Allow if ip is in array
1103 foreach ($cfg['upload_ip'] as $i) {
1107 // CIDR test for IPv4 only.
1108 if (strpos ($i, '/') !== false)
1110 list ($subnet, $mask) = explode('/', $i);
1111 if ((ip2long ($ip) & ~
((1 << (32 - $mask)) - 1) ) == ip2long ($subnet)) {
1116 if (!jirafeau_has_upload_password($cfg)) {
1120 foreach ($cfg['upload_password'] as $p) {
1121 if ($password == $p) {
1128 /** Tell if we have some HTTP headers generated by a proxy */
1129 function has_http_forwarded()
1132 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1133 !empty($_SERVER['http_X_forwarded_for']);
1137 * Generate IP list from HTTP headers generated by a proxy
1138 * @return array of IP strings
1140 function get_ip_list_http_forwarded()
1143 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1144 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1148 foreach ($l as $ip) {
1149 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1152 if (!empty($_SERVER['http_X_forwarded_for'])) {
1153 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1154 foreach ($l as $ip) {
1155 // Separate IP from port
1156 $ipa = explode(':', $ip);
1157 if ($ipa === false) {
1161 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1168 * Get the ip address of the client from REMOTE_ADDR
1169 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1170 * @returns the client ip address
1172 function get_ip_address($cfg)
1174 $remote = $_SERVER['REMOTE_ADDR'];
1175 if (count($cfg['proxy_ip']) == 0 ||
!has_http_forwarded()) {
1179 $ip_list = get_ip_list_http_forwarded();
1180 if (count($ip_list) == 0) {
1184 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1185 if ($remote != $proxy_ip) {
1188 // Take the last IP (the one which has been set by the defined proxy).
1189 return end($ip_list);
1195 * Convert hexadecimal string to base64
1197 function hex_to_base64($hex)
1200 foreach (str_split($hex, 2) as $pair) {
1201 $b .= chr(hexdec($pair));
1203 return base64_encode($b);
1207 * Read alias informations
1208 * @return array containing informations.
1210 function jirafeau_get_alias($hash)
1213 $link = VAR_ALIAS
. s2p("$hash") . $hash;
1215 if (!file_exists($link)) {
1220 $out['md5_password'] = trim($c[0]);
1221 $out['ip'] = trim($c[1]);
1222 $out['update_date'] = trim($c[2]);
1223 $out['destination'] = trim($c[3], NL
);
1228 /** Create an alias to a jirafeau's link.
1229 * @param $alias alias name
1230 * @param $destination reference of the destination
1231 * @param $password password to protect alias
1232 * @param $ip client's IP
1233 * @return a string containing the edit code of the alias or the string "Error"
1235 function jirafeau_alias_create($alias, $destination, $password, $ip)
1237 /* Check that alias and password are long enough. */
1238 if (strlen($alias) < 8 ||
1239 strlen($alias) > 32 ||
1240 strlen($password) < 8 ||
1241 strlen($password) > 32) {
1245 /* Check that destination exists. */
1246 $l = jirafeau_get_link($destination);
1251 /* Check that alias does not already exists. */
1252 $alias = md5($alias);
1253 $p = VAR_ALIAS
. s2p($alias);
1254 if (file_exists($p)) {
1258 /* Create alias folder. */
1259 @mkdir
($p, 0755, true);
1260 if (!file_exists($p)) {
1264 /* Generate password. */
1265 $md5_password = md5($password);
1267 /* Store informations. */
1269 $handle = fopen($p, 'w');
1271 $md5_password . NL
.
1280 /** Update an alias.
1281 * @param $alias alias to update
1282 * @param $destination reference of the new destination
1283 * @param $password password to protect alias
1284 * @param $new_password optional new password to protect alias
1285 * @param $ip client's IP
1286 * @return "Ok" or "Error" string
1288 function jirafeau_alias_update($alias, $destination, $password,
1291 $alias = md5($alias);
1292 /* Check that alias exits. */
1293 $a = jirafeau_get_alias($alias);
1298 /* Check that destination exists. */
1299 $l = jirafeau_get_link($a["destination"]);
1304 /* Check password. */
1305 if ($a["md5_password"] != md5($password)) {
1309 $p = $a['md5_password'];
1310 if (strlen($new_password) >= 8 &&
1311 strlen($new_password) <= 32) {
1312 $p = md5($new_password);
1313 } elseif (strlen($new_password) > 0) {
1317 /* Rewrite informations. */
1318 $p = VAR_ALIAS
. s2p($alias) . $alias;
1319 $handle = fopen($p, 'w');
1330 * @param $alias alias to get
1331 * @return alias destination or "Error" string
1333 function jirafeau_alias_get($alias)
1335 $alias = md5($alias);
1336 /* Check that alias exits. */
1337 $a = jirafeau_get_alias($alias);
1342 return $a['destination'];
1345 function jirafeau_clean_rm_alias($alias)
1348 if (file_exists(VAR_ALIAS
. $p . $alias)) {
1349 unlink(VAR_ALIAS
. $p . $alias);
1351 $parse = VAR_ALIAS
. $p;
1353 while (file_exists($parse)
1354 && ($scan = scandir($parse))
1355 && count($scan) == 2 // '.' and '..' folders => empty.
1356 && basename($parse) != basename(VAR_ALIAS
)) {
1358 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
1362 /** Delete an alias.
1363 * @param $alias alias to delete
1364 * @param $password password to protect alias
1365 * @return "Ok" or "Error" string
1367 function jirafeau_alias_delete($alias, $password)
1369 $alias = md5($alias);
1370 /* Check that alias exits. */
1371 $a = jirafeau_get_alias($alias);
1376 /* Check password. */
1377 if ($a["md5_password"] != md5($password)) {
1381 jirafeau_clean_rm_alias($alias);
1386 * Replace markers in templates.
1388 * Available markers have the scheme "###MARKERNAME###".
1390 * @param $content string Template text with markers
1391 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1392 * @return Template with replaced markers
1394 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1397 '/###ORGANISATION###/',
1398 '/###CONTACTPERSON###/',
1401 $replacements = array(
1402 $GLOBALS['cfg']['organisation'],
1403 $GLOBALS['cfg']['contactperson'],
1404 $GLOBALS['cfg']['web_root']
1406 $content = preg_replace($patterns, $replacements, $content);
1408 if (true === $htmllinebreaks) {
1409 $content = nl2br($content);
patrick-canterino.de