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

patrick-canterino.de