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

patrick-canterino.de