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

patrick-canterino.de