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

patrick-canterino.de