]>
git.p6c8.net - jirafeau.git/blob - lib/functions.php
d844e50627cb749075484056b8da2aebc0b867f8
3 * Jirafeau, your web file repository
4 * Copyright (C) 2008 Julien "axolotl" BERNARD <axolotl@magieeternelle.org>
5 * Copyright (C) 2015 Jerome Jutteau <j.jutteau@gmail.com>
6 * Copyright (C) 2015 Nicola Spanti (RyDroid) <dev@nicola-spanti.info>
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU Affero General Public License as
10 * published by the Free Software Foundation, either version 3 of the
11 * License, or (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Affero General Public License for more details.
18 * You should have received a copy of the GNU Affero General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 * Transform a string in a path by seperating each letters by a '/'.
24 * @return path finishing with a '/'
29 for ($i = 0; $i < strlen($s); $i++
) {
36 * Convert base 16 to base 64
37 * @returns A string based on 64 characters (0-9, a-z, A-Z, "-" and "_")
39 function base_16_to_64($num)
41 $m = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_';
42 $hex2bin = array('0000', # 0
61 # Convert long hex string to bin.
63 for ($i = 0; $i < $size; $i++
) {
64 $b .= $hex2bin{hexdec($num{$i})};
66 # Convert long bin to base 64.
68 for ($i = $size - 6; $i >= 0; $i -= 6) {
69 $o = $m{bindec(substr($b, $i, 6))} . $o;
71 # Some few bits remaining ?
72 if ($i < 0 && $i > -6) {
73 $o = $m{bindec(substr($b, 0, $i +
6))} . $o;
79 * Generate a random code.
80 * @param $l code length
81 * @return random code.
83 function jirafeau_gen_random($l)
90 for ($i = 0; $i < $l; $i++
) {
91 $code .= dechex(rand(0, 15));
99 if (isset($_SERVER['HTTPS'])) {
100 if ('on' == strtolower($_SERVER['HTTPS']) ||
101 '1' == $_SERVER['HTTPS']) {
104 } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
106 } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
107 if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
114 function jirafeau_human_size($octets)
116 $u = array('B', 'KB', 'MB', 'GB', 'TB');
117 $o = max($octets, 0);
118 $p = min(floor(($o ?
log($o) : 0) / log(1024)), count($u) - 1);
120 return round($o, 1) . $u[$p];
123 // Convert UTC timestamp to a datetime field
124 function jirafeau_get_datetimefield($timestamp)
126 $content = '<span class="datetime" data-datetime="' . strftime('%Y-%m-%d %H:%M', $timestamp) . '">'
127 . strftime('%Y-%m-%d %H:%M', $timestamp) . ' (GMT)</span>';
131 function jirafeau_fatal_error($errorText, $cfg = array())
133 echo '<div class="error"><h2>Error</h2><p>' . $errorText . '</p></div>';
134 require(JIRAFEAU_ROOT
. 'lib/template/footer.php');
138 function jirafeau_clean_rm_link($link)
141 if (file_exists(VAR_LINKS
. $p . $link)) {
142 unlink(VAR_LINKS
. $p . $link);
144 $parse = VAR_LINKS
. $p;
146 while (file_exists($parse)
147 && ($scan = scandir($parse))
148 && count($scan) == 2 // '.' and '..' folders => empty.
149 && basename($parse) != basename(VAR_LINKS
)) {
151 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
155 function jirafeau_clean_rm_file($md5)
158 $f = VAR_FILES
. $p . $md5;
159 if (file_exists($f) && is_file($f)) {
162 if (file_exists($f . '_count') && is_file($f . '_count')) {
163 unlink($f . '_count');
165 $parse = VAR_FILES
. $p;
167 while (file_exists($parse)
168 && ($scan = scandir($parse))
169 && count($scan) == 2 // '.' and '..' folders => empty.
170 && basename($parse) != basename(VAR_FILES
)) {
172 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
177 * transforms a php.ini string representing a value in an integer
178 * @param $value the value from php.ini
179 * @returns an integer for this value
181 function jirafeau_ini_to_bytes($value)
183 $modifier = substr($value, -1);
184 $bytes = substr($value, 0, -1);
185 switch (strtoupper($modifier)) {
201 * gets the maximum upload size according to php.ini
202 * @returns the maximum upload size in bytes
204 function jirafeau_get_max_upload_size_bytes()
206 return min(jirafeau_ini_to_bytes(ini_get('post_max_size')),
207 jirafeau_ini_to_bytes(ini_get('upload_max_filesize')));
211 * gets the maximum upload size according to php.ini
212 * @returns the maximum upload size string
214 function jirafeau_get_max_upload_size()
216 return jirafeau_human_size(
217 min(jirafeau_ini_to_bytes(ini_get('post_max_size')),
218 jirafeau_ini_to_bytes(ini_get('upload_max_filesize'))));
222 * gets a string explaining the error
223 * @param $code the error code
224 * @returns a string explaining the error
226 function jirafeau_upload_errstr($code)
229 case UPLOAD_ERR_INI_SIZE
:
230 case UPLOAD_ERR_FORM_SIZE
:
231 return t('Your file exceeds the maximum authorized file size. ');
233 case UPLOAD_ERR_PARTIAL
:
234 case UPLOAD_ERR_NO_FILE
:
236 t('Your file was not uploaded correctly. You may succeed in retrying. ');
238 case UPLOAD_ERR_NO_TMP_DIR
:
239 case UPLOAD_ERR_CANT_WRITE
:
240 case UPLOAD_ERR_EXTENSION
:
241 return t('Internal error. You may not succeed in retrying. ');
243 return t('Unknown error. ');
246 /** Remove link and it's file
247 * @param $link the link's name (hash)
250 function jirafeau_delete_link($link)
252 $l = jirafeau_get_link($link);
257 jirafeau_clean_rm_link($link);
263 if (file_exists(VAR_FILES
. $p . $md5. '_count')) {
264 $content = file(VAR_FILES
. $p . $md5. '_count');
265 $counter = trim($content[0]);
270 $handle = fopen(VAR_FILES
. $p . $md5. '_count', 'w');
271 fwrite($handle, $counter);
276 jirafeau_clean_rm_file($md5);
281 * Delete a file and it's links.
283 function jirafeau_delete_file($md5)
286 /* Get all links files. */
287 $stack = array(VAR_LINKS
);
288 while (($d = array_shift($stack)) && $d != null) {
291 foreach ($dir as $node) {
292 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
293 preg_match('/\.tmp/i', "$node")) {
297 if (is_dir($d . $node)) {
298 /* Push new found directory. */
299 $stack[] = $d . $node . '/';
300 } elseif (is_file($d . $node)) {
301 /* Read link informations. */
302 $l = jirafeau_get_link(basename($node));
306 if ($l['md5'] == $md5) {
308 jirafeau_delete_link($node);
313 jirafeau_clean_rm_file($md5);
318 * handles an uploaded file
319 * @param $file the file struct given by $_FILE[]
320 * @param $one_time_download is the file a one time download ?
321 * @param $key if not empty, protect the file with this key
322 * @param $time the time of validity of the file
323 * @param $ip uploader's ip
324 * @param $crypt boolean asking to crypt or not
325 * @param $link_name_length size of the link name
326 * @returns an array containing some information
327 * 'error' => information on possible errors
328 * 'link' => the link name of the uploaded file
329 * 'delete_link' => the link code to delete file
331 function jirafeau_upload($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length)
333 if (empty($file['tmp_name']) ||
!is_uploaded_file($file['tmp_name'])) {
336 array('has_error' => true,
337 'why' => jirafeau_upload_errstr($file['error'])),
339 'delete_link' => ''));
342 /* array representing no error */
343 $noerr = array('has_error' => false, 'why' => '');
345 /* Crypt file if option is enabled. */
348 if ($crypt == true && !(extension_loaded('mcrypt') == true)) {
349 error_log("PHP extension mcrypt not loaded, won't encrypt in Jirafeau");
351 if ($crypt == true && extension_loaded('mcrypt') == true) {
352 $crypt_key = jirafeau_encrypt_file($file['tmp_name'], $file['tmp_name']);
353 if (strlen($crypt_key) > 0) {
358 /* file informations */
359 $md5 = md5_file($file['tmp_name']);
360 $name = str_replace(NL
, '', trim($file['name']));
361 $mime_type = $file['type'];
362 $size = $file['size'];
364 /* does file already exist ? */
367 if (file_exists(VAR_FILES
. $p . $md5)) {
368 $rc = unlink($file['tmp_name']);
369 } elseif ((file_exists(VAR_FILES
. $p) || @mkdir
(VAR_FILES
. $p, 0755, true))
370 && move_uploaded_file($file['tmp_name'], VAR_FILES
. $p . $md5)) {
376 array('has_error' => true,
377 'why' => t('Internal error during file creation.')),
379 'delete_link' => ''));
382 /* Increment or create count file. */
384 if (file_exists(VAR_FILES
. $p . $md5 . '_count')) {
385 $content = file(VAR_FILES
. $p . $md5. '_count');
386 $counter = trim($content[0]);
389 $handle = fopen(VAR_FILES
. $p . $md5. '_count', 'w');
390 fwrite($handle, $counter);
393 /* Create delete code. */
394 $delete_link_code = jirafeau_gen_random(5);
396 /* md5 password or empty. */
399 $password = md5($key);
402 /* create link file */
403 $link_tmp_name = VAR_LINKS
. $md5 . rand(0, 10000) . '.tmp';
404 $handle = fopen($link_tmp_name, 'w');
406 $name . NL
. $mime_type . NL
. $size . NL
. $password . NL
. $time .
407 NL
. $md5. NL
. ($one_time_download ?
'O' : 'R') . NL
. time() .
408 NL
. $ip . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
410 $md5_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
411 $l = s2p("$md5_link");
412 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
413 !rename($link_tmp_name, VAR_LINKS
. $l . $md5_link)) {
414 if (file_exists($link_tmp_name)) {
415 unlink($link_tmp_name);
420 $handle = fopen(VAR_FILES
. $p . $md5. '_count', 'w');
421 fwrite($handle, $counter);
424 jirafeau_clean_rm_file($md5_link);
428 array('has_error' => true,
429 'why' => t('Internal error during file creation. ')),
431 'delete_link' => '');
433 return array( 'error' => $noerr,
435 'delete_link' => $delete_link_code,
436 'crypt_key' => $crypt_key);
440 * Tells if a mime-type is viewable in a browser
441 * @param $mime the mime type
442 * @returns a boolean telling if a mime type is viewable
444 function jirafeau_is_viewable($mime)
447 /* Actually, verify if mime-type is an image or a text. */
448 $viewable = array('image', 'text', 'video', 'audio');
449 $decomposed = explode('/', $mime);
450 return in_array($decomposed[0], $viewable);
455 // Error handling functions.
456 //! Global array that contains all registered errors.
457 $error_list = array();
460 * Adds an error to the list of errors.
461 * @param $title the error's title
462 * @param $description is a human-friendly description of the problem.
464 function add_error($title, $description)
467 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
471 * Informs whether any error has been registered yet.
472 * @return true if there are errors.
477 return !empty($error_list);
481 * Displays all the errors.
483 function show_errors()
487 echo '<div class="error">';
488 foreach ($error_list as $error) {
495 function check_errors($cfg)
497 if (file_exists(JIRAFEAU_ROOT
. 'install.php')
498 && !($cfg['installation_done'] === true)) {
499 header('Location: install.php');
503 /* check if the destination dirs are writable */
504 $writable = is_writable(VAR_FILES
) && is_writable(VAR_LINKS
);
506 /* Checking for errors. */
507 if (!is_writable(VAR_FILES
)) {
508 add_error(t('The file directory is not writable!'), VAR_FILES
);
511 if (!is_writable(VAR_LINKS
)) {
512 add_error(t('The link directory is not writable!'), VAR_LINKS
);
515 if (!is_writable(VAR_ASYNC
)) {
516 add_error(t('The async directory is not writable!'), VAR_ASYNC
);
521 * Read link informations
522 * @return array containing informations.
524 function jirafeau_get_link($hash)
527 $link = VAR_LINKS
. s2p("$hash") . $hash;
529 if (!file_exists($link)) {
534 $out['file_name'] = trim($c[0]);
535 $out['mime_type'] = trim($c[1]);
536 $out['file_size'] = trim($c[2]);
537 $out['key'] = trim($c[3], NL
);
538 $out['time'] = trim($c[4]);
539 $out['md5'] = trim($c[5]);
540 $out['onetime'] = trim($c[6]);
541 $out['upload_date'] = trim($c[7]);
542 $out['ip'] = trim($c[8]);
543 $out['link_code'] = trim($c[9]);
544 $out['crypted'] = trim($c[10]) == 'C';
550 * List files in admin interface.
552 function jirafeau_admin_list($name, $file_hash, $link_hash)
554 echo '<fieldset><legend>';
556 echo t('Filename') . ": $name ";
558 if (!empty($file_hash)) {
559 echo t('file') . ": $file_hash ";
561 if (!empty($link_hash)) {
562 echo t('link') . ": $link_hash ";
564 if (empty($name) && empty($file_hash) && empty($link_hash)) {
565 echo t('List all files');
570 echo '<td>' . t('Filename') . '</td>';
571 echo '<td>' . t('Type') . '</td>';
572 echo '<td>' . t('Size') . '</td>';
573 echo '<td>' . t('Expire') . '</td>';
574 echo '<td>' . t('Onetime') . '</td>';
575 echo '<td>' . t('Upload date') . '</td>';
576 echo '<td>' . t('Origin') . '</td>';
577 echo '<td>' . t('Action') . '</td>';
580 /* Get all links files. */
581 $stack = array(VAR_LINKS
);
582 while (($d = array_shift($stack)) && $d != null) {
584 foreach ($dir as $node) {
585 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
586 preg_match('/\.tmp/i', "$node")) {
589 if (is_dir($d . $node)) {
590 /* Push new found directory. */
591 $stack[] = $d . $node . '/';
592 } elseif (is_file($d . $node)) {
593 /* Read link informations. */
594 $l = jirafeau_get_link($node);
600 if (!empty($name) && !preg_match("/$name/i", htmlspecialchars($l['file_name']))) {
603 if (!empty($file_hash) && $file_hash != $l['md5']) {
606 if (!empty($link_hash) && $link_hash != $node) {
609 /* Print link informations. */
612 '<strong><a id="upload_link" href="' . JIRAFEAU_ABSPREFIX
. 'f.php?h='. htmlspecialchars($node) .'" title="' .
613 t('Download page') . '">' . htmlspecialchars($l['file_name']) . '</a></strong>';
615 echo '<td>' . $l['mime_type'] . '</td>';
616 echo '<td>' . jirafeau_human_size($l['file_size']) . '</td>';
617 echo '<td>' . ($l['time'] == -1 ?
'∞' : jirafeau_get_datetimefield($l['time'])) . '</td>';
619 if ($l['onetime'] == 'O') {
625 echo '<td>' . jirafeau_get_datetimefield($l['upload_date']) . '</td>';
626 echo '<td>' . $l['ip'] . '</td>';
628 '<form method="post">' .
629 '<input type = "hidden" name = "action" value = "download"/>' .
630 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
631 '<input type = "submit" value = "' . t('Download') . '" />' .
633 '<form method="post">' .
634 '<input type = "hidden" name = "action" value = "delete_link"/>' .
635 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
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 '<input type = "submit" value = "' . t('Del file and links') . '" />' .
648 echo '</table></fieldset>';
652 * Clean expired files.
653 * @return number of cleaned files.
655 function jirafeau_admin_clean()
658 /* Get all links files. */
659 $stack = array(VAR_LINKS
);
660 while (($d = array_shift($stack)) && $d != null) {
663 foreach ($dir as $node) {
664 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
665 preg_match('/\.tmp/i', "$node")) {
669 if (is_dir($d . $node)) {
670 /* Push new found directory. */
671 $stack[] = $d . $node . '/';
672 } elseif (is_file($d . $node)) {
673 /* Read link informations. */
674 $l = jirafeau_get_link(basename($node));
679 if ($l['time'] > 0 && $l['time'] < time() ||
// expired
680 !file_exists(VAR_FILES
. $p . $l['md5']) ||
// invalid
681 !file_exists(VAR_FILES
. $p . $l['md5'] . '_count')) { // invalid
682 jirafeau_delete_link($node);
693 * Clean old async transferts.
694 * @return number of cleaned files.
696 function jirafeau_admin_clean_async()
699 /* Get all links files. */
700 $stack = array(VAR_ASYNC
);
701 while (($d = array_shift($stack)) && $d != null) {
704 foreach ($dir as $node) {
705 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
706 preg_match('/\.tmp/i', "$node")) {
710 if (is_dir($d . $node)) {
711 /* Push new found directory. */
712 $stack[] = $d . $node . '/';
713 } elseif (is_file($d . $node)) {
714 /* Read async informations. */
715 $a = jirafeau_get_async_ref(basename($node));
719 /* Delete transferts older than 1 hour. */
720 if (time() - $a['last_edited'] > 3600) {
721 jirafeau_async_delete(basename($node));
730 * Read async transfert informations
731 * @return array containing informations.
733 function jirafeau_get_async_ref($ref)
736 $refinfos = VAR_ASYNC
. s2p("$ref") . "$ref";
738 if (!file_exists($refinfos)) {
742 $c = file($refinfos);
743 $out['file_name'] = trim($c[0]);
744 $out['mime_type'] = trim($c[1]);
745 $out['key'] = trim($c[2], NL
);
746 $out['time'] = trim($c[3]);
747 $out['onetime'] = trim($c[4]);
748 $out['ip'] = trim($c[5]);
749 $out['last_edited'] = trim($c[6]);
750 $out['next_code'] = trim($c[7]);
755 * Delete async transfert informations
757 function jirafeau_async_delete($ref)
760 if (file_exists(VAR_ASYNC
. $p . $ref)) {
761 unlink(VAR_ASYNC
. $p . $ref);
763 if (file_exists(VAR_ASYNC
. $p . $ref . '_data')) {
764 unlink(VAR_ASYNC
. $p . $ref . '_data');
766 $parse = VAR_ASYNC
. $p;
768 while (file_exists($parse)
769 && ($scan = scandir($parse))
770 && count($scan) == 2 // '.' and '..' folders => empty.
771 && basename($parse) != basename(VAR_ASYNC
)) {
773 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
778 * Init a new asynchronous upload.
779 * @param $finename Name of the file to send
780 * @param $one_time One time upload parameter
781 * @param $key eventual password (or blank)
782 * @param $time time limit
783 * @param $ip ip address of the client
784 * @return a string containing a temporary reference followed by a code or the string 'Error'
786 function jirafeau_async_init($filename, $type, $one_time, $key, $time, $ip)
790 /* Create temporary folder. */
793 $code = jirafeau_gen_random(4);
795 $ref = jirafeau_gen_random(32);
796 $p = VAR_ASYNC
. s2p($ref);
797 } while (file_exists($p));
798 @mkdir
($p, 0755, true);
799 if (!file_exists($p)) {
804 /* md5 password or empty */
807 $password = md5($key);
810 /* Store informations. */
812 $handle = fopen($p, 'w');
814 str_replace(NL
, '', trim($filename)) . NL
.
815 str_replace(NL
, '', trim($type)) . NL
. $password . NL
.
816 $time . NL
. ($one_time ?
'O' : 'R') . NL
. $ip . NL
.
817 time() . NL
. $code . NL
);
820 return $ref . NL
. $code ;
824 * Append a piece of file on the asynchronous upload.
825 * @param $ref asynchronous upload reference
826 * @param $file piece of data
827 * @param $code client code for this operation
828 * @param $max_file_size maximum allowed file size
829 * @return a string containing a next code to use or the string "Error"
831 function jirafeau_async_push($ref, $data, $code, $max_file_size)
833 /* Get async infos. */
834 $a = jirafeau_get_async_ref($ref);
836 /* Check some errors. */
838 ||
$a['next_code'] != "$code"
839 ||
empty($data['tmp_name'])
840 ||
!is_uploaded_file($data['tmp_name'])) {
847 $r_path = $data['tmp_name'];
848 $w_path = VAR_ASYNC
. $p . $ref . '_data';
850 /* Check that file size is not above upload limit. */
851 if ($max_file_size > 0 &&
852 filesize($r_path) +
filesize($w_path) > $max_file_size * 1024 * 1024) {
853 jirafeau_async_delete($ref);
857 /* Concatenate data. */
858 $r = fopen($r_path, 'r');
859 $w = fopen($w_path, 'a');
861 if (fwrite($w, fread($r, 1024)) === false) {
864 jirafeau_async_delete($ref);
872 /* Update async file. */
873 $code = jirafeau_gen_random(4);
874 $handle = fopen(VAR_ASYNC
. $p . $ref, 'w');
876 $a['file_name'] . NL
. $a['mime_type'] . NL
. $a['key'] . NL
.
877 $a['time'] . NL
. $a['onetime'] . NL
. $a['ip'] . NL
.
878 time() . NL
. $code . NL
);
884 * Finalyze an asynchronous upload.
885 * @param $ref asynchronous upload reference
886 * @param $code client code for this operation
887 * @param $crypt boolean asking to crypt or not
888 * @param $link_name_length link name length
889 * @return a string containing the download reference followed by a delete code or the string 'Error'
891 function jirafeau_async_end($ref, $code, $crypt, $link_name_length)
893 /* Get async infos. */
894 $a = jirafeau_get_async_ref($ref);
896 ||
$a['next_code'] != "$code") {
900 /* Generate link infos. */
901 $p = VAR_ASYNC
. s2p($ref) . $ref . "_data";
902 if (!file_exists($p)) {
908 if ($crypt == true && extension_loaded('mcrypt') == true) {
909 $crypt_key = jirafeau_encrypt_file($p, $p);
910 if (strlen($crypt_key) > 0) {
916 $size = filesize($p);
918 $delete_link_code = jirafeau_gen_random(5);
920 /* File already exist ? */
921 if (!file_exists(VAR_FILES
. $np)) {
922 @mkdir
(VAR_FILES
. $np, 0755, true);
924 if (!file_exists(VAR_FILES
. $np . $md5)) {
925 rename($p, VAR_FILES
. $np . $md5);
928 /* Increment or create count file. */
930 if (file_exists(VAR_FILES
. $np . $md5 . '_count')) {
931 $content = file(VAR_FILES
. $np . $md5. '_count');
932 $counter = trim($content[0]);
935 $handle = fopen(VAR_FILES
. $np . $md5. '_count', 'w');
936 fwrite($handle, $counter);
940 $link_tmp_name = VAR_LINKS
. $md5 . rand(0, 10000) . '.tmp';
941 $handle = fopen($link_tmp_name, 'w');
943 $a['file_name'] . NL
. $a['mime_type'] . NL
. $size . NL
.
944 $a['key'] . NL
. $a['time'] . NL
. $md5 . NL
. $a['onetime'] . NL
.
945 time() . NL
. $a['ip'] . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
947 $md5_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
948 $l = s2p("$md5_link");
949 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
950 !rename($link_tmp_name, VAR_LINKS
. $l . $md5_link)) {
954 /* Clean async upload. */
955 jirafeau_async_delete($ref);
956 return $md5_link . NL
. $delete_link_code . NL
. urlencode($crypt_key);
959 function jirafeau_crypt_create_iv($base, $size)
962 while (strlen($iv) < $size) {
965 $iv = substr($iv, 0, $size);
970 * Crypt file and returns decrypt key.
971 * @param $fp_src file path to the file to crypt.
972 * @param $fp_dst file path to the file to write crypted file (could be the same).
973 * @return decrypt key composed of the key and the iv separated by a point ('.')
975 function jirafeau_encrypt_file($fp_src, $fp_dst)
977 $fs = filesize($fp_src);
978 if ($fs === false ||
$fs == 0 ||
!(extension_loaded('mcrypt') == true)) {
982 /* Prepare module. */
983 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
985 $crypt_key = jirafeau_gen_random(10);
986 $md5_key = md5($crypt_key);
987 $iv = jirafeau_crypt_create_iv($md5_key, mcrypt_enc_get_iv_size($m));
989 mcrypt_generic_init($m, $md5_key, $iv);
991 $r = fopen($fp_src, 'r');
992 $w = fopen($fp_dst, 'c');
994 $enc = mcrypt_generic($m, fread($r, 1024));
995 if (fwrite($w, $enc) === false) {
1002 mcrypt_generic_deinit($m);
1003 mcrypt_module_close($m);
1009 * @param $fp_src file path to the file to decrypt.
1010 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1011 * @param $k string composed of the key and the iv separated by a point ('.')
1012 * @return key used to decrypt. a string of length 0 is returned if failed.
1014 function jirafeau_decrypt_file($fp_src, $fp_dst, $k)
1016 $fs = filesize($fp_src);
1017 if ($fs === false ||
$fs == 0 ||
extension_loaded('mcrypt') == false) {
1022 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1023 /* Extract key and iv. */
1025 $md5_key = md5($crypt_key);
1026 $iv = jirafeau_crypt_create_iv($md5_key, mcrypt_enc_get_iv_size($m));
1028 $r = fopen($fp_src, 'r');
1029 $w = fopen($fp_dst, 'c');
1031 $dec = mdecrypt_generic($m, fread($r, 1024));
1032 if (fwrite($w, $dec) === false) {
1039 mcrypt_generic_deinit($m);
1040 mcrypt_module_close($m);
1045 * Check if Jirafeau is password protected for visitors.
1046 * @return true if Jirafeau is password protected, false otherwise.
1048 function jirafeau_has_upload_password($cfg)
1050 return count($cfg['upload_password']) > 0;
1054 * Challenge password for a visitor.
1055 * @param $password password to be challenged
1056 * @return true if password is valid, false otherwise.
1058 function jirafeau_challenge_upload_password($cfg, $password)
1060 if (!jirafeau_has_upload_password($cfg)) {
1063 foreach ($cfg['upload_password'] as $p) {
1064 if ($password == $p) {
1072 * Test if visitor's IP is authorized to upload.
1073 * @param $ip IP to be challenged
1074 * @return true if IP is authorized, false otherwise.
1076 function jirafeau_challenge_upload_ip($cfg, $ip)
1078 if (count($cfg['upload_ip']) == 0) {
1081 foreach ($cfg['upload_ip'] as $i) {
1085 // CIDR test for IPv4 only.
1086 if (strpos($i, '/') !== false) {
1087 list($subnet, $mask) = explode('/', $i);
1088 if ((ip2long($ip) & ~
((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
1097 * Test if visitor's IP is authorized or password is supplied and authorized
1098 * @param $ip IP to be challenged
1099 * @param $password password to be challenged
1100 * @return true if access is valid, false otherwise.
1102 function jirafeau_challenge_upload ($cfg, $ip, $password)
1104 // Allow if no ip restrictaion and no password restriction
1105 if ((count ($cfg['upload_ip']) == 0) and (count ($cfg['upload_password']) == 0)) {
1109 // Allow if ip is in array
1110 foreach ($cfg['upload_ip'] as $i) {
1114 // CIDR test for IPv4 only.
1115 if (strpos ($i, '/') !== false)
1117 list ($subnet, $mask) = explode('/', $i);
1118 if ((ip2long ($ip) & ~
((1 << (32 - $mask)) - 1) ) == ip2long ($subnet)) {
1123 if (!jirafeau_has_upload_password($cfg)) {
1127 foreach ($cfg['upload_password'] as $p) {
1128 if ($password == $p) {
1135 /** Tell if we have some HTTP headers generated by a proxy */
1136 function has_http_forwarded()
1139 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1140 !empty($_SERVER['http_X_forwarded_for']);
1144 * Generate IP list from HTTP headers generated by a proxy
1145 * @return array of IP strings
1147 function get_ip_list_http_forwarded()
1150 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1151 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1155 foreach ($l as $ip) {
1156 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1159 if (!empty($_SERVER['http_X_forwarded_for'])) {
1160 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1161 foreach ($l as $ip) {
1162 // Separate IP from port
1163 $ipa = explode(':', $ip);
1164 if ($ipa === false) {
1168 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1175 * Get the ip address of the client from REMOTE_ADDR
1176 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1177 * @returns the client ip address
1179 function get_ip_address($cfg)
1181 $remote = $_SERVER['REMOTE_ADDR'];
1182 if (count($cfg['proxy_ip']) == 0 ||
!has_http_forwarded()) {
1186 $ip_list = get_ip_list_http_forwarded();
1187 if (count($ip_list) == 0) {
1191 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1192 if ($remote != $proxy_ip) {
1195 // Take the last IP (the one which has been set by the defined proxy).
1196 return end($ip_list);
1202 * Convert hexadecimal string to base64
1204 function hex_to_base64($hex)
1207 foreach (str_split($hex, 2) as $pair) {
1208 $b .= chr(hexdec($pair));
1210 return base64_encode($b);
1214 * Read alias informations
1215 * @return array containing informations.
1217 function jirafeau_get_alias($hash)
1220 $link = VAR_ALIAS
. s2p("$hash") . $hash;
1222 if (!file_exists($link)) {
1227 $out['md5_password'] = trim($c[0]);
1228 $out['ip'] = trim($c[1]);
1229 $out['update_date'] = trim($c[2]);
1230 $out['destination'] = trim($c[3], NL
);
1235 /** Create an alias to a jirafeau's link.
1236 * @param $alias alias name
1237 * @param $destination reference of the destination
1238 * @param $password password to protect alias
1239 * @param $ip client's IP
1240 * @return a string containing the edit code of the alias or the string "Error"
1242 function jirafeau_alias_create($alias, $destination, $password, $ip)
1244 /* Check that alias and password are long enough. */
1245 if (strlen($alias) < 8 ||
1246 strlen($alias) > 32 ||
1247 strlen($password) < 8 ||
1248 strlen($password) > 32) {
1252 /* Check that destination exists. */
1253 $l = jirafeau_get_link($destination);
1258 /* Check that alias does not already exists. */
1259 $alias = md5($alias);
1260 $p = VAR_ALIAS
. s2p($alias);
1261 if (file_exists($p)) {
1265 /* Create alias folder. */
1266 @mkdir
($p, 0755, true);
1267 if (!file_exists($p)) {
1271 /* Generate password. */
1272 $md5_password = md5($password);
1274 /* Store informations. */
1276 $handle = fopen($p, 'w');
1278 $md5_password . NL
.
1287 /** Update an alias.
1288 * @param $alias alias to update
1289 * @param $destination reference of the new destination
1290 * @param $password password to protect alias
1291 * @param $new_password optional new password to protect alias
1292 * @param $ip client's IP
1293 * @return "Ok" or "Error" string
1295 function jirafeau_alias_update($alias, $destination, $password,
1298 $alias = md5($alias);
1299 /* Check that alias exits. */
1300 $a = jirafeau_get_alias($alias);
1305 /* Check that destination exists. */
1306 $l = jirafeau_get_link($a["destination"]);
1311 /* Check password. */
1312 if ($a["md5_password"] != md5($password)) {
1316 $p = $a['md5_password'];
1317 if (strlen($new_password) >= 8 &&
1318 strlen($new_password) <= 32) {
1319 $p = md5($new_password);
1320 } elseif (strlen($new_password) > 0) {
1324 /* Rewrite informations. */
1325 $p = VAR_ALIAS
. s2p($alias) . $alias;
1326 $handle = fopen($p, 'w');
1337 * @param $alias alias to get
1338 * @return alias destination or "Error" string
1340 function jirafeau_alias_get($alias)
1342 $alias = md5($alias);
1343 /* Check that alias exits. */
1344 $a = jirafeau_get_alias($alias);
1349 return $a['destination'];
1352 function jirafeau_clean_rm_alias($alias)
1355 if (file_exists(VAR_ALIAS
. $p . $alias)) {
1356 unlink(VAR_ALIAS
. $p . $alias);
1358 $parse = VAR_ALIAS
. $p;
1360 while (file_exists($parse)
1361 && ($scan = scandir($parse))
1362 && count($scan) == 2 // '.' and '..' folders => empty.
1363 && basename($parse) != basename(VAR_ALIAS
)) {
1365 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
1369 /** Delete an alias.
1370 * @param $alias alias to delete
1371 * @param $password password to protect alias
1372 * @return "Ok" or "Error" string
1374 function jirafeau_alias_delete($alias, $password)
1376 $alias = md5($alias);
1377 /* Check that alias exits. */
1378 $a = jirafeau_get_alias($alias);
1383 /* Check password. */
1384 if ($a["md5_password"] != md5($password)) {
1388 jirafeau_clean_rm_alias($alias);
1393 * Replace markers in templates.
1395 * Available markers have the scheme "###MARKERNAME###".
1397 * @param $content string Template text with markers
1398 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1399 * @return Template with replaced markers
1401 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1404 '/###ORGANISATION###/',
1405 '/###CONTACTPERSON###/',
1408 $replacements = array(
1409 $GLOBALS['cfg']['organisation'],
1410 $GLOBALS['cfg']['contactperson'],
1411 $GLOBALS['cfg']['web_root']
1413 $content = preg_replace($patterns, $replacements, $content);
1415 if (true === $htmllinebreaks) {
1416 $content = nl2br($content);
patrick-canterino.de