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

patrick-canterino.de