]> git.p6c8.net - jirafeau_project.git/blob - lib/functions.php
[FIX] Better error handling with md5_outside
[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 <j.jutteau@gmail.com>
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 seperating each letters by a '/'.
24 * @return path finishing with a '/'
25 */
26 function s2p($s)
27 {
28 $block_size = 8;
29 $p = '';
30 for ($i = 0; $i < strlen($s); $i++) {
31 $p .= $s{$i};
32 if (($i + 1) % $block_size == 0) {
33 $p .= '/';
34 }
35 }
36 if (strlen($s) % $block_size != 0) {
37 $p .= '/';
38 }
39 return $p;
40 }
41
42 /**
43 * Convert base 16 to base 64
44 * @returns A string based on 64 characters (0-9, a-z, A-Z, "-" and "_")
45 */
46 function base_16_to_64($num)
47 {
48 $m = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_';
49 $hex2bin = array('0000', # 0
50 '0001', # 1
51 '0010', # 2
52 '0011', # 3
53 '0100', # 4
54 '0101', # 5
55 '0110', # 6
56 '0111', # 7
57 '1000', # 8
58 '1001', # 9
59 '1010', # a
60 '1011', # b
61 '1100', # c
62 '1101', # d
63 '1110', # e
64 '1111'); # f
65 $o = '';
66 $b = '';
67 $i = 0;
68 # Convert long hex string to bin.
69 $size = strlen($num);
70 for ($i = 0; $i < $size; $i++) {
71 $b .= $hex2bin{hexdec($num{$i})};
72 }
73 # Convert long bin to base 64.
74 $size *= 4;
75 for ($i = $size - 6; $i >= 0; $i -= 6) {
76 $o = $m{bindec(substr($b, $i, 6))} . $o;
77 }
78 # Some few bits remaining ?
79 if ($i < 0 && $i > -6) {
80 $o = $m{bindec(substr($b, 0, $i + 6))} . $o;
81 }
82 return $o;
83 }
84
85 /**
86 * Generate a random code.
87 * @param $l code length
88 * @return random code.
89 */
90 function jirafeau_gen_random($l)
91 {
92 if ($l <= 0) {
93 return 42;
94 }
95
96 $code="";
97 for ($i = 0; $i < $l; $i++) {
98 $code .= dechex(rand(0, 15));
99 }
100
101 return $code;
102 }
103
104 function is_ssl()
105 {
106 if (isset($_SERVER['HTTPS'])) {
107 if ('on' == strtolower($_SERVER['HTTPS']) ||
108 '1' == $_SERVER['HTTPS']) {
109 return true;
110 }
111 } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
112 return true;
113 } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
114 if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
115 return true;
116 }
117 }
118 return false;
119 }
120
121 function jirafeau_human_size($octets)
122 {
123 $u = array('B', 'KB', 'MB', 'GB', 'TB');
124 $o = max($octets, 0);
125 $p = min(floor(($o ? log($o) : 0) / log(1024)), count($u) - 1);
126 $o /= pow(1024, $p);
127 return round($o, 1) . $u[$p];
128 }
129
130 // Convert UTC timestamp to a datetime field
131 function jirafeau_get_datetimefield($timestamp)
132 {
133 $content = '<span class="datetime" data-datetime="' . strftime('%Y-%m-%d %H:%M', $timestamp) . '">'
134 . strftime('%Y-%m-%d %H:%M', $timestamp) . ' (GMT)</span>';
135 return $content;
136 }
137
138 function jirafeau_fatal_error($errorText, $cfg = array())
139 {
140 echo '<div class="error"><h2>Error</h2><p>' . $errorText . '</p></div>';
141 require(JIRAFEAU_ROOT . 'lib/template/footer.php');
142 exit;
143 }
144
145 function jirafeau_clean_rm_link($link)
146 {
147 $p = s2p("$link");
148 if (file_exists(VAR_LINKS . $p . $link)) {
149 unlink(VAR_LINKS . $p . $link);
150 }
151 $parse = VAR_LINKS . $p;
152 $scan = array();
153 while (file_exists($parse)
154 && ($scan = scandir($parse))
155 && count($scan) == 2 // '.' and '..' folders => empty.
156 && basename($parse) != basename(VAR_LINKS)) {
157 rmdir($parse);
158 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
159 }
160 }
161
162 function jirafeau_clean_rm_file($hash)
163 {
164 $p = s2p("$hash");
165 $f = VAR_FILES . $p . $hash;
166 if (file_exists($f) && is_file($f)) {
167 unlink($f);
168 }
169 if (file_exists($f . '_count') && is_file($f . '_count')) {
170 unlink($f . '_count');
171 }
172 $parse = VAR_FILES . $p;
173 $scan = array();
174 while (file_exists($parse)
175 && ($scan = scandir($parse))
176 && count($scan) == 2 // '.' and '..' folders => empty.
177 && basename($parse) != basename(VAR_FILES)) {
178 rmdir($parse);
179 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
180 }
181 }
182
183 /**
184 * transforms a php.ini string representing a value in an integer
185 * @param $value the value from php.ini
186 * @returns an integer for this value
187 */
188 function jirafeau_ini_to_bytes($value)
189 {
190 $modifier = substr($value, -1);
191 $bytes = substr($value, 0, -1);
192 switch (strtoupper($modifier)) {
193 case 'P':
194 $bytes *= 1024;
195 case 'T':
196 $bytes *= 1024;
197 case 'G':
198 $bytes *= 1024;
199 case 'M':
200 $bytes *= 1024;
201 case 'K':
202 $bytes *= 1024;
203 }
204 return $bytes;
205 }
206
207 /**
208 * gets the maximum upload size according to php.ini
209 * @returns the maximum upload size in bytes
210 */
211 function jirafeau_get_max_upload_size_bytes()
212 {
213 return min(jirafeau_ini_to_bytes(ini_get('post_max_size')),
214 jirafeau_ini_to_bytes(ini_get('upload_max_filesize')));
215 }
216
217 /**
218 * gets the maximum upload size according to php.ini
219 * @returns the maximum upload size string
220 */
221 function jirafeau_get_max_upload_size()
222 {
223 return jirafeau_human_size(jirafeau_get_max_upload_size_bytes());
224 }
225
226 /**
227 * gets a string explaining the error
228 * @param $code the error code
229 * @returns a string explaining the error
230 */
231 function jirafeau_upload_errstr($code)
232 {
233 switch ($code) {
234 case UPLOAD_ERR_INI_SIZE:
235 case UPLOAD_ERR_FORM_SIZE:
236 return t('Your file exceeds the maximum authorized file size. ');
237
238 case UPLOAD_ERR_PARTIAL:
239 case UPLOAD_ERR_NO_FILE:
240 return
241 t('Your file was not uploaded correctly. You may succeed in retrying. ');
242
243 case UPLOAD_ERR_NO_TMP_DIR:
244 case UPLOAD_ERR_CANT_WRITE:
245 case UPLOAD_ERR_EXTENSION:
246 return t('Internal error. You may not succeed in retrying. ');
247 }
248 return t('Unknown error. ');
249 }
250
251 /** Remove link and it's file
252 * @param $link the link's name (hash)
253 */
254
255 function jirafeau_delete_link($link)
256 {
257 $l = jirafeau_get_link($link);
258 if (!count($l)) {
259 return;
260 }
261
262 jirafeau_clean_rm_link($link);
263
264 $hash = $l['hash'];
265 $p = s2p("$hash");
266
267 $counter = 1;
268 if (file_exists(VAR_FILES . $p . $hash. '_count')) {
269 $content = file(VAR_FILES . $p . $hash. '_count');
270 $counter = trim($content[0]);
271 }
272 $counter--;
273
274 if ($counter >= 1) {
275 $handle = fopen(VAR_FILES . $p . $hash. '_count', 'w');
276 fwrite($handle, $counter);
277 fclose($handle);
278 }
279
280 if ($counter == 0) {
281 jirafeau_clean_rm_file($hash);
282 }
283 }
284
285 /**
286 * Delete a file and it's links.
287 */
288 function jirafeau_delete_file($hash)
289 {
290 $count = 0;
291 /* Get all links files. */
292 $stack = array(VAR_LINKS);
293 while (($d = array_shift($stack)) && $d != null) {
294 $dir = scandir($d);
295
296 foreach ($dir as $node) {
297 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
298 preg_match('/\.tmp/i', "$node")) {
299 continue;
300 }
301
302 if (is_dir($d . $node)) {
303 /* Push new found directory. */
304 $stack[] = $d . $node . '/';
305 } elseif (is_file($d . $node)) {
306 /* Read link informations. */
307 $l = jirafeau_get_link(basename($node));
308 if (!count($l)) {
309 continue;
310 }
311 if ($l['hash'] == $hash) {
312 $count++;
313 jirafeau_delete_link($node);
314 }
315 }
316 }
317 }
318 jirafeau_clean_rm_file($hash);
319 return $count;
320 }
321
322
323 /** hash file's content
324 * @param $method hash method, see 'file_hash' option. 'md5' or 'md5_outside'.
325 * @param $file_path file to hash
326 * @returns hash string
327 */
328 function jirafeau_hash_file($method, $file_path)
329 {
330 switch ($method) {
331 case 'md5_outside':
332 return jirafeau_md5_outside($file_path);
333 case 'md5':
334 return md5_file($file_path);
335 }
336 return md5_file($file_path);
337 }
338
339 /** hash part of file: start, end and size.
340 * This is a partial file hash, faster but weaker.
341 * @param $file_path file to hash
342 * @returns hash string
343 */
344 function jirafeau_md5_outside($file_path)
345 {
346 $out = false;
347 $handle = fopen($file_path, "r");
348 if ($handle === false) {
349 return false;
350 }
351 $size = filesize($file_path);
352 if ($size === false) {
353 goto err;
354 }
355 $first = fread($handle, 64);
356 if ($first === false) {
357 goto err;
358 }
359 if (fseek($handle, $size < 64 ? 0 : $size - 64) == -1) {
360 goto err;
361 }
362 $last = fread($handle, 64);
363 if ($last === false) {
364 goto err;
365 }
366 $out = md5($first . $last . $size);
367 err:
368 fclose($handle);
369 return $out;
370 }
371
372 /**
373 * handles an uploaded file
374 * @param $file the file struct given by $_FILE[]
375 * @param $one_time_download is the file a one time download ?
376 * @param $key if not empty, protect the file with this key
377 * @param $time the time of validity of the file
378 * @param $ip uploader's ip
379 * @param $crypt boolean asking to crypt or not
380 * @param $link_name_length size of the link name
381 * @returns an array containing some information
382 * 'error' => information on possible errors
383 * 'link' => the link name of the uploaded file
384 * 'delete_link' => the link code to delete file
385 */
386 function jirafeau_upload($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length, $file_hash_method)
387 {
388 if (empty($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
389 return (array(
390 'error' =>
391 array('has_error' => true,
392 'why' => jirafeau_upload_errstr($file['error'])),
393 'link' => '',
394 'delete_link' => ''));
395 }
396
397 /* array representing no error */
398 $noerr = array('has_error' => false, 'why' => '');
399
400 /* Crypt file if option is enabled. */
401 $crypted = false;
402 $crypt_key = '';
403 if ($crypt == true && !(extension_loaded('mcrypt') == true)) {
404 error_log("PHP extension mcrypt not loaded, won't encrypt in Jirafeau");
405 }
406 if ($crypt == true && extension_loaded('mcrypt') == true) {
407 $crypt_key = jirafeau_encrypt_file($file['tmp_name'], $file['tmp_name']);
408 if (strlen($crypt_key) > 0) {
409 $crypted = true;
410 }
411 }
412
413 /* file informations */
414 $hash = jirafeau_hash_file($file_hash_method, $file['tmp_name']);
415 $name = str_replace(NL, '', trim($file['name']));
416 $mime_type = $file['type'];
417 $size = $file['size'];
418
419 /* does file already exist ? */
420 $rc = false;
421 $p = s2p("$hash");
422 if (file_exists(VAR_FILES . $p . $hash)) {
423 $rc = unlink($file['tmp_name']);
424 } elseif ((file_exists(VAR_FILES . $p) || @mkdir(VAR_FILES . $p, 0755, true))
425 && move_uploaded_file($file['tmp_name'], VAR_FILES . $p . $hash)) {
426 $rc = true;
427 }
428 if (!$rc) {
429 return (array(
430 'error' =>
431 array('has_error' => true,
432 'why' => t('INTERNAL_ERROR_DEL')),
433 'link' =>'',
434 'delete_link' => ''));
435 }
436
437 /* Increment or create count file. */
438 $counter = 0;
439 if (file_exists(VAR_FILES . $p . $hash . '_count')) {
440 $content = file(VAR_FILES . $p . $hash. '_count');
441 $counter = trim($content[0]);
442 }
443 $counter++;
444 $handle = fopen(VAR_FILES . $p . $hash. '_count', 'w');
445 fwrite($handle, $counter);
446 fclose($handle);
447
448 /* Create delete code. */
449 $delete_link_code = jirafeau_gen_random(5);
450
451 /* hash password or empty. */
452 $password = '';
453 if (!empty($key)) {
454 $password = md5($key);
455 }
456
457 /* create link file */
458 $link_tmp_name = VAR_LINKS . $hash . rand(0, 10000) . '.tmp';
459 $handle = fopen($link_tmp_name, 'w');
460 fwrite($handle,
461 $name . NL. $mime_type . NL. $size . NL. $password . NL. $time .
462 NL . $hash. NL . ($one_time_download ? 'O' : 'R') . NL . time() .
463 NL . $ip . NL. $delete_link_code . NL . ($crypted ? 'C' : 'O'));
464 fclose($handle);
465 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
466 $l = s2p("$hash_link");
467 if (!@mkdir(VAR_LINKS . $l, 0755, true) ||
468 !rename($link_tmp_name, VAR_LINKS . $l . $hash_link)) {
469 if (file_exists($link_tmp_name)) {
470 unlink($link_tmp_name);
471 }
472
473 $counter--;
474 if ($counter >= 1) {
475 $handle = fopen(VAR_FILES . $p . $hash. '_count', 'w');
476 fwrite($handle, $counter);
477 fclose($handle);
478 } else {
479 jirafeau_clean_rm_file($hash_link);
480 }
481 return array(
482 'error' =>
483 array('has_error' => true,
484 'why' => t('Internal error during file creation. ')),
485 'link' =>'',
486 'delete_link' => '');
487 }
488 return array( 'error' => $noerr,
489 'link' => $hash_link,
490 'delete_link' => $delete_link_code,
491 'crypt_key' => $crypt_key);
492 }
493
494 /**
495 * Tells if a mime-type is viewable in a browser
496 * @param $mime the mime type
497 * @returns a boolean telling if a mime type is viewable
498 */
499 function jirafeau_is_viewable($mime)
500 {
501 if (!empty($mime)) {
502 /* Actually, verify if mime-type is an image or a text. */
503 $viewable = array('image', 'text', 'video', 'audio');
504 $decomposed = explode('/', $mime);
505 return in_array($decomposed[0], $viewable);
506 }
507 return false;
508 }
509
510 // Error handling functions.
511 //! Global array that contains all registered errors.
512 $error_list = array();
513
514 /**
515 * Adds an error to the list of errors.
516 * @param $title the error's title
517 * @param $description is a human-friendly description of the problem.
518 */
519 function add_error($title, $description)
520 {
521 global $error_list;
522 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
523 }
524
525 /**
526 * Informs whether any error has been registered yet.
527 * @return true if there are errors.
528 */
529 function has_error()
530 {
531 global $error_list;
532 return !empty($error_list);
533 }
534
535 /**
536 * Displays all the errors.
537 */
538 function show_errors()
539 {
540 if (has_error()) {
541 global $error_list;
542 echo '<div class="error">';
543 foreach ($error_list as $error) {
544 echo $error;
545 }
546 echo '</div>';
547 }
548 }
549
550 function check_errors($cfg)
551 {
552 if (file_exists(JIRAFEAU_ROOT . 'install.php')
553 && !($cfg['installation_done'] === true)) {
554 header('Location: install.php');
555 exit;
556 }
557
558 /* Checking for errors. */
559 if (!is_writable(VAR_FILES)) {
560 add_error(t('FILE_DIR_W'), VAR_FILES);
561 }
562
563 if (!is_writable(VAR_LINKS)) {
564 add_error(t('LINK_DIR_W'), VAR_LINKS);
565 }
566
567 if (!is_writable(VAR_ASYNC)) {
568 add_error(t('ASYNC_DIR_W'), VAR_ASYNC);
569 }
570 }
571
572 /**
573 * Read link informations
574 * @return array containing informations.
575 */
576 function jirafeau_get_link($hash)
577 {
578 $out = array();
579 $link = VAR_LINKS . s2p("$hash") . $hash;
580
581 if (!file_exists($link)) {
582 return $out;
583 }
584
585 $c = file($link);
586 $out['file_name'] = trim($c[0]);
587 $out['mime_type'] = trim($c[1]);
588 $out['file_size'] = trim($c[2]);
589 $out['key'] = trim($c[3], NL);
590 $out['time'] = trim($c[4]);
591 $out['hash'] = trim($c[5]);
592 $out['onetime'] = trim($c[6]);
593 $out['upload_date'] = trim($c[7]);
594 $out['ip'] = trim($c[8]);
595 $out['link_code'] = trim($c[9]);
596 $out['crypted'] = trim($c[10]) == 'C';
597
598 return $out;
599 }
600
601 /**
602 * List files in admin interface.
603 */
604 function jirafeau_admin_list($name, $file_hash, $link_hash)
605 {
606 echo '<fieldset><legend>';
607 if (!empty($name)) {
608 echo t('FILENAME') . ": " . jirafeau_escape($name);
609 }
610 if (!empty($file_hash)) {
611 echo t('FILE') . ": " . jirafeau_escape($file_hash);
612 }
613 if (!empty($link_hash)) {
614 echo t('LINK') . ": " . jirafeau_escape($link_hash);
615 }
616 if (empty($name) && empty($file_hash) && empty($link_hash)) {
617 echo t('LS_FILES');
618 }
619 echo '</legend>';
620 echo '<table border="1" width="1100">';
621 echo '<tr>';
622 echo '<th>' . t('FILENAME') . '</th>';
623 echo '<th>' . t('TYPE') . '</th>';
624 echo '<th>' . t('SIZE') . '</th>';
625 echo '<th>' . t('EXPIRE') . '</th>';
626 echo '<th>' . t('ONETIME') . '</th>';
627 echo '<th>' . t('UPLOAD_DATE') . '</th>';
628 echo '<th>' . t('ORIGIN') . '</th>';
629 echo '<th>' . t('ACTION') . '</th>';
630 echo '</tr>';
631
632 /* Get all links files. */
633 $stack = array(VAR_LINKS);
634 while (($d = array_shift($stack)) && $d != null) {
635 $dir = scandir($d);
636 foreach ($dir as $node) {
637 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
638 preg_match('/\.tmp/i', "$node")) {
639 continue;
640 }
641 if (is_dir($d . $node)) {
642 /* Push new found directory. */
643 $stack[] = $d . $node . '/';
644 } elseif (is_file($d . $node)) {
645 /* Read link informations. */
646 $l = jirafeau_get_link($node);
647 if (!count($l)) {
648 continue;
649 }
650
651 /* Filter. */
652 if (!empty($name) && !@preg_match("/$name/i", jirafeau_escape($l['file_name']))) {
653 continue;
654 }
655 if (!empty($file_hash) && $file_hash != $l['hash']) {
656 continue;
657 }
658 if (!empty($link_hash) && $link_hash != $node) {
659 continue;
660 }
661 /* Print link informations. */
662 echo '<tr>';
663 echo '<td>' .
664 '<strong><a id="upload_link" href="f.php?h='. jirafeau_escape($node) .'" title="' .
665 t('DL_PAGE') . '">' . jirafeau_escape($l['file_name']) . '</a></strong>';
666 echo '</td>';
667 echo '<td>' . jirafeau_escape($l['mime_type']) . '</td>';
668 echo '<td>' . jirafeau_human_size($l['file_size']) . '</td>';
669 echo '<td>' . ($l['time'] == -1 ? '∞' : jirafeau_get_datetimefield($l['time'])) . '</td>';
670 echo '<td>';
671 if ($l['onetime'] == 'O') {
672 echo 'Y';
673 } else {
674 echo 'N';
675 }
676 echo '</td>';
677 echo '<td>' . jirafeau_get_datetimefield($l['upload_date']) . '</td>';
678 echo '<td>' . $l['ip'] . '</td>';
679 echo '<td>' .
680 '<form method="post">' .
681 '<input type = "hidden" name = "action" value = "download"/>' .
682 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
683 jirafeau_admin_csrf_field() .
684 '<input type = "submit" value = "' . t('DL') . '" />' .
685 '</form>' .
686 '<form method="post">' .
687 '<input type = "hidden" name = "action" value = "delete_link"/>' .
688 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
689 jirafeau_admin_csrf_field() .
690 '<input type = "submit" value = "' . t('DEL_LINK') . '" />' .
691 '</form>' .
692 '<form method="post">' .
693 '<input type = "hidden" name = "action" value = "delete_file"/>' .
694 '<input type = "hidden" name = "hash" value = "' . $l['hash'] . '"/>' .
695 jirafeau_admin_csrf_field() .
696 '<input type = "submit" value = "' . t('DEL_FILE_LINKS') . '" />' .
697 '</form>' .
698 '</td>';
699 echo '</tr>';
700 }
701 }
702 }
703 echo '</table></fieldset>';
704 }
705
706 /**
707 * Clean expired files.
708 * @return number of cleaned files.
709 */
710 function jirafeau_admin_clean()
711 {
712 $count = 0;
713 /* Get all links files. */
714 $stack = array(VAR_LINKS);
715 while (($d = array_shift($stack)) && $d != null) {
716 $dir = scandir($d);
717
718 foreach ($dir as $node) {
719 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
720 preg_match('/\.tmp/i', "$node")) {
721 continue;
722 }
723
724 if (is_dir($d . $node)) {
725 /* Push new found directory. */
726 $stack[] = $d . $node . '/';
727 } elseif (is_file($d . $node)) {
728 /* Read link informations. */
729 $l = jirafeau_get_link(basename($node));
730 if (!count($l)) {
731 continue;
732 }
733 $p = s2p($l['hash']);
734 if ($l['time'] > 0 && $l['time'] < time() || // expired
735 !file_exists(VAR_FILES . $p . $l['hash']) || // invalid
736 !file_exists(VAR_FILES . $p . $l['hash'] . '_count')) { // invalid
737 jirafeau_delete_link($node);
738 $count++;
739 }
740 }
741 }
742 }
743 return $count;
744 }
745
746
747 /**
748 * Clean old async transferts.
749 * @return number of cleaned files.
750 */
751 function jirafeau_admin_clean_async()
752 {
753 $count = 0;
754 /* Get all links files. */
755 $stack = array(VAR_ASYNC);
756 while (($d = array_shift($stack)) && $d != null) {
757 $dir = scandir($d);
758
759 foreach ($dir as $node) {
760 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
761 preg_match('/\.tmp/i', "$node")) {
762 continue;
763 }
764
765 if (is_dir($d . $node)) {
766 /* Push new found directory. */
767 $stack[] = $d . $node . '/';
768 } elseif (is_file($d . $node)) {
769 /* Read async informations. */
770 $a = jirafeau_get_async_ref(basename($node));
771 if (!count($a)) {
772 continue;
773 }
774 /* Delete transferts older than 1 hour. */
775 if (time() - $a['last_edited'] > 3600) {
776 jirafeau_async_delete(basename($node));
777 $count++;
778 }
779 }
780 }
781 }
782 return $count;
783 }
784 /**
785 * Read async transfert informations
786 * @return array containing informations.
787 */
788 function jirafeau_get_async_ref($ref)
789 {
790 $out = array();
791 $refinfos = VAR_ASYNC . s2p("$ref") . "$ref";
792
793 if (!file_exists($refinfos)) {
794 return $out;
795 }
796
797 $c = file($refinfos);
798 $out['file_name'] = trim($c[0]);
799 $out['mime_type'] = trim($c[1]);
800 $out['key'] = trim($c[2], NL);
801 $out['time'] = trim($c[3]);
802 $out['onetime'] = trim($c[4]);
803 $out['ip'] = trim($c[5]);
804 $out['last_edited'] = trim($c[6]);
805 $out['next_code'] = trim($c[7]);
806 return $out;
807 }
808
809 /**
810 * Delete async transfert informations
811 */
812 function jirafeau_async_delete($ref)
813 {
814 $p = s2p("$ref");
815 if (file_exists(VAR_ASYNC . $p . $ref)) {
816 unlink(VAR_ASYNC . $p . $ref);
817 }
818 if (file_exists(VAR_ASYNC . $p . $ref . '_data')) {
819 unlink(VAR_ASYNC . $p . $ref . '_data');
820 }
821 $parse = VAR_ASYNC . $p;
822 $scan = array();
823 while (file_exists($parse)
824 && ($scan = scandir($parse))
825 && count($scan) == 2 // '.' and '..' folders => empty.
826 && basename($parse) != basename(VAR_ASYNC)) {
827 rmdir($parse);
828 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
829 }
830 }
831
832 /**
833 * Init a new asynchronous upload.
834 * @param $finename Name of the file to send
835 * @param $one_time One time upload parameter
836 * @param $key eventual password (or blank)
837 * @param $time time limit
838 * @param $ip ip address of the client
839 * @return a string containing a temporary reference followed by a code or the string 'Error'
840 */
841 function jirafeau_async_init($filename, $type, $one_time, $key, $time, $ip)
842 {
843 $res = 'Error';
844
845 /* Create temporary folder. */
846 $ref;
847 $p;
848 $code = jirafeau_gen_random(4);
849 do {
850 $ref = jirafeau_gen_random(32);
851 $p = VAR_ASYNC . s2p($ref);
852 } while (file_exists($p));
853 @mkdir($p, 0755, true);
854 if (!file_exists($p)) {
855 echo 'Error';
856 return;
857 }
858
859 /* md5 password or empty */
860 $password = '';
861 if (!empty($key)) {
862 $password = md5($key);
863 }
864
865 /* Store informations. */
866 $p .= $ref;
867 $handle = fopen($p, 'w');
868 fwrite($handle,
869 str_replace(NL, '', trim($filename)) . NL .
870 str_replace(NL, '', trim($type)) . NL . $password . NL .
871 $time . NL . ($one_time ? 'O' : 'R') . NL . $ip . NL .
872 time() . NL . $code . NL);
873 fclose($handle);
874
875 return $ref . NL . $code ;
876 }
877
878 /**
879 * Append a piece of file on the asynchronous upload.
880 * @param $ref asynchronous upload reference
881 * @param $file piece of data
882 * @param $code client code for this operation
883 * @param $max_file_size maximum allowed file size
884 * @return a string containing a next code to use or the string "Error"
885 */
886 function jirafeau_async_push($ref, $data, $code, $max_file_size)
887 {
888 /* Get async infos. */
889 $a = jirafeau_get_async_ref($ref);
890
891 /* Check some errors. */
892 if (count($a) == 0
893 || $a['next_code'] != "$code"
894 || empty($data['tmp_name'])
895 || !is_uploaded_file($data['tmp_name'])) {
896 return 'Error';
897 }
898
899 $p = s2p($ref);
900
901 /* File path. */
902 $r_path = $data['tmp_name'];
903 $w_path = VAR_ASYNC . $p . $ref . '_data';
904
905 /* Check that file size is not above upload limit. */
906 if ($max_file_size > 0 &&
907 filesize($r_path) + filesize($w_path) > $max_file_size * 1024 * 1024) {
908 jirafeau_async_delete($ref);
909 return 'Error';
910 }
911
912 /* Concatenate data. */
913 $r = fopen($r_path, 'r');
914 $w = fopen($w_path, 'a');
915 while (!feof($r)) {
916 if (fwrite($w, fread($r, 1024)) === false) {
917 fclose($r);
918 fclose($w);
919 jirafeau_async_delete($ref);
920 return 'Error';
921 }
922 }
923 fclose($r);
924 fclose($w);
925 unlink($r_path);
926
927 /* Update async file. */
928 $code = jirafeau_gen_random(4);
929 $handle = fopen(VAR_ASYNC . $p . $ref, 'w');
930 fwrite($handle,
931 $a['file_name'] . NL. $a['mime_type'] . NL. $a['key'] . NL .
932 $a['time'] . NL . $a['onetime'] . NL . $a['ip'] . NL .
933 time() . NL . $code . NL);
934 fclose($handle);
935 return $code;
936 }
937
938 /**
939 * Finalyze an asynchronous upload.
940 * @param $ref asynchronous upload reference
941 * @param $code client code for this operation
942 * @param $crypt boolean asking to crypt or not
943 * @param $link_name_length link name length
944 * @return a string containing the download reference followed by a delete code or the string 'Error'
945 */
946 function jirafeau_async_end($ref, $code, $crypt, $link_name_length, $file_hash_method)
947 {
948 /* Get async infos. */
949 $a = jirafeau_get_async_ref($ref);
950 if (count($a) == 0
951 || $a['next_code'] != "$code") {
952 return "Error";
953 }
954
955 /* Generate link infos. */
956 $p = VAR_ASYNC . s2p($ref) . $ref . "_data";
957 if (!file_exists($p)) {
958 return 'Error';
959 }
960
961 $crypted = false;
962 $crypt_key = '';
963 if ($crypt == true && extension_loaded('mcrypt') == true) {
964 $crypt_key = jirafeau_encrypt_file($p, $p);
965 if (strlen($crypt_key) > 0) {
966 $crypted = true;
967 }
968 }
969
970 $hash = jirafeau_hash_file($file_hash_method, $p);
971 $size = filesize($p);
972 $np = s2p($hash);
973 $delete_link_code = jirafeau_gen_random(5);
974
975 /* File already exist ? */
976 if (!file_exists(VAR_FILES . $np)) {
977 @mkdir(VAR_FILES . $np, 0755, true);
978 }
979 if (!file_exists(VAR_FILES . $np . $hash)) {
980 rename($p, VAR_FILES . $np . $hash);
981 }
982
983 /* Increment or create count file. */
984 $counter = 0;
985 if (file_exists(VAR_FILES . $np . $hash . '_count')) {
986 $content = file(VAR_FILES . $np . $hash. '_count');
987 $counter = trim($content[0]);
988 }
989 $counter++;
990 $handle = fopen(VAR_FILES . $np . $hash. '_count', 'w');
991 fwrite($handle, $counter);
992 fclose($handle);
993
994 /* Create link. */
995 $link_tmp_name = VAR_LINKS . $hash . rand(0, 10000) . '.tmp';
996 $handle = fopen($link_tmp_name, 'w');
997 fwrite($handle,
998 $a['file_name'] . NL . $a['mime_type'] . NL . $size . NL .
999 $a['key'] . NL . $a['time'] . NL . $hash . NL . $a['onetime'] . NL .
1000 time() . NL . $a['ip'] . NL . $delete_link_code . NL . ($crypted ? 'C' : 'O'));
1001 fclose($handle);
1002 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
1003 $l = s2p("$hash_link");
1004 if (!@mkdir(VAR_LINKS . $l, 0755, true) ||
1005 !rename($link_tmp_name, VAR_LINKS . $l . $hash_link)) {
1006 echo "Error";
1007 }
1008
1009 /* Clean async upload. */
1010 jirafeau_async_delete($ref);
1011 return $hash_link . NL . $delete_link_code . NL . urlencode($crypt_key);
1012 }
1013
1014 function jirafeau_crypt_create_iv($base, $size)
1015 {
1016 $iv = '';
1017 while (strlen($iv) < $size) {
1018 $iv = $iv . $base;
1019 }
1020 $iv = substr($iv, 0, $size);
1021 return $iv;
1022 }
1023
1024 /**
1025 * Crypt file and returns decrypt key.
1026 * @param $fp_src file path to the file to crypt.
1027 * @param $fp_dst file path to the file to write crypted file (could be the same).
1028 * @return decrypt key composed of the key and the iv separated by a point ('.')
1029 */
1030 function jirafeau_encrypt_file($fp_src, $fp_dst)
1031 {
1032 $fs = filesize($fp_src);
1033 if ($fs === false || $fs == 0 || !(extension_loaded('mcrypt') == true)) {
1034 return '';
1035 }
1036
1037 /* Prepare module. */
1038 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1039 /* Generate key. */
1040 $crypt_key = jirafeau_gen_random(10);
1041 $hash_key = md5($crypt_key);
1042 $iv = jirafeau_crypt_create_iv($hash_key, mcrypt_enc_get_iv_size($m));
1043 /* Init module. */
1044 mcrypt_generic_init($m, $hash_key, $iv);
1045 /* Crypt file. */
1046 $r = fopen($fp_src, 'r');
1047 $w = fopen($fp_dst, 'c');
1048 while (!feof($r)) {
1049 $enc = mcrypt_generic($m, fread($r, 1024));
1050 if (fwrite($w, $enc) === false) {
1051 return '';
1052 }
1053 }
1054 fclose($r);
1055 fclose($w);
1056 /* Cleanup. */
1057 mcrypt_generic_deinit($m);
1058 mcrypt_module_close($m);
1059 return $crypt_key;
1060 }
1061
1062 /**
1063 * Decrypt file.
1064 * @param $fp_src file path to the file to decrypt.
1065 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1066 * @param $k string composed of the key and the iv separated by a point ('.')
1067 * @return key used to decrypt. a string of length 0 is returned if failed.
1068 */
1069 function jirafeau_decrypt_file($fp_src, $fp_dst, $k)
1070 {
1071 $fs = filesize($fp_src);
1072 if ($fs === false || $fs == 0 || extension_loaded('mcrypt') == false) {
1073 return false;
1074 }
1075
1076 /* Init module */
1077 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1078 /* Extract key and iv. */
1079 $crypt_key = $k;
1080 $hash_key = md5($crypt_key);
1081 $iv = jirafeau_crypt_create_iv($hash_key, mcrypt_enc_get_iv_size($m));
1082 /* Decrypt file. */
1083 $r = fopen($fp_src, 'r');
1084 $w = fopen($fp_dst, 'c');
1085 while (!feof($r)) {
1086 $dec = mdecrypt_generic($m, fread($r, 1024));
1087 if (fwrite($w, $dec) === false) {
1088 return false;
1089 }
1090 }
1091 fclose($r);
1092 fclose($w);
1093 /* Cleanup. */
1094 mcrypt_generic_deinit($m);
1095 mcrypt_module_close($m);
1096 return true;
1097 }
1098
1099 /**
1100 * Check if Jirafeau is password protected for visitors.
1101 * @return true if Jirafeau is password protected, false otherwise.
1102 */
1103 function jirafeau_has_upload_password($cfg)
1104 {
1105 return count($cfg['upload_password']) > 0;
1106 }
1107
1108 /**
1109 * Challenge password for a visitor.
1110 * @param $password password to be challenged
1111 * @return true if password is valid, false otherwise.
1112 */
1113 function jirafeau_challenge_upload_password($cfg, $password)
1114 {
1115 if (!jirafeau_has_upload_password($cfg)) {
1116 return false;
1117 }
1118 foreach ($cfg['upload_password'] as $p) {
1119 if ($password == $p) {
1120 return true;
1121 }
1122 }
1123 return false;
1124 }
1125
1126 /**
1127 * Test if the given IP is whitelisted by the given list.
1128 *
1129 * @param $allowedIpList array of allowed IPs
1130 * @param $challengedIp IP to be challenged
1131 * @return true if IP is authorized, false otherwise.
1132 */
1133 function jirafeau_challenge_ip($allowedIpList, $challengedIp)
1134 {
1135 foreach ($allowedIpList as $i) {
1136 if ($i == $challengedIp) {
1137 return true;
1138 }
1139 // CIDR test for IPv4 only.
1140 if (strpos($i, '/') !== false) {
1141 list($subnet, $mask) = explode('/', $i);
1142 if ((ip2long($challengedIp) & ~((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
1143 return true;
1144 }
1145 }
1146 }
1147 return false;
1148 }
1149
1150 /**
1151 * Check if Jirafeau has a restriction on the IP address for uploading.
1152 * @return true if uploading is IP restricted, false otherwise.
1153 */
1154 function jirafeau_upload_has_ip_restriction($cfg) {
1155 return count($cfg['upload_ip']) > 0;
1156 }
1157
1158 /**
1159 * Test if visitor's IP is authorized to upload at all.
1160 *
1161 * @param $cfg configuration
1162 * @param $challengedIp IP to be challenged
1163 * @return true if IP is authorized, false otherwise.
1164 */
1165 function jirafeau_challenge_upload_ip($cfg, $challengedIp)
1166 {
1167 // If no IP address have been listed, allow upload from any IP
1168 if (!jirafeau_upload_has_ip_restriction($cfg)) {
1169 return true;
1170 }
1171 return jirafeau_challenge_ip($cfg['upload_ip'], $challengedIp);
1172 }
1173
1174 /**
1175 * Test if visitor's IP is authorized to upload without a password.
1176 *
1177 * @param $cfg configuration
1178 * @param $challengedIp IP to be challenged
1179 * @return true if IP is authorized, false otherwise.
1180 */
1181 function jirafeau_challenge_upload_ip_without_password($cfg, $challengedIp)
1182 {
1183 return jirafeau_challenge_ip($cfg['upload_ip_nopassword'], $challengedIp);
1184 }
1185
1186 /**
1187 * Test if visitor's IP is authorized or password is supplied and authorized
1188 * @param $ip IP to be challenged
1189 * @param $password password to be challenged
1190 * @return true if access is valid, false otherwise.
1191 */
1192 function jirafeau_challenge_upload ($cfg, $ip, $password)
1193 {
1194 return jirafeau_challenge_upload_ip_without_password($cfg, $ip) ||
1195 (!jirafeau_has_upload_password($cfg) && !jirafeau_upload_has_ip_restriction($cfg)) ||
1196 (jirafeau_challenge_upload_password($cfg, $password) && jirafeau_challenge_upload_ip($cfg, $ip));
1197 }
1198
1199 /** Tell if we have some HTTP headers generated by a proxy */
1200 function has_http_forwarded()
1201 {
1202 return
1203 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1204 !empty($_SERVER['http_X_forwarded_for']);
1205 }
1206
1207 /**
1208 * Generate IP list from HTTP headers generated by a proxy
1209 * @return array of IP strings
1210 */
1211 function get_ip_list_http_forwarded()
1212 {
1213 $ip_list = array();
1214 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1215 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1216 if ($l === false) {
1217 return array();
1218 }
1219 foreach ($l as $ip) {
1220 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1221 }
1222 }
1223 if (!empty($_SERVER['http_X_forwarded_for'])) {
1224 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1225 foreach ($l as $ip) {
1226 // Separate IP from port
1227 $ipa = explode(':', $ip);
1228 if ($ipa === false) {
1229 continue;
1230 }
1231 $ip = $ipa[0];
1232 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1233 }
1234 }
1235 return $ip_list;
1236 }
1237
1238 /**
1239 * Get the ip address of the client from REMOTE_ADDR
1240 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1241 * @returns the client ip address
1242 */
1243 function get_ip_address($cfg)
1244 {
1245 $remote = $_SERVER['REMOTE_ADDR'];
1246 if (count($cfg['proxy_ip']) == 0 || !has_http_forwarded()) {
1247 return $remote;
1248 }
1249
1250 $ip_list = get_ip_list_http_forwarded();
1251 if (count($ip_list) == 0) {
1252 return $remote;
1253 }
1254
1255 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1256 if ($remote != $proxy_ip) {
1257 continue;
1258 }
1259 // Take the last IP (the one which has been set by the defined proxy).
1260 return end($ip_list);
1261 }
1262 return $remote;
1263 }
1264
1265 /**
1266 * Convert hexadecimal string to base64
1267 */
1268 function hex_to_base64($hex)
1269 {
1270 $b = '';
1271 foreach (str_split($hex, 2) as $pair) {
1272 $b .= chr(hexdec($pair));
1273 }
1274 return base64_encode($b);
1275 }
1276
1277 /**
1278 * Replace markers in templates.
1279 *
1280 * Available markers have the scheme "###MARKERNAME###".
1281 *
1282 * @param $content string Template text with markers
1283 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1284 * @return Template with replaced markers
1285 */
1286 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1287 {
1288 $patterns = array(
1289 '/###ORGANISATION###/',
1290 '/###CONTACTPERSON###/',
1291 '/###WEBROOT###/'
1292 );
1293 $replacements = array(
1294 $GLOBALS['cfg']['organisation'],
1295 $GLOBALS['cfg']['contactperson'],
1296 $GLOBALS['cfg']['web_root']
1297 );
1298 $content = preg_replace($patterns, $replacements, $content);
1299
1300 if (true === $htmllinebreaks) {
1301 $content = nl2br($content);
1302 }
1303
1304 return $content;
1305 }
1306
1307 function jirafeau_escape($string)
1308 {
1309 return htmlspecialchars($string, ENT_QUOTES);
1310 }
1311
1312 function jirafeau_admin_session_start()
1313 {
1314 $_SESSION['admin_auth'] = true;
1315 $_SESSION['admin_csrf'] = md5(uniqid(mt_rand(), true));
1316 }
1317
1318 function jirafeau_admin_session_end()
1319 {
1320 $_SESSION = array();
1321 session_destroy();
1322 }
1323
1324 function jirafeau_admin_session_logged()
1325 {
1326 return isset($_SESSION['admin_auth']) &&
1327 isset($_SESSION['admin_csrf']) &&
1328 isset($_POST['admin_csrf']) &&
1329 $_SESSION['admin_auth'] === true &&
1330 $_SESSION['admin_csrf'] === $_POST['admin_csrf'];
1331 }
1332
1333 function jirafeau_admin_csrf_field()
1334 {
1335 return "<input type='hidden' name='admin_csrf' value='". $_SESSION['admin_csrf'] . "'/>";
1336 }

patrick-canterino.de