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

patrick-canterino.de