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

patrick-canterino.de