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

patrick-canterino.de