]>
git.p6c8.net - jirafeau_mojo42.git/blob - lib/functions.php
c234f4cdedf8f62050895f46e73e34c75f86588a
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 '/'
30 for ($i = 0; $i < strlen($s); $i++
) {
32 if (($i +
1) %
$block_size == 0) {
36 if (strlen($s) %
$block_size != 0) {
43 * Convert base 16 to base 64
44 * @returns A string based on 64 characters (0-9, a-z, A-Z, "-" and "_")
46 function base_16_to_64($num)
48 $m = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_';
49 $hex2bin = array('0000', # 0
68 # Convert long hex string to bin.
70 for ($i = 0; $i < $size; $i++
) {
71 $b .= $hex2bin{hexdec($num{$i})};
73 # Convert long bin to base 64.
75 for ($i = $size - 6; $i >= 0; $i -= 6) {
76 $o = $m{bindec(substr($b, $i, 6))} . $o;
78 # Some few bits remaining ?
79 if ($i < 0 && $i > -6) {
80 $o = $m{bindec(substr($b, 0, $i +
6))} . $o;
86 * Generate a random code.
87 * @param $l code length
88 * @return random code.
90 function jirafeau_gen_random($l)
97 for ($i = 0; $i < $l; $i++
) {
98 $code .= dechex(rand(0, 15));
106 if (isset($_SERVER['HTTPS'])) {
107 if ('on' == strtolower($_SERVER['HTTPS']) ||
108 '1' == $_SERVER['HTTPS']) {
111 } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
113 } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
114 if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
121 function jirafeau_human_size($octets)
123 $u = array('B', 'KB', 'MB', 'GB', 'TB');
124 $o = max($octets, 0);
125 $p = min(floor(($o ?
log($o) : 0) / log(1024)), count($u) - 1);
127 return round($o, 1) . $u[$p];
130 // Convert UTC timestamp to a datetime field
131 function jirafeau_get_datetimefield($timestamp)
133 $content = '<span class="datetime" data-datetime="' . strftime('%Y-%m-%d %H:%M', $timestamp) . '">'
134 . strftime('%Y-%m-%d %H:%M', $timestamp) . ' (GMT)</span>';
138 function jirafeau_fatal_error($errorText, $cfg = array())
140 echo '<div class="error"><h2>Error</h2><p>' . $errorText . '</p></div>';
141 require(JIRAFEAU_ROOT
. 'lib/template/footer.php');
145 function jirafeau_clean_rm_link($link)
148 if (file_exists(VAR_LINKS
. $p . $link)) {
149 unlink(VAR_LINKS
. $p . $link);
151 $parse = VAR_LINKS
. $p;
153 while (file_exists($parse)
154 && ($scan = scandir($parse))
155 && count($scan) == 2 // '.' and '..' folders => empty.
156 && basename($parse) != basename(VAR_LINKS
)) {
158 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
162 function jirafeau_clean_rm_file($md5)
165 $f = VAR_FILES
. $p . $md5;
166 if (file_exists($f) && is_file($f)) {
169 if (file_exists($f . '_count') && is_file($f . '_count')) {
170 unlink($f . '_count');
172 $parse = VAR_FILES
. $p;
174 while (file_exists($parse)
175 && ($scan = scandir($parse))
176 && count($scan) == 2 // '.' and '..' folders => empty.
177 && basename($parse) != basename(VAR_FILES
)) {
179 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
184 * transforms a php.ini string representing a value in an integer
185 * @param $value the value from php.ini
186 * @returns an integer for this value
188 function jirafeau_ini_to_bytes($value)
190 $modifier = substr($value, -1);
191 $bytes = substr($value, 0, -1);
192 switch (strtoupper($modifier)) {
208 * gets the maximum upload size according to php.ini
209 * @returns the maximum upload size in bytes
211 function jirafeau_get_max_upload_size_bytes()
213 return min(jirafeau_ini_to_bytes(ini_get('post_max_size')),
214 jirafeau_ini_to_bytes(ini_get('upload_max_filesize')));
218 * gets the maximum upload size according to php.ini
219 * @returns the maximum upload size string
221 function jirafeau_get_max_upload_size()
223 return jirafeau_human_size(jirafeau_get_max_upload_size_bytes());
227 * gets a string explaining the error
228 * @param $code the error code
229 * @returns a string explaining the error
231 function jirafeau_upload_errstr($code)
234 case UPLOAD_ERR_INI_SIZE
:
235 case UPLOAD_ERR_FORM_SIZE
:
236 return t('Your file exceeds the maximum authorized file size. ');
238 case UPLOAD_ERR_PARTIAL
:
239 case UPLOAD_ERR_NO_FILE
:
241 t('Your file was not uploaded correctly. You may succeed in retrying. ');
243 case UPLOAD_ERR_NO_TMP_DIR
:
244 case UPLOAD_ERR_CANT_WRITE
:
245 case UPLOAD_ERR_EXTENSION
:
246 return t('Internal error. You may not succeed in retrying. ');
248 return t('Unknown error. ');
251 /** Remove link and it's file
252 * @param $link the link's name (hash)
255 function jirafeau_delete_link($link)
257 $l = jirafeau_get_link($link);
262 jirafeau_clean_rm_link($link);
268 if (file_exists(VAR_FILES
. $p . $md5. '_count')) {
269 $content = file(VAR_FILES
. $p . $md5. '_count');
270 $counter = trim($content[0]);
275 $handle = fopen(VAR_FILES
. $p . $md5. '_count', 'w');
276 fwrite($handle, $counter);
281 jirafeau_clean_rm_file($md5);
286 * Delete a file and it's links.
288 function jirafeau_delete_file($md5)
291 /* Get all links files. */
292 $stack = array(VAR_LINKS
);
293 while (($d = array_shift($stack)) && $d != null) {
296 foreach ($dir as $node) {
297 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
298 preg_match('/\.tmp/i', "$node")) {
302 if (is_dir($d . $node)) {
303 /* Push new found directory. */
304 $stack[] = $d . $node . '/';
305 } elseif (is_file($d . $node)) {
306 /* Read link informations. */
307 $l = jirafeau_get_link(basename($node));
311 if ($l['md5'] == $md5) {
313 jirafeau_delete_link($node);
318 jirafeau_clean_rm_file($md5);
323 * handles an uploaded file
324 * @param $file the file struct given by $_FILE[]
325 * @param $one_time_download is the file a one time download ?
326 * @param $key if not empty, protect the file with this key
327 * @param $time the time of validity of the file
328 * @param $ip uploader's ip
329 * @param $crypt boolean asking to crypt or not
330 * @param $link_name_length size of the link name
331 * @returns an array containing some information
332 * 'error' => information on possible errors
333 * 'link' => the link name of the uploaded file
334 * 'delete_link' => the link code to delete file
336 function jirafeau_upload($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length)
338 if (empty($file['tmp_name']) ||
!is_uploaded_file($file['tmp_name'])) {
341 array('has_error' => true,
342 'why' => jirafeau_upload_errstr($file['error'])),
344 'delete_link' => ''));
347 /* array representing no error */
348 $noerr = array('has_error' => false, 'why' => '');
350 /* Crypt file if option is enabled. */
353 if ($crypt == true && !(extension_loaded('mcrypt') == true)) {
354 error_log("PHP extension mcrypt not loaded, won't encrypt in Jirafeau");
356 if ($crypt == true && extension_loaded('mcrypt') == true) {
357 $crypt_key = jirafeau_encrypt_file($file['tmp_name'], $file['tmp_name']);
358 if (strlen($crypt_key) > 0) {
363 /* file informations */
364 $md5 = md5_file($file['tmp_name']);
365 $name = str_replace(NL
, '', trim($file['name']));
366 $mime_type = $file['type'];
367 $size = $file['size'];
369 /* does file already exist ? */
372 if (file_exists(VAR_FILES
. $p . $md5)) {
373 $rc = unlink($file['tmp_name']);
374 } elseif ((file_exists(VAR_FILES
. $p) || @mkdir
(VAR_FILES
. $p, 0755, true))
375 && move_uploaded_file($file['tmp_name'], VAR_FILES
. $p . $md5)) {
381 array('has_error' => true,
382 'why' => t('INTERNAL_ERROR_DEL')),
384 'delete_link' => ''));
387 /* Increment or create count file. */
389 if (file_exists(VAR_FILES
. $p . $md5 . '_count')) {
390 $content = file(VAR_FILES
. $p . $md5. '_count');
391 $counter = trim($content[0]);
394 $handle = fopen(VAR_FILES
. $p . $md5. '_count', 'w');
395 fwrite($handle, $counter);
398 /* Create delete code. */
399 $delete_link_code = jirafeau_gen_random(5);
401 /* md5 password or empty. */
404 $password = md5($key);
407 /* create link file */
408 $link_tmp_name = VAR_LINKS
. $md5 . rand(0, 10000) . '.tmp';
409 $handle = fopen($link_tmp_name, 'w');
411 $name . NL
. $mime_type . NL
. $size . NL
. $password . NL
. $time .
412 NL
. $md5. NL
. ($one_time_download ?
'O' : 'R') . NL
. time() .
413 NL
. $ip . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
415 $md5_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
416 $l = s2p("$md5_link");
417 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
418 !rename($link_tmp_name, VAR_LINKS
. $l . $md5_link)) {
419 if (file_exists($link_tmp_name)) {
420 unlink($link_tmp_name);
425 $handle = fopen(VAR_FILES
. $p . $md5. '_count', 'w');
426 fwrite($handle, $counter);
429 jirafeau_clean_rm_file($md5_link);
433 array('has_error' => true,
434 'why' => t('Internal error during file creation. ')),
436 'delete_link' => '');
438 return array( 'error' => $noerr,
440 'delete_link' => $delete_link_code,
441 'crypt_key' => $crypt_key);
445 * Tells if a mime-type is viewable in a browser
446 * @param $mime the mime type
447 * @returns a boolean telling if a mime type is viewable
449 function jirafeau_is_viewable($mime)
452 /* Actually, verify if mime-type is an image or a text. */
453 $viewable = array('image', 'text', 'video', 'audio');
454 $decomposed = explode('/', $mime);
455 return in_array($decomposed[0], $viewable);
460 // Error handling functions.
461 //! Global array that contains all registered errors.
462 $error_list = array();
465 * Adds an error to the list of errors.
466 * @param $title the error's title
467 * @param $description is a human-friendly description of the problem.
469 function add_error($title, $description)
472 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
476 * Informs whether any error has been registered yet.
477 * @return true if there are errors.
482 return !empty($error_list);
486 * Displays all the errors.
488 function show_errors()
492 echo '<div class="error">';
493 foreach ($error_list as $error) {
500 function check_errors($cfg)
502 if (file_exists(JIRAFEAU_ROOT
. 'install.php')
503 && !($cfg['installation_done'] === true)) {
504 header('Location: install.php');
508 /* Checking for errors. */
509 if (!is_writable(VAR_FILES
)) {
510 add_error(t('FILE_DIR_W'), VAR_FILES
);
513 if (!is_writable(VAR_LINKS
)) {
514 add_error(t('LINK_DIR_W'), VAR_LINKS
);
517 if (!is_writable(VAR_ASYNC
)) {
518 add_error(t('ASYNC_DIR_W'), VAR_ASYNC
);
523 * Read link informations
524 * @return array containing informations.
526 function jirafeau_get_link($hash)
529 $link = VAR_LINKS
. s2p("$hash") . $hash;
531 if (!file_exists($link)) {
536 $out['file_name'] = trim($c[0]);
537 $out['mime_type'] = trim($c[1]);
538 $out['file_size'] = trim($c[2]);
539 $out['key'] = trim($c[3], NL
);
540 $out['time'] = trim($c[4]);
541 $out['md5'] = trim($c[5]);
542 $out['onetime'] = trim($c[6]);
543 $out['upload_date'] = trim($c[7]);
544 $out['ip'] = trim($c[8]);
545 $out['link_code'] = trim($c[9]);
546 $out['crypted'] = trim($c[10]) == 'C';
552 * List files in admin interface.
554 function jirafeau_admin_list($name, $file_hash, $link_hash)
556 echo '<fieldset><legend>';
558 echo t('FILENAME') . ": " . jirafeau_escape($name);
560 if (!empty($file_hash)) {
561 echo t('FILE') . ": " . jirafeau_escape($file_hash);
563 if (!empty($link_hash)) {
564 echo t('LINK') . ": " . jirafeau_escape($link_hash);
566 if (empty($name) && empty($file_hash) && empty($link_hash)) {
570 echo '<table border="1" width="1100">';
572 echo '<th>' . t('FILENAME') . '</th>';
573 echo '<th>' . t('TYPE') . '</th>';
574 echo '<th>' . t('SIZE') . '</th>';
575 echo '<th>' . t('EXPIRE') . '</th>';
576 echo '<th>' . t('ONETIME') . '</th>';
577 echo '<th>' . t('UPLOAD_DATE') . '</th>';
578 echo '<th>' . t('ORIGIN') . '</th>';
579 echo '<th>' . t('ACTION') . '</th>';
582 /* Get all links files. */
583 $stack = array(VAR_LINKS
);
584 while (($d = array_shift($stack)) && $d != null) {
586 foreach ($dir as $node) {
587 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
588 preg_match('/\.tmp/i', "$node")) {
591 if (is_dir($d . $node)) {
592 /* Push new found directory. */
593 $stack[] = $d . $node . '/';
594 } elseif (is_file($d . $node)) {
595 /* Read link informations. */
596 $l = jirafeau_get_link($node);
602 if (!empty($name) && !@preg_match
("/$name/i", jirafeau_escape($l['file_name']))) {
605 if (!empty($file_hash) && $file_hash != $l['md5']) {
608 if (!empty($link_hash) && $link_hash != $node) {
611 /* Print link informations. */
614 '<strong><a id="upload_link" href="f.php?h='. jirafeau_escape($node) .'" title="' .
615 t('DL_PAGE') . '">' . jirafeau_escape($l['file_name']) . '</a></strong>';
617 echo '<td>' . jirafeau_escape($l['mime_type']) . '</td>';
618 echo '<td>' . jirafeau_human_size($l['file_size']) . '</td>';
619 echo '<td>' . ($l['time'] == -1 ?
'∞' : jirafeau_get_datetimefield($l['time'])) . '</td>';
621 if ($l['onetime'] == 'O') {
627 echo '<td>' . jirafeau_get_datetimefield($l['upload_date']) . '</td>';
628 echo '<td>' . $l['ip'] . '</td>';
630 '<form method="post">' .
631 '<input type = "hidden" name = "action" value = "download"/>' .
632 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
633 jirafeau_admin_csrf_field() .
634 '<input type = "submit" value = "' . t('DL') . '" />' .
636 '<form method="post">' .
637 '<input type = "hidden" name = "action" value = "delete_link"/>' .
638 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
639 jirafeau_admin_csrf_field() .
640 '<input type = "submit" value = "' . t('DEL_LINK') . '" />' .
642 '<form method="post">' .
643 '<input type = "hidden" name = "action" value = "delete_file"/>' .
644 '<input type = "hidden" name = "md5" value = "' . $l['md5'] . '"/>' .
645 jirafeau_admin_csrf_field() .
646 '<input type = "submit" value = "' . t('DEL_FILE_LINKS') . '" />' .
653 echo '</table></fieldset>';
657 * Clean expired files.
658 * @return number of cleaned files.
660 function jirafeau_admin_clean()
663 /* Get all links files. */
664 $stack = array(VAR_LINKS
);
665 while (($d = array_shift($stack)) && $d != null) {
668 foreach ($dir as $node) {
669 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
670 preg_match('/\.tmp/i', "$node")) {
674 if (is_dir($d . $node)) {
675 /* Push new found directory. */
676 $stack[] = $d . $node . '/';
677 } elseif (is_file($d . $node)) {
678 /* Read link informations. */
679 $l = jirafeau_get_link(basename($node));
684 if ($l['time'] > 0 && $l['time'] < time() ||
// expired
685 !file_exists(VAR_FILES
. $p . $l['md5']) ||
// invalid
686 !file_exists(VAR_FILES
. $p . $l['md5'] . '_count')) { // invalid
687 jirafeau_delete_link($node);
698 * Clean old async transferts.
699 * @return number of cleaned files.
701 function jirafeau_admin_clean_async()
704 /* Get all links files. */
705 $stack = array(VAR_ASYNC
);
706 while (($d = array_shift($stack)) && $d != null) {
709 foreach ($dir as $node) {
710 if (strcmp($node, '.') == 0 ||
strcmp($node, '..') == 0 ||
711 preg_match('/\.tmp/i', "$node")) {
715 if (is_dir($d . $node)) {
716 /* Push new found directory. */
717 $stack[] = $d . $node . '/';
718 } elseif (is_file($d . $node)) {
719 /* Read async informations. */
720 $a = jirafeau_get_async_ref(basename($node));
724 /* Delete transferts older than 1 hour. */
725 if (time() - $a['last_edited'] > 3600) {
726 jirafeau_async_delete(basename($node));
735 * Read async transfert informations
736 * @return array containing informations.
738 function jirafeau_get_async_ref($ref)
741 $refinfos = VAR_ASYNC
. s2p("$ref") . "$ref";
743 if (!file_exists($refinfos)) {
747 $c = file($refinfos);
748 $out['file_name'] = trim($c[0]);
749 $out['mime_type'] = trim($c[1]);
750 $out['key'] = trim($c[2], NL
);
751 $out['time'] = trim($c[3]);
752 $out['onetime'] = trim($c[4]);
753 $out['ip'] = trim($c[5]);
754 $out['last_edited'] = trim($c[6]);
755 $out['next_code'] = trim($c[7]);
760 * Delete async transfert informations
762 function jirafeau_async_delete($ref)
765 if (file_exists(VAR_ASYNC
. $p . $ref)) {
766 unlink(VAR_ASYNC
. $p . $ref);
768 if (file_exists(VAR_ASYNC
. $p . $ref . '_data')) {
769 unlink(VAR_ASYNC
. $p . $ref . '_data');
771 $parse = VAR_ASYNC
. $p;
773 while (file_exists($parse)
774 && ($scan = scandir($parse))
775 && count($scan) == 2 // '.' and '..' folders => empty.
776 && basename($parse) != basename(VAR_ASYNC
)) {
778 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
783 * Init a new asynchronous upload.
784 * @param $finename Name of the file to send
785 * @param $one_time One time upload parameter
786 * @param $key eventual password (or blank)
787 * @param $time time limit
788 * @param $ip ip address of the client
789 * @return a string containing a temporary reference followed by a code or the string 'Error'
791 function jirafeau_async_init($filename, $type, $one_time, $key, $time, $ip)
795 /* Create temporary folder. */
798 $code = jirafeau_gen_random(4);
800 $ref = jirafeau_gen_random(32);
801 $p = VAR_ASYNC
. s2p($ref);
802 } while (file_exists($p));
803 @mkdir
($p, 0755, true);
804 if (!file_exists($p)) {
809 /* md5 password or empty */
812 $password = md5($key);
815 /* Store informations. */
817 $handle = fopen($p, 'w');
819 str_replace(NL
, '', trim($filename)) . NL
.
820 str_replace(NL
, '', trim($type)) . NL
. $password . NL
.
821 $time . NL
. ($one_time ?
'O' : 'R') . NL
. $ip . NL
.
822 time() . NL
. $code . NL
);
825 return $ref . NL
. $code ;
829 * Append a piece of file on the asynchronous upload.
830 * @param $ref asynchronous upload reference
831 * @param $file piece of data
832 * @param $code client code for this operation
833 * @param $max_file_size maximum allowed file size
834 * @return a string containing a next code to use or the string "Error"
836 function jirafeau_async_push($ref, $data, $code, $max_file_size)
838 /* Get async infos. */
839 $a = jirafeau_get_async_ref($ref);
841 /* Check some errors. */
843 ||
$a['next_code'] != "$code"
844 ||
empty($data['tmp_name'])
845 ||
!is_uploaded_file($data['tmp_name'])) {
852 $r_path = $data['tmp_name'];
853 $w_path = VAR_ASYNC
. $p . $ref . '_data';
855 /* Check that file size is not above upload limit. */
856 if ($max_file_size > 0 &&
857 filesize($r_path) +
filesize($w_path) > $max_file_size * 1024 * 1024) {
858 jirafeau_async_delete($ref);
862 /* Concatenate data. */
863 $r = fopen($r_path, 'r');
864 $w = fopen($w_path, 'a');
866 if (fwrite($w, fread($r, 1024)) === false) {
869 jirafeau_async_delete($ref);
877 /* Update async file. */
878 $code = jirafeau_gen_random(4);
879 $handle = fopen(VAR_ASYNC
. $p . $ref, 'w');
881 $a['file_name'] . NL
. $a['mime_type'] . NL
. $a['key'] . NL
.
882 $a['time'] . NL
. $a['onetime'] . NL
. $a['ip'] . NL
.
883 time() . NL
. $code . NL
);
889 * Finalyze an asynchronous upload.
890 * @param $ref asynchronous upload reference
891 * @param $code client code for this operation
892 * @param $crypt boolean asking to crypt or not
893 * @param $link_name_length link name length
894 * @return a string containing the download reference followed by a delete code or the string 'Error'
896 function jirafeau_async_end($ref, $code, $crypt, $link_name_length)
898 /* Get async infos. */
899 $a = jirafeau_get_async_ref($ref);
901 ||
$a['next_code'] != "$code") {
905 /* Generate link infos. */
906 $p = VAR_ASYNC
. s2p($ref) . $ref . "_data";
907 if (!file_exists($p)) {
913 if ($crypt == true && extension_loaded('mcrypt') == true) {
914 $crypt_key = jirafeau_encrypt_file($p, $p);
915 if (strlen($crypt_key) > 0) {
921 $size = filesize($p);
923 $delete_link_code = jirafeau_gen_random(5);
925 /* File already exist ? */
926 if (!file_exists(VAR_FILES
. $np)) {
927 @mkdir
(VAR_FILES
. $np, 0755, true);
929 if (!file_exists(VAR_FILES
. $np . $md5)) {
930 rename($p, VAR_FILES
. $np . $md5);
933 /* Increment or create count file. */
935 if (file_exists(VAR_FILES
. $np . $md5 . '_count')) {
936 $content = file(VAR_FILES
. $np . $md5. '_count');
937 $counter = trim($content[0]);
940 $handle = fopen(VAR_FILES
. $np . $md5. '_count', 'w');
941 fwrite($handle, $counter);
945 $link_tmp_name = VAR_LINKS
. $md5 . rand(0, 10000) . '.tmp';
946 $handle = fopen($link_tmp_name, 'w');
948 $a['file_name'] . NL
. $a['mime_type'] . NL
. $size . NL
.
949 $a['key'] . NL
. $a['time'] . NL
. $md5 . NL
. $a['onetime'] . NL
.
950 time() . NL
. $a['ip'] . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
952 $md5_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
953 $l = s2p("$md5_link");
954 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
955 !rename($link_tmp_name, VAR_LINKS
. $l . $md5_link)) {
959 /* Clean async upload. */
960 jirafeau_async_delete($ref);
961 return $md5_link . NL
. $delete_link_code . NL
. urlencode($crypt_key);
964 function jirafeau_crypt_create_iv($base, $size)
967 while (strlen($iv) < $size) {
970 $iv = substr($iv, 0, $size);
975 * Crypt file and returns decrypt key.
976 * @param $fp_src file path to the file to crypt.
977 * @param $fp_dst file path to the file to write crypted file (could be the same).
978 * @return decrypt key composed of the key and the iv separated by a point ('.')
980 function jirafeau_encrypt_file($fp_src, $fp_dst)
982 $fs = filesize($fp_src);
983 if ($fs === false ||
$fs == 0 ||
!(extension_loaded('mcrypt') == true)) {
987 /* Prepare module. */
988 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
990 $crypt_key = jirafeau_gen_random(10);
991 $md5_key = md5($crypt_key);
992 $iv = jirafeau_crypt_create_iv($md5_key, mcrypt_enc_get_iv_size($m));
994 mcrypt_generic_init($m, $md5_key, $iv);
996 $r = fopen($fp_src, 'r');
997 $w = fopen($fp_dst, 'c');
999 $enc = mcrypt_generic($m, fread($r, 1024));
1000 if (fwrite($w, $enc) === false) {
1007 mcrypt_generic_deinit($m);
1008 mcrypt_module_close($m);
1014 * @param $fp_src file path to the file to decrypt.
1015 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1016 * @param $k string composed of the key and the iv separated by a point ('.')
1017 * @return key used to decrypt. a string of length 0 is returned if failed.
1019 function jirafeau_decrypt_file($fp_src, $fp_dst, $k)
1021 $fs = filesize($fp_src);
1022 if ($fs === false ||
$fs == 0 ||
extension_loaded('mcrypt') == false) {
1027 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1028 /* Extract key and iv. */
1030 $md5_key = md5($crypt_key);
1031 $iv = jirafeau_crypt_create_iv($md5_key, mcrypt_enc_get_iv_size($m));
1033 $r = fopen($fp_src, 'r');
1034 $w = fopen($fp_dst, 'c');
1036 $dec = mdecrypt_generic($m, fread($r, 1024));
1037 if (fwrite($w, $dec) === false) {
1044 mcrypt_generic_deinit($m);
1045 mcrypt_module_close($m);
1050 * Check if Jirafeau is password protected for visitors.
1051 * @return true if Jirafeau is password protected, false otherwise.
1053 function jirafeau_has_upload_password($cfg)
1055 return count($cfg['upload_password']) > 0;
1059 * Challenge password for a visitor.
1060 * @param $password password to be challenged
1061 * @return true if password is valid, false otherwise.
1063 function jirafeau_challenge_upload_password($cfg, $password)
1065 if (!jirafeau_has_upload_password($cfg)) {
1068 foreach ($cfg['upload_password'] as $p) {
1069 if ($password == $p) {
1077 * Test if visitor's IP is authorized to upload.
1079 * @param $allowedIpList array of allowed IPs
1080 * @param $challengedIp IP to be challenged
1081 * @return true if IP is authorized, false otherwise.
1083 function jirafeau_challenge_upload_ip($allowedIpList, $challengedIp)
1085 // skip if list is empty = all IPs allowed
1086 if (count($allowedIpList) == 0) {
1089 // test given IP against each allowed IP
1090 foreach ($allowedIpList as $i) {
1091 if ($i == $challengedIp) {
1094 // CIDR test for IPv4 only.
1095 if (strpos($i, '/') !== false) {
1096 list($subnet, $mask) = explode('/', $i);
1097 if ((ip2long($challengedIp) & ~
((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
1106 * Test if visitor's IP is authorized or password is supplied and authorized
1107 * @param $ip IP to be challenged
1108 * @param $password password to be challenged
1109 * @return true if access is valid, false otherwise.
1111 function jirafeau_challenge_upload ($cfg, $ip, $password)
1113 // Allow if no ip restrictaion and no password restriction
1114 if ((count ($cfg['upload_ip']) == 0) and (count ($cfg['upload_password']) == 0)) {
1118 // Allow if ip is in array (no password)
1119 foreach ($cfg['upload_ip_nopassword'] as $i) {
1123 // CIDR test for IPv4 only.
1124 if (strpos ($i, '/') !== false)
1126 list ($subnet, $mask) = explode('/', $i);
1127 if ((ip2long ($ip) & ~
((1 << (32 - $mask)) - 1) ) == ip2long ($subnet)) {
1133 // Allow if ip is in array
1134 foreach ($cfg['upload_ip'] as $i) {
1138 // CIDR test for IPv4 only.
1139 if (strpos ($i, '/') !== false)
1141 list ($subnet, $mask) = explode('/', $i);
1142 if ((ip2long ($ip) & ~
((1 << (32 - $mask)) - 1) ) == ip2long ($subnet)) {
1147 if (!jirafeau_has_upload_password($cfg)) {
1151 foreach ($cfg['upload_password'] as $p) {
1152 if ($password == $p) {
1159 /** Tell if we have some HTTP headers generated by a proxy */
1160 function has_http_forwarded()
1163 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1164 !empty($_SERVER['http_X_forwarded_for']);
1168 * Generate IP list from HTTP headers generated by a proxy
1169 * @return array of IP strings
1171 function get_ip_list_http_forwarded()
1174 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1175 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1179 foreach ($l as $ip) {
1180 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1183 if (!empty($_SERVER['http_X_forwarded_for'])) {
1184 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1185 foreach ($l as $ip) {
1186 // Separate IP from port
1187 $ipa = explode(':', $ip);
1188 if ($ipa === false) {
1192 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1199 * Get the ip address of the client from REMOTE_ADDR
1200 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1201 * @returns the client ip address
1203 function get_ip_address($cfg)
1205 $remote = $_SERVER['REMOTE_ADDR'];
1206 if (count($cfg['proxy_ip']) == 0 ||
!has_http_forwarded()) {
1210 $ip_list = get_ip_list_http_forwarded();
1211 if (count($ip_list) == 0) {
1215 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1216 if ($remote != $proxy_ip) {
1219 // Take the last IP (the one which has been set by the defined proxy).
1220 return end($ip_list);
1226 * Convert hexadecimal string to base64
1228 function hex_to_base64($hex)
1231 foreach (str_split($hex, 2) as $pair) {
1232 $b .= chr(hexdec($pair));
1234 return base64_encode($b);
1238 * Replace markers in templates.
1240 * Available markers have the scheme "###MARKERNAME###".
1242 * @param $content string Template text with markers
1243 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1244 * @return Template with replaced markers
1246 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1249 '/###ORGANISATION###/',
1250 '/###CONTACTPERSON###/',
1253 $replacements = array(
1254 $GLOBALS['cfg']['organisation'],
1255 $GLOBALS['cfg']['contactperson'],
1256 $GLOBALS['cfg']['web_root']
1258 $content = preg_replace($patterns, $replacements, $content);
1260 if (true === $htmllinebreaks) {
1261 $content = nl2br($content);
1267 function jirafeau_escape($string)
1269 return htmlspecialchars($string, ENT_QUOTES
);
1272 function jirafeau_admin_session_start()
1274 $_SESSION['admin_auth'] = true;
1275 $_SESSION['admin_csrf'] = md5(uniqid(mt_rand(), true));
1278 function jirafeau_admin_session_end()
1280 $_SESSION = array();
1284 function jirafeau_admin_session_logged()
1286 return isset($_SESSION['admin_auth']) &&
1287 isset($_SESSION['admin_csrf']) &&
1288 isset($_POST['admin_csrf']) &&
1289 $_SESSION['admin_auth'] === true &&
1290 $_SESSION['admin_csrf'] === $_POST['admin_csrf'];
1293 function jirafeau_admin_csrf_field()
1295 return "<input type='hidden' name='admin_csrf' value='". $_SESSION['admin_csrf'] . "'/>";
patrick-canterino.de