]> git.p6c8.net - jirafeau.git/blob - lib/functions.php
4736b7f35b2d1b3d9454f631f26e28b824cfadeb
[jirafeau.git] / lib / functions.php
1 <?php
2 /*
3 * Jirafeau, your web file repository
4 * Copyright (C) 2008 Julien "axolotl" BERNARD <axolotl@magieeternelle.org>
5 * Copyright (C) 2015 Jerome Jutteau <jerome@jutteau.fr>
6 * Copyright (C) 2015 Nicola Spanti (RyDroid) <dev@nicola-spanti.info>
7 *
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.
12 *
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.
17 *
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/>.
20 */
21
22 /**
23 * Transform a string in a path by separating each letters by a '/'.
24 * @return path finishing with a '/'
25 */
26 function s2p($s)
27 {
28 $block_size = 8;
29 $p = '';
30 for ($i = 0; $i < strlen($s); $i++) {
31 $p .= $s[$i];
32 if (($i + 1) % $block_size == 0) {
33 $p .= '/';
34 }
35 }
36 if (strlen($s) % $block_size != 0) {
37 $p .= '/';
38 }
39 return $p;
40 }
41
42 /**
43 * Convert base 16 to base 64
44 * @returns A string based on 64 characters (0-9, a-z, A-Z, "-" and "_")
45 */
46 function base_16_to_64($num)
47 {
48 $m = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_';
49 $hex2bin = array('0000', # 0
50 '0001', # 1
51 '0010', # 2
52 '0011', # 3
53 '0100', # 4
54 '0101', # 5
55 '0110', # 6
56 '0111', # 7
57 '1000', # 8
58 '1001', # 9
59 '1010', # a
60 '1011', # b
61 '1100', # c
62 '1101', # d
63 '1110', # e
64 '1111'); # f
65 $o = '';
66 $b = '';
67 $i = 0;
68 # Convert long hex string to bin.
69 $size = strlen($num);
70 for ($i = 0; $i < $size; $i++) {
71 $b .= $hex2bin[hexdec($num[$i])];
72 }
73 # Convert long bin to base 64.
74 $size *= 4;
75 for ($i = $size - 6; $i >= 0; $i -= 6) {
76 $o = $m[bindec(substr($b, $i, 6))] . $o;
77 }
78 # Some few bits remaining ?
79 if ($i < 0 && $i > -6) {
80 $o = $m[bindec(substr($b, 0, $i + 6))] . $o;
81 }
82 return $o;
83 }
84
85 /**
86 * Generate a random code.
87 * @param $l code length
88 * @return random code.
89 */
90 function jirafeau_gen_random($l)
91 {
92 if ($l <= 0) {
93 return 42;
94 }
95
96 $code="";
97 for ($i = 0; $i < $l; $i++) {
98 $code .= dechex(rand(0, 15));
99 }
100
101 return $code;
102 }
103
104 function jirafeau_gen_download_pass($length, $allowed_chars)
105 {
106 if ($length <= 0) {
107 return false;
108 }
109 $pass="";
110 for ($i = 0; $i < $length; $i++) {
111 $pass .= $allowed_chars[rand(0, strlen($allowed_chars) - 1)];
112 }
113
114 return $pass;
115 }
116
117 function is_ssl()
118 {
119 if (isset($_SERVER['HTTPS'])) {
120 if ('on' == strtolower($_SERVER['HTTPS']) ||
121 '1' == $_SERVER['HTTPS']) {
122 return true;
123 }
124 } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
125 return true;
126 } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
127 if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
128 return true;
129 }
130 }
131 return false;
132 }
133
134 function jirafeau_human_size($octets)
135 {
136 $u = array('B', 'KB', 'MB', 'GB', 'TB');
137 $o = max($octets, 0);
138 $p = min(floor(($o ? log($o) : 0) / log(1024)), count($u) - 1);
139 $o /= pow(1024, $p);
140 return round($o, 1) . $u[$p];
141 }
142
143 // Convert UTC timestamp to a datetime field
144 function jirafeau_get_datetimefield($timestamp)
145 {
146 $ts = date_create("@" . $timestamp);
147 $content = '<span class="datetime" data-datetime="' . date_format($ts, 'Y-m-d H:i') . '">'
148 . date_format($ts, 'Y-m-d H:i') . ' (GMT)</span>';
149
150 return $content;
151 }
152
153 function jirafeau_fatal_error($errorText, $cfg = array())
154 {
155 echo '<div class="error"><h2>Error</h2><p>' . $errorText . '</p></div>';
156 require(JIRAFEAU_ROOT . 'lib/template/footer.php');
157 exit;
158 }
159
160 function jirafeau_clean_rm_link($link)
161 {
162 $p = s2p("$link");
163 if (file_exists(VAR_LINKS . $p . $link)) {
164 unlink(VAR_LINKS . $p . $link);
165 }
166 if (file_exists(VAR_LINKS . $p . $link . '_download')) {
167 unlink(VAR_LINKS . $p . $link . '_download');
168 }
169 $parse = VAR_LINKS . $p;
170 $scan = array();
171 while (file_exists($parse)
172 && ($scan = scandir($parse))
173 && count($scan) == 2 // '.' and '..' folders => empty.
174 && basename($parse) != basename(VAR_LINKS)) {
175 rmdir($parse);
176 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
177 }
178 }
179
180 function jirafeau_clean_rm_file($hash)
181 {
182 $p = s2p("$hash");
183 $f = VAR_FILES . $p . $hash;
184 if (file_exists($f) && is_file($f)) {
185 unlink($f);
186 }
187 if (file_exists($f . '_count') && is_file($f . '_count')) {
188 unlink($f . '_count');
189 }
190 $parse = VAR_FILES . $p;
191 $scan = array();
192 while (file_exists($parse)
193 && ($scan = scandir($parse))
194 && count($scan) == 2 // '.' and '..' folders => empty.
195 && basename($parse) != basename(VAR_FILES)) {
196 rmdir($parse);
197 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
198 }
199 }
200
201 /**
202 * transforms a php.ini string representing a value in an integer
203 * @param $value the value from php.ini
204 * @returns an integer for this value
205 */
206 function jirafeau_ini_to_bytes($value)
207 {
208 $modifier = substr($value, -1);
209 $bytes = substr($value, 0, -1);
210 switch (strtoupper($modifier)) {
211 default:
212 return intval($value);
213 break;
214 case 'P':
215 $bytes *= 1024;
216 // no break
217 case 'T':
218 $bytes *= 1024;
219 // no break
220 case 'G':
221 $bytes *= 1024;
222 // no break
223 case 'M':
224 $bytes *= 1024;
225 // no break
226 case 'K':
227 $bytes *= 1024;
228 }
229 return $bytes;
230 }
231
232 /**
233 * gets the maximum upload size according to php.ini
234 * @returns the maximum upload size in bytes
235 */
236 function jirafeau_get_max_upload_size_bytes()
237 {
238 return min(
239 jirafeau_ini_to_bytes(ini_get('post_max_size')),
240 jirafeau_ini_to_bytes(ini_get('upload_max_filesize'))
241 );
242 }
243
244 /**
245 * gets the maximum upload size according to php.ini
246 * @returns the maximum upload size string
247 */
248 function jirafeau_get_max_upload_size()
249 {
250 return jirafeau_human_size(jirafeau_get_max_upload_size_bytes());
251 }
252
253 /**
254 * get the maximal upload size for a data chunk in async uploads
255 * @param max_upload_chunk_size_bytes
256 */
257 function jirafeau_get_max_upload_chunk_size_bytes($max_upload_chunk_size_bytes = 0)
258 {
259 if ($max_upload_chunk_size_bytes == 0) {
260 $size = jirafeau_get_max_upload_size_bytes();
261 // Jirafeau must choose an arbitrary number as PHP config does not give any limit nor $max_upload_chunk_size_bytes
262 if ($size == 0) {
263 return 10000000; // 10MB
264 }
265 return $size;
266 }
267 $size = min(
268 jirafeau_get_max_upload_size_bytes(),
269 $max_upload_chunk_size_bytes
270 );
271 if ($size == 0) {
272 return $max_upload_chunk_size_bytes;
273 }
274 return $size;
275 }
276
277 /**
278 * gets a string explaining the error
279 * @param $code the error code
280 * @returns a string explaining the error
281 */
282 function jirafeau_upload_errstr($code)
283 {
284 switch ($code) {
285 case UPLOAD_ERR_INI_SIZE:
286 case UPLOAD_ERR_FORM_SIZE:
287 return t('Your file exceeds the maximum authorized file size. ');
288
289 case UPLOAD_ERR_PARTIAL:
290 case UPLOAD_ERR_NO_FILE:
291 return
292 t('Your file was not uploaded correctly. You may succeed in retrying. ');
293
294 case UPLOAD_ERR_NO_TMP_DIR:
295 case UPLOAD_ERR_CANT_WRITE:
296 case UPLOAD_ERR_EXTENSION:
297 return t('Internal error. You may not succeed in retrying. ');
298 }
299 return t('Unknown error. ');
300 }
301
302 /** Remove link and it's file
303 * @param $link the link's name (hash)
304 */
305
306 function jirafeau_delete_link($link)
307 {
308 $l = jirafeau_get_link($link);
309 if (!count($l)) {
310 return;
311 }
312
313 jirafeau_clean_rm_link($link);
314
315 $hash = $l['hash'];
316 $p = s2p("$hash");
317
318 $counter = 1;
319 if (file_exists(VAR_FILES . $p . $hash. '_count')) {
320 $content = file(VAR_FILES . $p . $hash. '_count');
321 $counter = trim($content[0]);
322 }
323 $counter--;
324
325 if ($counter >= 1) {
326 $handle = fopen(VAR_FILES . $p . $hash. '_count', 'w');
327 fwrite($handle, $counter);
328 fclose($handle);
329 }
330
331 if ($counter == 0) {
332 jirafeau_clean_rm_file($hash);
333 }
334 }
335
336 /**
337 * Delete a file and it's links.
338 */
339 function jirafeau_delete_file($hash)
340 {
341 $count = 0;
342 /* Get all links files. */
343 $stack = array(VAR_LINKS);
344 while (($d = array_shift($stack)) && $d != null) {
345 $dir = scandir($d);
346
347 foreach ($dir as $node) {
348 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
349 preg_match('/\.tmp/i', "$node")) {
350 continue;
351 }
352
353 if (is_dir($d . $node)) {
354 /* Push new found directory. */
355 $stack[] = $d . $node . '/';
356 } elseif (is_file($d . $node)) {
357 /* Read link informations. */
358 $l = jirafeau_get_link(basename($node));
359 if (!count($l)) {
360 continue;
361 }
362 if ($l['hash'] == $hash) {
363 $count++;
364 jirafeau_delete_link($node);
365 }
366 }
367 }
368 }
369 jirafeau_clean_rm_file($hash);
370 return $count;
371 }
372
373
374 /** hash file's content
375 * @param $method hash method, see 'file_hash' option. Valid methods are 'md5', 'md5_outside' or 'random'
376 * @param $file_path file to hash
377 * @returns hash string
378 */
379 function jirafeau_hash_file($method, $file_path)
380 {
381 switch ($method) {
382 case 'md5_outside':
383 return jirafeau_md5_outside($file_path);
384 case 'md5':
385 return md5_file($file_path);
386 case 'random':
387 return jirafeau_gen_random(32);
388 }
389 return md5_file($file_path);
390 }
391
392 /** hash part of file: start, end and size.
393 * This is a partial file hash, faster but weaker.
394 * @param $file_path file to hash
395 * @returns hash string
396 */
397 function jirafeau_md5_outside($file_path)
398 {
399 $out = false;
400 $handle = fopen($file_path, "r");
401 if ($handle === false) {
402 return false;
403 }
404 $size = filesize($file_path);
405 if ($size === false) {
406 goto err;
407 }
408 $first = fread($handle, 64);
409 if ($first === false) {
410 goto err;
411 }
412 if (fseek($handle, $size < 64 ? 0 : $size - 64) == -1) {
413 goto err;
414 }
415 $last = fread($handle, 64);
416 if ($last === false) {
417 goto err;
418 }
419 $out = md5($first . $last . $size);
420 err:
421 fclose($handle);
422 return $out;
423 }
424
425 /**
426 * handles an uploaded file
427 * @param $file the file struct given by $_FILE[]
428 * @param $one_time_download is the file a one time download ?
429 * @param $key if not empty, protect the file with this key
430 * @param $time the time of validity of the file
431 * @param $ip uploader's ip
432 * @param $crypt boolean asking to crypt or not
433 * @param $link_name_length size of the link name
434 * @returns an array containing some information
435 * 'error' => information on possible errors
436 * 'link' => the link name of the uploaded file
437 * 'delete_link' => the link code to delete file
438 */
439 function jirafeau_upload($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length, $file_hash_method)
440 {
441 if (empty($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
442 return (array(
443 'error' =>
444 array('has_error' => true,
445 'why' => jirafeau_upload_errstr($file['error'])),
446 'link' => '',
447 'delete_link' => ''));
448 }
449
450 /* array representing no error */
451 $noerr = array('has_error' => false, 'why' => '');
452
453 /* Crypt file if option is enabled. */
454 $crypted = false;
455 $crypt_key = '';
456 if ($crypt == true && !(extension_loaded('sodium') == true)) {
457 error_log("PHP extension sodium not loaded, won't encrypt in Jirafeau");
458 }
459 if ($crypt == true && extension_loaded('sodium') == true) {
460 $crypt_key = jirafeau_encrypt_file($file['tmp_name'], $file['tmp_name'].'crypt');
461 if (strlen($crypt_key) > 0) {
462 if (rename($file['tmp_name'].'crypt', $file['tmp_name']) === true) {
463 $crypted = true;
464 }
465 }
466 }
467
468 /* file information */
469 $hash = jirafeau_hash_file($file_hash_method, $file['tmp_name']);
470 $name = str_replace(NL, '', trim($file['name']));
471 $mime_type = $file['type'];
472 $size = $file['size'];
473
474 /* does file already exist ? */
475 $rc = false;
476 $p = s2p("$hash");
477 if (file_exists(VAR_FILES . $p . $hash)) {
478 $rc = unlink($file['tmp_name']);
479 } elseif ((file_exists(VAR_FILES . $p) || @mkdir(VAR_FILES . $p, 0755, true))
480 && move_uploaded_file($file['tmp_name'], VAR_FILES . $p . $hash)) {
481 $rc = true;
482 }
483 if (!$rc) {
484 return (array(
485 'error' =>
486 array('has_error' => true,
487 'why' => t('INTERNAL_ERROR_DEL')),
488 'link' =>'',
489 'delete_link' => ''));
490 }
491
492 /* Increment or create count file. */
493 $counter = 0;
494 if (file_exists(VAR_FILES . $p . $hash . '_count')) {
495 $content = file(VAR_FILES . $p . $hash. '_count');
496 $counter = trim($content[0]);
497 }
498 $counter++;
499 $handle = fopen(VAR_FILES . $p . $hash. '_count', 'w');
500 fwrite($handle, $counter);
501 fclose($handle);
502
503 /* Create delete code. */
504 $delete_link_code = jirafeau_gen_random(5);
505
506 /* hash password or empty. */
507 $password = '';
508 if (!empty($key)) {
509 $password = md5($key);
510 }
511
512 /* create link file */
513 $link_tmp_name = VAR_LINKS . $hash . rand(0, 10000) . '.tmp';
514 $handle = fopen($link_tmp_name, 'w');
515 fwrite(
516 $handle,
517 $name . NL. $mime_type . NL. $size . NL. $password . NL. $time .
518 NL . $hash. NL . ($one_time_download ? 'O' : 'R') . NL . time() .
519 NL . $ip . NL. $delete_link_code . NL . ($crypted ? 'C2' : 'O')
520 );
521 fclose($handle);
522 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
523 $l = s2p("$hash_link");
524 if (!@mkdir(VAR_LINKS . $l, 0755, true) ||
525 !rename($link_tmp_name, VAR_LINKS . $l . $hash_link)) {
526 if (file_exists($link_tmp_name)) {
527 unlink($link_tmp_name);
528 }
529
530 $counter--;
531 if ($counter >= 1) {
532 $handle = fopen(VAR_FILES . $p . $hash. '_count', 'w');
533 fwrite($handle, $counter);
534 fclose($handle);
535 } else {
536 jirafeau_clean_rm_file($hash_link);
537 }
538 return array(
539 'error' =>
540 array('has_error' => true,
541 'why' => t('Internal error during file creation. ')),
542 'link' =>'',
543 'delete_link' => '');
544 }
545 return array( 'error' => $noerr,
546 'link' => $hash_link,
547 'delete_link' => $delete_link_code,
548 'crypt_key' => $crypt_key);
549 }
550
551 /**
552 * Tells if a mime-type is viewable in a browser
553 * @param $mime the mime type
554 * @returns a boolean telling if a mime type is viewable
555 */
556 function jirafeau_is_viewable($mime)
557 {
558 if (!empty($mime)) {
559 $viewable = array('image', 'video', 'audio');
560 $decomposed = explode('/', $mime);
561 if (in_array($decomposed[0], $viewable) && strpos($mime, 'image/svg+xml') === false) {
562 return true;
563 }
564 $viewable = array('text/plain');
565 if (in_array($mime, $viewable)) {
566 return true;
567 }
568 }
569 return false;
570 }
571
572 // Error handling functions.
573 //! Global array that contains all registered errors.
574 $error_list = array();
575
576 /**
577 * Adds an error to the list of errors.
578 * @param $title the error's title
579 * @param $description is a human-friendly description of the problem.
580 */
581 function add_error($title, $description)
582 {
583 global $error_list;
584 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
585 }
586
587 /**
588 * Informs whether any error has been registered yet.
589 * @return true if there are errors.
590 */
591 function has_error()
592 {
593 global $error_list;
594 return !empty($error_list);
595 }
596
597 /**
598 * Displays all the errors.
599 */
600 function show_errors()
601 {
602 if (has_error()) {
603 global $error_list;
604 echo '<div class="error">';
605 foreach ($error_list as $error) {
606 echo $error;
607 }
608 echo '</div>';
609 }
610 }
611
612 function check_errors($cfg)
613 {
614 if (!($cfg['installation_done'] === true)) {
615 if (file_exists(JIRAFEAU_ROOT . 'install.php')) {
616 header('Location: install.php');
617 exit;
618 } else {
619 add_error(t('INSTALL_FILE_NOT_FOUND_TITLE'), t('INSTALL_FILE_NOT_FOUND_DESC'));
620 }
621 }
622
623 if (!is_writable(VAR_FILES)) {
624 add_error(t('FILE_DIR_W'), VAR_FILES);
625 }
626
627 if (!is_writable(VAR_LINKS)) {
628 add_error(t('LINK_DIR_W'), VAR_LINKS);
629 }
630
631 if (!is_writable(VAR_ASYNC)) {
632 add_error(t('ASYNC_DIR_W'), VAR_ASYNC);
633 }
634
635 if ($cfg['enable_crypt'] && $cfg['litespeed_workaround']) {
636 add_error(t('INCOMPATIBLE_OPTIONS_W'), 'enable_crypt=true<br>litespeed_workaround=true');
637 }
638
639 if ($cfg['one_time_download'] && $cfg['litespeed_workaround']) {
640 add_error(t('INCOMPATIBLE_OPTIONS_W'), 'one_time_download=true<br>litespeed_workaround=true');
641 }
642 }
643
644 /**
645 * Read link information
646 * @return array containing information.
647 */
648 function jirafeau_get_link($hash)
649 {
650 $out = array();
651 $link = VAR_LINKS . s2p("$hash") . $hash;
652
653 if (!file_exists($link)) {
654 return $out;
655 }
656
657 $c = file($link);
658 $out['file_name'] = trim($c[0]);
659 $out['mime_type'] = trim($c[1]);
660 $out['file_size'] = trim($c[2]);
661 $out['key'] = trim($c[3], NL);
662 $out['time'] = trim($c[4]);
663 $out['hash'] = trim($c[5]);
664 $out['onetime'] = trim($c[6]);
665 $out['upload_date'] = trim($c[7]);
666 $out['ip'] = trim($c[8]);
667 $out['link_code'] = trim($c[9]);
668 $out['crypted'] = trim($c[10]) == 'C2';
669 $out['crypted_legacy'] = trim($c[10]) == 'C';
670
671 return $out;
672 }
673
674 /**
675 * List files in admin interface.
676 */
677 function jirafeau_admin_list($name, $file_hash, $link_hash)
678 {
679 echo '<fieldset><legend>';
680 if (!empty($name)) {
681 echo t('FILENAME') . ": " . jirafeau_escape($name);
682 }
683 if (!empty($file_hash)) {
684 echo t('FILE') . ": " . jirafeau_escape($file_hash);
685 }
686 if (!empty($link_hash)) {
687 echo t('LINK') . ": " . jirafeau_escape($link_hash);
688 }
689 if (empty($name) && empty($file_hash) && empty($link_hash)) {
690 echo t('LS_FILES');
691 }
692 echo '</legend>';
693 echo '<table>';
694 echo '<tr>';
695 echo '<th></th>';
696 echo '<th>' . t('ACTION') . '</th>';
697 echo '</tr>';
698
699 /* Get all links files. */
700 $stack = array(VAR_LINKS);
701 while (($d = array_shift($stack)) && $d != null) {
702 $dir = scandir($d);
703 foreach ($dir as $node) {
704 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
705 preg_match('/\.tmp/i', "$node")) {
706 continue;
707 }
708 if (is_dir($d . $node)) {
709 /* Push new found directory. */
710 $stack[] = $d . $node . '/';
711 } elseif (is_file($d . $node)) {
712 /* Read link information. */
713 $l = jirafeau_get_link($node);
714 if (!count($l)) {
715 continue;
716 }
717 $ld = jirafeau_get_download_stats($node);
718
719 /* Filter. */
720 if (!empty($name) && !@preg_match("/$name/i", jirafeau_escape($l['file_name']))) {
721 continue;
722 }
723 if (!empty($file_hash) && $file_hash != $l['hash']) {
724 continue;
725 }
726 if (!empty($link_hash) && $link_hash != $node) {
727 continue;
728 }
729 /* Print link information. */
730 echo '<tr>';
731 echo '<td>' .
732 '<strong><a id="upload_link" href="f.php?h='. jirafeau_escape($node) .'" title="' .
733 t('DL_PAGE') . '">' . jirafeau_escape($l['file_name']) . '</a></strong><br/>';
734 echo t('TYPE') . ': ' . jirafeau_escape($l['mime_type']) . '<br/>';
735 echo t('SIZE') . ': ' . jirafeau_human_size($l['file_size']) . '<br>';
736 echo t('EXPIRE') . ': ' . ($l['time'] == -1 ? '∞' : jirafeau_get_datetimefield($l['time'])) . '<br/>';
737 echo t('ONETIME') . ': ' . ($l['onetime'] == 'O' ? 'Yes' : 'No') . '<br/>';
738 echo t('UPLOAD_DATE') . ': ' . jirafeau_get_datetimefield($l['upload_date']) . '<br/>';
739 if (strlen($l['ip']) > 0) {
740 echo t('ORIGIN') . ': ' . $l['ip'] . '<br/>';
741 }
742 echo t('DOWNLOAD_COUNT') . ': ' . $ld['count'] . '<br/>';
743 if ($ld['count'] > 0) {
744 echo t('DOWNLOAD_DATE') . ': ' . jirafeau_get_datetimefield($ld['date']) . '<br/>';
745 echo t('DOWNLOAD_IP') . ': ' . $ld['ip'] . '<br/>';
746 }
747 echo '</td><td>';
748 echo '<form method="post">' .
749 '<input type = "hidden" name = "action" value = "download"/>' .
750 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
751 jirafeau_admin_csrf_field() .
752 '<input type = "submit" value = "' . t('DL') . '" />' .
753 '</form>' .
754 '<form method="post">' .
755 '<input type = "hidden" name = "action" value = "delete_link"/>' .
756 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
757 jirafeau_admin_csrf_field() .
758 '<input type = "submit" value = "' . t('DEL_LINK') . '" />' .
759 '</form>' .
760 '<form method="post">' .
761 '<input type = "hidden" name = "action" value = "delete_file"/>' .
762 '<input type = "hidden" name = "hash" value = "' . $l['hash'] . '"/>' .
763 jirafeau_admin_csrf_field() .
764 '<input type = "submit" value = "' . t('DEL_FILE_LINKS') . '" />' .
765 '</form>' .
766 '</td>';
767 echo '</tr>';
768 }
769 }
770 }
771 echo '</table></fieldset>';
772 }
773
774 /**
775 * Clean expired files.
776 * @return number of cleaned files.
777 */
778 function jirafeau_admin_clean()
779 {
780 $count = 0;
781 /* Get all links files. */
782 $stack = array(VAR_LINKS);
783 while (($d = array_shift($stack)) && $d != null) {
784 $dir = scandir($d);
785
786 foreach ($dir as $node) {
787 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
788 preg_match('/\.tmp/i', "$node")) {
789 continue;
790 }
791
792 if (is_dir($d . $node)) {
793 /* Push new found directory. */
794 $stack[] = $d . $node . '/';
795 } elseif (is_file($d . $node)) {
796 /* Read link information. */
797 $l = jirafeau_get_link(basename($node));
798 if (!count($l)) {
799 continue;
800 }
801 $p = s2p($l['hash']);
802 if ($l['time'] > 0 && $l['time'] < time() || // expired
803 !file_exists(VAR_FILES . $p . $l['hash']) || // invalid
804 !file_exists(VAR_FILES . $p . $l['hash'] . '_count')) { // invalid
805 jirafeau_delete_link($node);
806 $count++;
807 }
808 }
809 }
810 }
811 return $count;
812 }
813
814
815 /**
816 * Clean old async transfers.
817 * @return number of cleaned files.
818 */
819 function jirafeau_admin_clean_async()
820 {
821 $count = 0;
822 /* Get all links files. */
823 $stack = array(VAR_ASYNC);
824 while (($d = array_shift($stack)) && $d != null) {
825 $dir = scandir($d);
826
827 foreach ($dir as $node) {
828 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
829 preg_match('/\.tmp/i', "$node")) {
830 continue;
831 }
832
833 if (is_dir($d . $node)) {
834 /* Push new found directory. */
835 $stack[] = $d . $node . '/';
836 } elseif (is_file($d . $node)) {
837 /* Read async information. */
838 $a = jirafeau_get_async_ref(basename($node));
839 if (!count($a)) {
840 continue;
841 }
842 /* Delete transfers older than 1 hour. */
843 if (time() - $a['last_edited'] > 3600) {
844 jirafeau_async_delete(basename($node));
845 $count++;
846 }
847 }
848 }
849 }
850 return $count;
851 }
852
853 /**
854 * Better strval function for debug purposes
855 */
856 function jirafeau_strval($value)
857 {
858 if (gettype($value) == "boolean") {
859 return $value ? 'true' : 'false';
860 }
861 return strval($value);
862 }
863
864 /**
865 * Show file/folder permissions
866 */
867 function jirafeau_fileperms($path)
868 {
869 $out = substr(sprintf("%o", @fileperms($path)), -4) . ", ";
870 $out .= "read " . (is_readable($path) ? "OK" : "KO") . ", ";
871 $out .= "write " . (is_writable($path) ? "OK" : "KO");
872 return $out;
873 }
874
875 /**
876 * Show some useful informations for bug reporting.
877 */
878 function jirafeau_admin_bug_report($cfg)
879 {
880 $out = "<fieldset><legend>" . t('REPORTING_AN_ISSUE') . "</legend>";
881 $out .= "If you have a problem related to Jirafeau, please <a href='" . JIRAFEAU_WEBSITE . "/-/issues'>open an issue</a>, explain your problem in english and copy-paste the following content:<br/><br/><code>";
882
883 $out .= "# Jirafeau<br/>";
884 $out .= "- version: " . JIRAFEAU_VERSION . "<br/>";
885 $jirafeau_options = [
886 'debug',
887 'file_hash',
888 'litespeed_workaround',
889 'store_uploader_ip',
890 'installation_done',
891 'enable_crypt',
892 'preview',
893 'maximal_upload_size',
894 'store_uploader_ip',
895 'max_upload_chunk_size_bytes'
896 ];
897 foreach ($jirafeau_options as &$o) {
898 $v = $cfg[$o];
899 $out .= "- $o: " . jirafeau_strval($v) . " (" . gettype($v) . ")<br/>";
900 }
901 $out .= "<br/>";
902
903 $out .= "# PHP options<br/>";
904 $out .= "- php version: " . phpversion() . "<br/>";
905 $out .= "- sodium version: " . phpversion('sodium') . "<br/>";
906 $out .= "- mcrypt version: " . phpversion('mcrypt') . "<br/>";
907 $php_options = [
908 'post_max_size',
909 'upload_max_filesize',
910 'safe_mode',
911 'max_execution_time',
912 'max_input_time'
913 ];
914 foreach ($php_options as &$o) {
915 $v = ini_get($o);
916 $out .= "- $o: " . jirafeau_strval($v) . " (" . gettype($v). ")<br/>";
917 }
918 $out .= "- can set_time_limit: " . (set_time_limit(0) ? "yes" : "no") . "<br/>";
919 $out .= "<br/>";
920
921 $out .= "# File permissions<br/>";
922 $out .= "- 'var' folder permissions: " . jirafeau_fileperms($cfg['var_root']) . "<br/>";
923 $out .= "- 'file' folder permissions: " . jirafeau_fileperms(VAR_FILES) . "<br/>";
924 $out .= "- 'links' folder permissions: " . jirafeau_fileperms(VAR_LINKS) . "<br/>";
925 $out .= "- 'async' folder permissions: " . jirafeau_fileperms(VAR_ASYNC) . "<br/>";
926 $out .= "<br/>";
927
928 $out .= "# Server details<br/>";
929 $out .= "- server software: " . $_SERVER["SERVER_SOFTWARE"] . "<br/>";
930 $out .= "<br/>";
931
932 $out .= "# OS details<br/>";
933 $out .= "- OS: " . php_uname() . "<br/>";
934 $out .= "<br/>";
935
936 $out .= "# Browser details<br/>";
937 $out .= "<script type='text/javascript' lang='Javascript'>
938 // @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-v3-or-Later
939 document.write('- html5 support: ' + (check_html5_file_api() ? 'yes' : 'no') + '<br/>');
940 document.write('- user agent: ' + navigator.userAgent + '<br/>');
941 // @license-end
942 </script>";
943 $out .= "<br/>";
944
945 $out .= "# Memory<br/>";
946 $out .= "- memory_get_peak_usage: " . jirafeau_human_size(memory_get_peak_usage()) . "<br/>";
947
948 $out .= "</code></fieldset>";
949 return $out;
950 }
951
952 /**
953 * Read async transfer information
954 * @return array containing information.
955 */
956 function jirafeau_get_async_ref($ref)
957 {
958 $out = array();
959 $refinfos = VAR_ASYNC . s2p("$ref") . "$ref";
960
961 if (!file_exists($refinfos)) {
962 return $out;
963 }
964
965 $c = file($refinfos);
966 $out['file_name'] = trim($c[0]);
967 $out['mime_type'] = trim($c[1]);
968 $out['key'] = trim($c[2], NL);
969 $out['time'] = trim($c[3]);
970 $out['onetime'] = trim($c[4]);
971 $out['ip'] = trim($c[5]);
972 $out['last_edited'] = trim($c[6]);
973 $out['next_code'] = trim($c[7]);
974 return $out;
975 }
976
977 /**
978 * Delete async transfer information
979 */
980 function jirafeau_async_delete($ref)
981 {
982 $p = s2p("$ref");
983 if (file_exists(VAR_ASYNC . $p . $ref)) {
984 unlink(VAR_ASYNC . $p . $ref);
985 }
986 if (file_exists(VAR_ASYNC . $p . $ref . '_data')) {
987 unlink(VAR_ASYNC . $p . $ref . '_data');
988 }
989 $parse = VAR_ASYNC . $p;
990 $scan = array();
991 while (file_exists($parse)
992 && ($scan = scandir($parse))
993 && count($scan) == 2 // '.' and '..' folders => empty.
994 && basename($parse) != basename(VAR_ASYNC)) {
995 rmdir($parse);
996 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
997 }
998 }
999
1000 /**
1001 * Init a new asynchronous upload.
1002 * @param $filename Name of the file to send
1003 * @param $one_time One time upload parameter
1004 * @param $key eventual password (or blank)
1005 * @param $time time limit
1006 * @param $ip ip address of the client
1007 * @return a string containing a temporary reference followed by a code or a string starting with 'Error'
1008 */
1009 function jirafeau_async_init($filename, $type, $one_time, $key, $time, $ip)
1010 {
1011 /* Create temporary folder. */
1012 $ref;
1013 $p;
1014 $code = jirafeau_gen_random(4);
1015 do {
1016 $ref = jirafeau_gen_random(32);
1017 $p = VAR_ASYNC . s2p($ref);
1018 } while (file_exists($p));
1019 @mkdir($p, 0755, true);
1020 if (!file_exists($p)) {
1021 return 'Error: cannot create async folder.';
1022 }
1023
1024 /* touch empty data file */
1025 $w_path = $p . $ref . '_data';
1026 touch($w_path);
1027
1028 /* md5 password or empty */
1029 $password = '';
1030 if (!empty($key)) {
1031 $password = md5($key);
1032 }
1033
1034 /* Store information. */
1035 $p .= $ref;
1036 $handle = fopen($p, 'w');
1037 fwrite(
1038 $handle,
1039 str_replace(NL, '', trim($filename)) . NL .
1040 str_replace(NL, '', trim($type)) . NL . $password . NL .
1041 $time . NL . ($one_time ? 'O' : 'R') . NL . $ip . NL .
1042 time() . NL . $code . NL
1043 );
1044 fclose($handle);
1045
1046 return $ref . NL . $code ;
1047 }
1048
1049 /**
1050 * Append a piece of file on the asynchronous upload.
1051 * @param $ref asynchronous upload reference
1052 * @param $file piece of data
1053 * @param $code client code for this operation
1054 * @param $max_file_size maximum allowed file size
1055 * @return a string containing a next code to use or a string starting with 'Error'
1056 */
1057 function jirafeau_async_push($ref, $data, $code, $max_file_size)
1058 {
1059 /* Get async infos. */
1060 $a = jirafeau_get_async_ref($ref);
1061
1062 /* Check some errors. */
1063 if (count($a) == 0) {
1064 return "Error: cannot find transfer";
1065 }
1066 if ($a['next_code'] != "$code") {
1067 return "Error: bad transfer code";
1068 }
1069 if ($data['error'] != UPLOAD_ERR_OK) {
1070 // Check error code in https://www.php.net/manual/en/features.file-upload.errors.php
1071 $data_details = print_r($data, true);
1072 return "Error: upload error: {$data_details}";
1073 }
1074 if (empty($data['tmp_name'])) {
1075 return "Error: missing tmp_name";
1076 }
1077 if (!is_uploaded_file($data['tmp_name'])) {
1078 return "Error: tmp_name may not be uploaded";
1079 }
1080
1081 $p = s2p($ref);
1082
1083 /* File path. */
1084 $r_path = $data['tmp_name'];
1085 $w_path = VAR_ASYNC . $p . $ref . '_data';
1086
1087 /* Check that file size is not above upload limit. */
1088 if ($max_file_size > 0 &&
1089 filesize($r_path) + filesize($w_path) > $max_file_size * 1024 * 1024) {
1090 jirafeau_async_delete($ref);
1091 return "Error: file size is above upload limit";
1092 }
1093
1094 /* Concatenate data. */
1095 $r = fopen($r_path, 'r');
1096 $w = fopen($w_path, 'a');
1097 while (!feof($r)) {
1098 if (fwrite($w, fread($r, 1024)) === false) {
1099 fclose($r);
1100 fclose($w);
1101 jirafeau_async_delete($ref);
1102 return "Error: cannot write file";
1103 }
1104 }
1105 fclose($r);
1106 fclose($w);
1107 unlink($r_path);
1108
1109 /* Update async file. */
1110 $code = jirafeau_gen_random(4);
1111 $handle = fopen(VAR_ASYNC . $p . $ref, 'w');
1112 fwrite(
1113 $handle,
1114 $a['file_name'] . NL. $a['mime_type'] . NL. $a['key'] . NL .
1115 $a['time'] . NL . $a['onetime'] . NL . $a['ip'] . NL .
1116 time() . NL . $code . NL
1117 );
1118 fclose($handle);
1119 return $code;
1120 }
1121
1122 /**
1123 * Finalize an asynchronous upload.
1124 * @param $ref asynchronous upload reference
1125 * @param $code client code for this operation
1126 * @param $crypt boolean asking to crypt or not
1127 * @param $link_name_length link name length
1128 * @return a string containing the download reference followed by a delete code or a string starting with 'Error'
1129 */
1130 function jirafeau_async_end($ref, $code, $crypt, $link_name_length, $file_hash_method)
1131 {
1132 /* Get async infos. */
1133 $a = jirafeau_get_async_ref($ref);
1134 if (count($a) == 0
1135 || $a['next_code'] != "$code") {
1136 return "Error: bad code for ending transfer";
1137 }
1138
1139 /* Generate link infos. */
1140 $p = VAR_ASYNC . s2p($ref) . $ref . "_data";
1141 if (!file_exists($p)) {
1142 return "Error: referenced file does not exist";
1143 }
1144
1145 $crypted = false;
1146 $crypt_key = '';
1147 if ($crypt == true && extension_loaded('sodium') == true) {
1148 $crypt_key = jirafeau_encrypt_file($p, $p.'.crypt');
1149 if (strlen($crypt_key) > 0) {
1150 if (rename($p.'.crypt', $p) === true) {
1151 $crypted = true;
1152 }
1153 }
1154 }
1155
1156 $hash = jirafeau_hash_file($file_hash_method, $p);
1157 $size = filesize($p);
1158 $np = s2p($hash);
1159 $delete_link_code = jirafeau_gen_random(5);
1160
1161 /* File already exist ? */
1162 if (!file_exists(VAR_FILES . $np)) {
1163 @mkdir(VAR_FILES . $np, 0755, true);
1164 }
1165 if (!file_exists(VAR_FILES . $np . $hash)) {
1166 rename($p, VAR_FILES . $np . $hash);
1167 }
1168
1169 /* Increment or create count file. */
1170 $counter = 0;
1171 if (file_exists(VAR_FILES . $np . $hash . '_count')) {
1172 $content = file(VAR_FILES . $np . $hash. '_count');
1173 $counter = trim($content[0]);
1174 }
1175 $counter++;
1176 $handle = fopen(VAR_FILES . $np . $hash. '_count', 'w');
1177 fwrite($handle, $counter);
1178 fclose($handle);
1179
1180 /* Create link. */
1181 $link_tmp_name = VAR_LINKS . $hash . rand(0, 10000) . '.tmp';
1182 $handle = fopen($link_tmp_name, 'w');
1183 fwrite(
1184 $handle,
1185 $a['file_name'] . NL . $a['mime_type'] . NL . $size . NL .
1186 $a['key'] . NL . $a['time'] . NL . $hash . NL . $a['onetime'] . NL .
1187 time() . NL . $a['ip'] . NL . $delete_link_code . NL . ($crypted ? 'C2' : 'O')
1188 );
1189 fclose($handle);
1190 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
1191 $l = s2p("$hash_link");
1192 if (!@mkdir(VAR_LINKS . $l, 0755, true)) {
1193 return "Error: cannot create folder in LINKS";
1194 }
1195 if (!rename($link_tmp_name, VAR_LINKS . $l . $hash_link)) {
1196 return "Error: cannot rename file in LINKS";
1197 }
1198
1199 /* Clean async upload. */
1200 jirafeau_async_delete($ref);
1201 return $hash_link . NL . $delete_link_code . NL . urlencode($crypt_key);
1202 }
1203
1204 function jirafeau_crypt_create_iv($base, $size)
1205 {
1206 $iv = '';
1207 while (strlen($iv) < $size) {
1208 $iv = $iv . $base;
1209 }
1210 $iv = substr($iv, 0, $size);
1211 return $iv;
1212 }
1213
1214 /**
1215 * Crypt file using Sodium and returns decrypt key.
1216 * @param $fp_src file path to the file to crypt.
1217 * @param $fp_dst file path to the file to write crypted file (must not be the same).
1218 * @return key used to encrypt the file
1219 */
1220 function jirafeau_encrypt_file($fp_src, $fp_dst)
1221 {
1222 $fs = filesize($fp_src);
1223 if ($fs === false || $fs == 0 || extension_loaded('sodium') == false || $fp_src == $fp_dst) {
1224 return '';
1225 }
1226
1227 /* Generate key. */
1228 $crypt_key = bin2hex(random_bytes(SODIUM_CRYPTO_STREAM_XCHACHA20_KEYBYTES / 2));
1229 /* Init module. */
1230 [$crypt_state, $crypt_header] = sodium_crypto_secretstream_xchacha20poly1305_init_push($crypt_key);
1231 /* Crypt file. */
1232 $r = fopen($fp_src, 'rb');
1233 $w = fopen($fp_dst, 'wb');
1234 fwrite($w, $crypt_header);
1235
1236 for ($i = 0; $i < $fs; $i += JIRAFEAU_SODIUM_CHUNKSIZE) {
1237 $to_enc = fread($r, JIRAFEAU_SODIUM_CHUNKSIZE);
1238 $enc = sodium_crypto_secretstream_xchacha20poly1305_push($crypt_state, $to_enc);
1239
1240 if (fwrite($w, $enc) === false) {
1241 return '';
1242 }
1243 }
1244
1245 fclose($r);
1246 fclose($w);
1247
1248 /* Cleanup. */
1249 sodium_memzero($crypt_state);
1250
1251 return $crypt_key;
1252 }
1253
1254 /**
1255 * Decrypt file using Sodium.
1256 * @param $fp_src file path to the file to decrypt.
1257 * @param $fp_dst file path to the file to write decrypted file (must not be the same).
1258 * @param $k decryption key
1259 * @return true if decryption succeeded, false otherwise
1260 */
1261 function jirafeau_decrypt_file($fp_src, $fp_dst, $k)
1262 {
1263 $fs = filesize($fp_src);
1264 if ($fs === false || $fs == 0 || extension_loaded('sodium') == false || $fp_src == $fp_dst) {
1265 return false;
1266 }
1267
1268 /* Decrypt file. */
1269 $r = fopen($fp_src, 'rb');
1270 $w = fopen($fp_dst, 'wb');
1271
1272 $crypt_header = fread($r, SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES);
1273
1274 /* Init module. */
1275 $crypt_state = sodium_crypto_secretstream_xchacha20poly1305_init_pull($crypt_header, $k);
1276
1277 /* Decrypt file. */
1278
1279 for ($i = SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES; $i < $fs; $i += JIRAFEAU_SODIUM_CHUNKSIZE + SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES) {
1280 $to_dec = fread($r, JIRAFEAU_SODIUM_CHUNKSIZE + SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES);
1281 [$dec, $crypt_tag] = sodium_crypto_secretstream_xchacha20poly1305_pull($crypt_state, $to_dec);
1282
1283 if (fwrite($w, $dec) === false) {
1284 return false;
1285 }
1286 }
1287
1288 fclose($r);
1289 fclose($w);
1290
1291 /* Cleanup. */
1292 sodium_memzero($crypt_state);
1293
1294 return true;
1295 }
1296
1297 /**
1298 * Decrypt file using mcrypt.
1299 * @param $fp_src file path to the file to decrypt.
1300 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1301 * @param $k string composed of the key and the iv separated by a point ('.')
1302 * @return true if decryption succeeded, false otherwise
1303 */
1304 function jirafeau_decrypt_file_legacy($fp_src, $fp_dst, $k)
1305 {
1306 $fs = filesize($fp_src);
1307 if ($fs === false || $fs == 0 || extension_loaded('mcrypt') == false) {
1308 return false;
1309 }
1310
1311 /* Init module */
1312 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1313 /* Extract key and iv. */
1314 $crypt_key = $k;
1315 $hash_key = md5($crypt_key);
1316 $iv = jirafeau_crypt_create_iv($hash_key, mcrypt_enc_get_iv_size($m));
1317 /* Init module. */
1318 mcrypt_generic_init($m, $hash_key, $iv);
1319 /* Decrypt file. */
1320 $r = fopen($fp_src, 'r');
1321 $w = fopen($fp_dst, 'c');
1322 while (!feof($r)) {
1323 $dec = mdecrypt_generic($m, fread($r, 1024));
1324 if (fwrite($w, $dec) === false) {
1325 return false;
1326 }
1327 }
1328 fclose($r);
1329 fclose($w);
1330 /* Cleanup. */
1331 mcrypt_generic_deinit($m);
1332 mcrypt_module_close($m);
1333 return true;
1334 }
1335
1336 /**
1337 * Check if Jirafeau is password protected for visitors.
1338 * @return true if Jirafeau is password protected, false otherwise.
1339 */
1340 function jirafeau_has_upload_password($cfg)
1341 {
1342 return count($cfg['upload_password']) > 0;
1343 }
1344
1345 /**
1346 * Challenge password for a visitor.
1347 * @param $password password to be challenged
1348 * @return true if password is valid, false otherwise.
1349 */
1350 function jirafeau_challenge_upload_password($cfg, $password)
1351 {
1352 if (!jirafeau_has_upload_password($cfg)) {
1353 return false;
1354 }
1355 foreach ($cfg['upload_password'] as $p) {
1356 if ($password == $p) {
1357 return true;
1358 }
1359 }
1360 return false;
1361 }
1362
1363 /**
1364 * Test if the given IP is whitelisted by the given list.
1365 *
1366 * @param $allowedIpList array of allowed IPs
1367 * @param $challengedIp IP to be challenged
1368 * @return true if IP is authorized, false otherwise.
1369 */
1370 function jirafeau_challenge_ip($allowedIpList, $challengedIp)
1371 {
1372 foreach ($allowedIpList as $i) {
1373 if ($i == $challengedIp) {
1374 return true;
1375 }
1376 // CIDR test for IPv4 only.
1377 if (strpos($i, '/') !== false) {
1378 list($subnet, $mask) = explode('/', $i);
1379 if ((ip2long($challengedIp) & ~((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
1380 return true;
1381 }
1382 }
1383 }
1384 return false;
1385 }
1386
1387 /**
1388 * Check if Jirafeau has a restriction on the IP address for uploading.
1389 * @return true if uploading is IP restricted, false otherwise.
1390 */
1391 function jirafeau_upload_has_ip_restriction($cfg)
1392 {
1393 return count($cfg['upload_ip']) > 0;
1394 }
1395
1396 /**
1397 * Test if visitor's IP is authorized to upload at all.
1398 *
1399 * @param $cfg configuration
1400 * @param $challengedIp IP to be challenged
1401 * @return true if IP is authorized, false otherwise.
1402 */
1403 function jirafeau_challenge_upload_ip($cfg, $challengedIp)
1404 {
1405 // If no IP address have been listed, allow upload from any IP
1406 if (!jirafeau_upload_has_ip_restriction($cfg)) {
1407 return true;
1408 }
1409 return jirafeau_challenge_ip($cfg['upload_ip'], $challengedIp);
1410 }
1411
1412 /**
1413 * Test if visitor's IP is authorized to upload without a password.
1414 *
1415 * @param $cfg configuration
1416 * @param $challengedIp IP to be challenged
1417 * @return true if IP is authorized, false otherwise.
1418 */
1419 function jirafeau_challenge_upload_ip_without_password($cfg, $challengedIp)
1420 {
1421 return jirafeau_challenge_ip($cfg['upload_ip_nopassword'], $challengedIp);
1422 }
1423
1424 /**
1425 * Test if visitor's IP is authorized or password is supplied and authorized
1426 * @param $ip IP to be challenged
1427 * @param $password password to be challenged
1428 * @return true if access is valid, false otherwise.
1429 */
1430 function jirafeau_challenge_upload($cfg, $ip, $password)
1431 {
1432 return jirafeau_challenge_upload_ip_without_password($cfg, $ip) ||
1433 (!jirafeau_has_upload_password($cfg) && !jirafeau_upload_has_ip_restriction($cfg)) ||
1434 (jirafeau_challenge_upload_password($cfg, $password) && jirafeau_challenge_upload_ip($cfg, $ip));
1435 }
1436
1437 /**
1438 * Check if Jirafeau has a restriction on the IP address for accessing the admin interface.
1439 * @return true if admin interface is IP restricted, false otherwise.
1440 */
1441 function jirafeau_admin_has_ip_restriction($cfg)
1442 {
1443 return count($cfg['admin_ip']) > 0;
1444 }
1445
1446 /**
1447 * Test if visitor's IP is authorized to access the admin interface.
1448 *
1449 * @param $cfg configuration
1450 * @param $challengedIp IP to be challenged
1451 * @return true if IP is authorized, false otherwise.
1452 */
1453 function jirafeau_challenge_admin_ip($cfg, $challengedIp)
1454 {
1455 // If no IP address have been listed, allow upload from any IP
1456 if (!jirafeau_admin_has_ip_restriction($cfg)) {
1457 return true;
1458 }
1459 return jirafeau_challenge_ip($cfg['admin_ip'], $challengedIp);
1460 }
1461
1462 /** Tell if we have some HTTP headers generated by a proxy */
1463 function has_http_forwarded()
1464 {
1465 return
1466 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1467 !empty($_SERVER['http_X_forwarded_for']);
1468 }
1469
1470 /**
1471 * Generate IP list from HTTP headers generated by a proxy
1472 * @return array of IP strings
1473 */
1474 function get_ip_list_http_forwarded()
1475 {
1476 $ip_list = array();
1477 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1478 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1479 if ($l === false) {
1480 return array();
1481 }
1482 foreach ($l as $ip) {
1483 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1484 }
1485 }
1486 if (!empty($_SERVER['http_X_forwarded_for'])) {
1487 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1488 foreach ($l as $ip) {
1489 // Separate IP from port
1490 $ipa = explode(':', $ip);
1491 if ($ipa === false) {
1492 continue;
1493 }
1494 $ip = $ipa[0];
1495 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1496 }
1497 }
1498 return $ip_list;
1499 }
1500
1501 /**
1502 * Get the ip address of the client from REMOTE_ADDR
1503 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1504 * @returns the client ip address
1505 */
1506 function get_ip_address($cfg)
1507 {
1508 $remote = $_SERVER['REMOTE_ADDR'];
1509 if (count($cfg['proxy_ip']) == 0 || !has_http_forwarded()) {
1510 return $remote;
1511 }
1512
1513 $ip_list = get_ip_list_http_forwarded();
1514 if (count($ip_list) == 0) {
1515 return $remote;
1516 }
1517
1518 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1519 if ($remote != $proxy_ip) {
1520 continue;
1521 }
1522 // Take the last IP (the one which has been set by the defined proxy).
1523 return end($ip_list);
1524 }
1525 return $remote;
1526 }
1527
1528 /**
1529 * Convert hexadecimal string to base64
1530 */
1531 function hex_to_base64($hex)
1532 {
1533 $b = '';
1534 foreach (str_split($hex, 2) as $pair) {
1535 $b .= chr(hexdec($pair));
1536 }
1537 return base64_encode($b);
1538 }
1539
1540 /**
1541 * Replace markers in templates.
1542 *
1543 * Available markers have the scheme "###MARKERNAME###".
1544 *
1545 * @param $content string Template text with markers
1546 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1547 * @return Template with replaced markers
1548 */
1549 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1550 {
1551 $patterns = array(
1552 '/###ORGANISATION###/',
1553 '/###CONTACTPERSON###/',
1554 '/###WEBROOT###/'
1555 );
1556 $replacements = array(
1557 $GLOBALS['cfg']['organisation'],
1558 $GLOBALS['cfg']['contactperson'],
1559 $GLOBALS['cfg']['web_root']
1560 );
1561 $content = preg_replace($patterns, $replacements, $content);
1562
1563 if (true === $htmllinebreaks) {
1564 $content = nl2br($content);
1565 }
1566
1567 return $content;
1568 }
1569
1570 function jirafeau_escape($string)
1571 {
1572 return htmlspecialchars($string, ENT_QUOTES);
1573 }
1574
1575 function jirafeau_admin_session_start()
1576 {
1577 $_SESSION['admin_auth'] = true;
1578 $_SESSION['admin_csrf'] = md5(uniqid(mt_rand(), true));
1579 }
1580
1581 function jirafeau_session_end()
1582 {
1583 $_SESSION = array();
1584 session_destroy();
1585 }
1586
1587 function jirafeau_admin_session_logged()
1588 {
1589 return isset($_SESSION['admin_auth']) &&
1590 isset($_SESSION['admin_csrf']) &&
1591 isset($_POST['admin_csrf']) &&
1592 $_SESSION['admin_auth'] === true &&
1593 $_SESSION['admin_csrf'] === $_POST['admin_csrf'];
1594 }
1595
1596 function jirafeau_admin_csrf_field()
1597 {
1598 return "<input type='hidden' name='admin_csrf' value='". $_SESSION['admin_csrf'] . "'/>";
1599 }
1600
1601 function jirafeau_user_session_start()
1602 {
1603 $_SESSION['user_auth'] = true;
1604 }
1605
1606 function jirafeau_user_session_logged()
1607 {
1608 return isset($_SESSION['user_auth']) &&
1609 $_SESSION['user_auth'] === true;
1610 }
1611
1612 function jirafeau_dir_size($dir)
1613 {
1614 $size = 0;
1615 foreach (glob(rtrim($dir, '/').'/*', GLOB_NOSORT) as $entry) {
1616 $size += is_file($entry) ? filesize($entry) : jirafeau_dir_size($entry);
1617 }
1618 return $size;
1619 }
1620
1621 function jirafeau_export_cfg($cfg)
1622 {
1623 $content = '<?php' . NL;
1624 $content .= '/* This file was generated by the install process. ' .
1625 'You can edit it. Please see config.original.php to understand the ' .
1626 'configuration items. */' . NL;
1627 $content .= '$cfg = ' . var_export($cfg, true) . ';';
1628
1629 $fileWrite = file_put_contents(JIRAFEAU_CFG, $content);
1630
1631 if (false === $fileWrite) {
1632 jirafeau_fatal_error(t('Can not write local configuration file'));
1633 }
1634 }
1635
1636 function jirafeau_mkdir($path)
1637 {
1638 return !(!file_exists($path) && !@mkdir($path, 0755));
1639 }
1640
1641 /**
1642 * Returns true whether the path is writable or we manage to make it
1643 * so, which essentially is the same thing.
1644 * @param $path is the file or directory to be tested.
1645 * @return true if $path is writable.
1646 */
1647 function jirafeau_is_writable($path)
1648 {
1649 /* "@" gets rid of error messages. */
1650 return is_writable($path) || @chmod($path, 0777);
1651 }
1652
1653 function jirafeau_check_var_dir($path)
1654 {
1655 $mkdir_str1 = t('CANNOT_CREATE_DIR') . ':';
1656 $mkdir_str2 = t('MANUAL_CREATE');
1657 $write_str1 = t('DIR_NOT_W') . ':';
1658 $write_str2 = t('You should give the write permission to the web server on ' .
1659 'this directory.');
1660 $solution_str = t('HERE_SOLUTION') . ':';
1661
1662 if (!jirafeau_mkdir($path) || !jirafeau_is_writable($path)) {
1663 return array('has_error' => true,
1664 'why' => $mkdir_str1 . '<br /><code>' .
1665 $path . '</code><br />' . $solution_str .
1666 '<br />' . $mkdir_str2);
1667 }
1668
1669 foreach (array('files', 'links', 'async') as $subdir) {
1670 $subpath = $path.$subdir;
1671
1672 if (!jirafeau_mkdir($subpath) || !jirafeau_is_writable($subpath)) {
1673 return array('has_error' => true,
1674 'why' => $mkdir_str1 . '<br /><code>' .
1675 $subpath . '</code><br />' . $solution_str .
1676 '<br />' . $mkdir_str2);
1677 }
1678 }
1679
1680 return array('has_error' => false, 'why' => '');
1681 }
1682
1683 function jirafeau_add_ending_slash($path)
1684 {
1685 return $path . ((substr($path, -1) == '/') ? '' : '/');
1686 }
1687
1688 function jirafeau_default_web_root()
1689 {
1690 $url_scheme = (isset($_SERVER['HTTPS'])) ? 'https://' : 'http://';
1691 return $url_scheme . $_SERVER['HTTP_HOST'] . str_replace('install.php', '', $_SERVER['REQUEST_URI']);
1692 }
1693
1694 function jirafeau_get_download_stats($hash)
1695 {
1696 $filename = VAR_LINKS . s2p("$hash") . $hash . '_download';
1697
1698 if (!file_exists($filename)) {
1699 return array('count'=>0);
1700 }
1701
1702 $c = file($filename);
1703 $data['count'] = trim($c[0]);
1704 $data['date'] = trim($c[1]);
1705 $data['ip'] = trim($c[2]);
1706
1707 return $data;
1708 }
1709
1710 function jirafeau_write_download_stats($hash, $ip)
1711 {
1712 $data = jirafeau_get_download_stats($hash);
1713 $count = $data['count'];
1714 $count++;
1715
1716 $filename = VAR_LINKS . s2p("$hash") . $hash . '_download';
1717
1718 $handle = fopen($filename, 'w');
1719 fwrite($handle, $count . NL . time() . NL . $ip);
1720 fclose($handle);
1721 }

patrick-canterino.de