]> git.p6c8.net - jirafeau.git/blob - lib/functions.php
4e227967475973466a0c186fcbf616aeeaecf559
[jirafeau.git] / lib / functions.php
1 <?php
2 /*
3 * Jirafeau, your web file repository
4 * Copyright (C) 2008 Julien "axolotl" BERNARD <axolotl@magieeternelle.org>
5 * Copyright (C) 2015 Jerome Jutteau <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 $size = filesize($file_path);
347 if ($size === false) {
348 $size = 0;
349 }
350 $handle = fopen($file_path, "r");
351 if ($handle === false) {
352 return false;
353 }
354 $first = fread($handle, 64);
355 if ($first === false) {
356 return false;
357 }
358 fseek($handle, $size < 64 ? 0 : $size - 64);
359 $last = fread($handle, 64);
360 fclose($handle);
361 return md5($first . $last . $size);
362 }
363
364 /**
365 * handles an uploaded file
366 * @param $file the file struct given by $_FILE[]
367 * @param $one_time_download is the file a one time download ?
368 * @param $key if not empty, protect the file with this key
369 * @param $time the time of validity of the file
370 * @param $ip uploader's ip
371 * @param $crypt boolean asking to crypt or not
372 * @param $link_name_length size of the link name
373 * @returns an array containing some information
374 * 'error' => information on possible errors
375 * 'link' => the link name of the uploaded file
376 * 'delete_link' => the link code to delete file
377 */
378 function jirafeau_upload($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length, $file_hash_method)
379 {
380 if (empty($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
381 return (array(
382 'error' =>
383 array('has_error' => true,
384 'why' => jirafeau_upload_errstr($file['error'])),
385 'link' => '',
386 'delete_link' => ''));
387 }
388
389 /* array representing no error */
390 $noerr = array('has_error' => false, 'why' => '');
391
392 /* Crypt file if option is enabled. */
393 $crypted = false;
394 $crypt_key = '';
395 if ($crypt == true && !(extension_loaded('mcrypt') == true)) {
396 error_log("PHP extension mcrypt not loaded, won't encrypt in Jirafeau");
397 }
398 if ($crypt == true && extension_loaded('mcrypt') == true) {
399 $crypt_key = jirafeau_encrypt_file($file['tmp_name'], $file['tmp_name']);
400 if (strlen($crypt_key) > 0) {
401 $crypted = true;
402 }
403 }
404
405 /* file informations */
406 $hash = jirafeau_hash_file($file_hash_method, $file['tmp_name']);
407 $name = str_replace(NL, '', trim($file['name']));
408 $mime_type = $file['type'];
409 $size = $file['size'];
410
411 /* does file already exist ? */
412 $rc = false;
413 $p = s2p("$hash");
414 if (file_exists(VAR_FILES . $p . $hash)) {
415 $rc = unlink($file['tmp_name']);
416 } elseif ((file_exists(VAR_FILES . $p) || @mkdir(VAR_FILES . $p, 0755, true))
417 && move_uploaded_file($file['tmp_name'], VAR_FILES . $p . $hash)) {
418 $rc = true;
419 }
420 if (!$rc) {
421 return (array(
422 'error' =>
423 array('has_error' => true,
424 'why' => t('INTERNAL_ERROR_DEL')),
425 'link' =>'',
426 'delete_link' => ''));
427 }
428
429 /* Increment or create count file. */
430 $counter = 0;
431 if (file_exists(VAR_FILES . $p . $hash . '_count')) {
432 $content = file(VAR_FILES . $p . $hash. '_count');
433 $counter = trim($content[0]);
434 }
435 $counter++;
436 $handle = fopen(VAR_FILES . $p . $hash. '_count', 'w');
437 fwrite($handle, $counter);
438 fclose($handle);
439
440 /* Create delete code. */
441 $delete_link_code = jirafeau_gen_random(5);
442
443 /* hash password or empty. */
444 $password = '';
445 if (!empty($key)) {
446 $password = md5($key);
447 }
448
449 /* create link file */
450 $link_tmp_name = VAR_LINKS . $hash . rand(0, 10000) . '.tmp';
451 $handle = fopen($link_tmp_name, 'w');
452 fwrite($handle,
453 $name . NL. $mime_type . NL. $size . NL. $password . NL. $time .
454 NL . $hash. NL . ($one_time_download ? 'O' : 'R') . NL . time() .
455 NL . $ip . NL. $delete_link_code . NL . ($crypted ? 'C' : 'O'));
456 fclose($handle);
457 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
458 $l = s2p("$hash_link");
459 if (!@mkdir(VAR_LINKS . $l, 0755, true) ||
460 !rename($link_tmp_name, VAR_LINKS . $l . $hash_link)) {
461 if (file_exists($link_tmp_name)) {
462 unlink($link_tmp_name);
463 }
464
465 $counter--;
466 if ($counter >= 1) {
467 $handle = fopen(VAR_FILES . $p . $hash. '_count', 'w');
468 fwrite($handle, $counter);
469 fclose($handle);
470 } else {
471 jirafeau_clean_rm_file($hash_link);
472 }
473 return array(
474 'error' =>
475 array('has_error' => true,
476 'why' => t('Internal error during file creation. ')),
477 'link' =>'',
478 'delete_link' => '');
479 }
480 return array( 'error' => $noerr,
481 'link' => $hash_link,
482 'delete_link' => $delete_link_code,
483 'crypt_key' => $crypt_key);
484 }
485
486 /**
487 * Tells if a mime-type is viewable in a browser
488 * @param $mime the mime type
489 * @returns a boolean telling if a mime type is viewable
490 */
491 function jirafeau_is_viewable($mime)
492 {
493 if (!empty($mime)) {
494 /* Actually, verify if mime-type is an image or a text. */
495 $viewable = array('image', 'text', 'video', 'audio');
496 $decomposed = explode('/', $mime);
497 return in_array($decomposed[0], $viewable);
498 }
499 return false;
500 }
501
502 // Error handling functions.
503 //! Global array that contains all registered errors.
504 $error_list = array();
505
506 /**
507 * Adds an error to the list of errors.
508 * @param $title the error's title
509 * @param $description is a human-friendly description of the problem.
510 */
511 function add_error($title, $description)
512 {
513 global $error_list;
514 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
515 }
516
517 /**
518 * Informs whether any error has been registered yet.
519 * @return true if there are errors.
520 */
521 function has_error()
522 {
523 global $error_list;
524 return !empty($error_list);
525 }
526
527 /**
528 * Displays all the errors.
529 */
530 function show_errors()
531 {
532 if (has_error()) {
533 global $error_list;
534 echo '<div class="error">';
535 foreach ($error_list as $error) {
536 echo $error;
537 }
538 echo '</div>';
539 }
540 }
541
542 function check_errors($cfg)
543 {
544 if (file_exists(JIRAFEAU_ROOT . 'install.php')
545 && !($cfg['installation_done'] === true)) {
546 header('Location: install.php');
547 exit;
548 }
549
550 /* Checking for errors. */
551 if (!is_writable(VAR_FILES)) {
552 add_error(t('FILE_DIR_W'), VAR_FILES);
553 }
554
555 if (!is_writable(VAR_LINKS)) {
556 add_error(t('LINK_DIR_W'), VAR_LINKS);
557 }
558
559 if (!is_writable(VAR_ASYNC)) {
560 add_error(t('ASYNC_DIR_W'), VAR_ASYNC);
561 }
562 }
563
564 /**
565 * Read link informations
566 * @return array containing informations.
567 */
568 function jirafeau_get_link($hash)
569 {
570 $out = array();
571 $link = VAR_LINKS . s2p("$hash") . $hash;
572
573 if (!file_exists($link)) {
574 return $out;
575 }
576
577 $c = file($link);
578 $out['file_name'] = trim($c[0]);
579 $out['mime_type'] = trim($c[1]);
580 $out['file_size'] = trim($c[2]);
581 $out['key'] = trim($c[3], NL);
582 $out['time'] = trim($c[4]);
583 $out['hash'] = trim($c[5]);
584 $out['onetime'] = trim($c[6]);
585 $out['upload_date'] = trim($c[7]);
586 $out['ip'] = trim($c[8]);
587 $out['link_code'] = trim($c[9]);
588 $out['crypted'] = trim($c[10]) == 'C';
589
590 return $out;
591 }
592
593 /**
594 * List files in admin interface.
595 */
596 function jirafeau_admin_list($name, $file_hash, $link_hash)
597 {
598 echo '<fieldset><legend>';
599 if (!empty($name)) {
600 echo t('FILENAME') . ": " . jirafeau_escape($name);
601 }
602 if (!empty($file_hash)) {
603 echo t('FILE') . ": " . jirafeau_escape($file_hash);
604 }
605 if (!empty($link_hash)) {
606 echo t('LINK') . ": " . jirafeau_escape($link_hash);
607 }
608 if (empty($name) && empty($file_hash) && empty($link_hash)) {
609 echo t('LS_FILES');
610 }
611 echo '</legend>';
612 echo '<table border="1" width="1100">';
613 echo '<tr>';
614 echo '<th>' . t('FILENAME') . '</th>';
615 echo '<th>' . t('TYPE') . '</th>';
616 echo '<th>' . t('SIZE') . '</th>';
617 echo '<th>' . t('EXPIRE') . '</th>';
618 echo '<th>' . t('ONETIME') . '</th>';
619 echo '<th>' . t('UPLOAD_DATE') . '</th>';
620 echo '<th>' . t('ORIGIN') . '</th>';
621 echo '<th>' . t('ACTION') . '</th>';
622 echo '</tr>';
623
624 /* Get all links files. */
625 $stack = array(VAR_LINKS);
626 while (($d = array_shift($stack)) && $d != null) {
627 $dir = scandir($d);
628 foreach ($dir as $node) {
629 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
630 preg_match('/\.tmp/i', "$node")) {
631 continue;
632 }
633 if (is_dir($d . $node)) {
634 /* Push new found directory. */
635 $stack[] = $d . $node . '/';
636 } elseif (is_file($d . $node)) {
637 /* Read link informations. */
638 $l = jirafeau_get_link($node);
639 if (!count($l)) {
640 continue;
641 }
642
643 /* Filter. */
644 if (!empty($name) && !@preg_match("/$name/i", jirafeau_escape($l['file_name']))) {
645 continue;
646 }
647 if (!empty($file_hash) && $file_hash != $l['hash']) {
648 continue;
649 }
650 if (!empty($link_hash) && $link_hash != $node) {
651 continue;
652 }
653 /* Print link informations. */
654 echo '<tr>';
655 echo '<td>' .
656 '<strong><a id="upload_link" href="f.php?h='. jirafeau_escape($node) .'" title="' .
657 t('DL_PAGE') . '">' . jirafeau_escape($l['file_name']) . '</a></strong>';
658 echo '</td>';
659 echo '<td>' . jirafeau_escape($l['mime_type']) . '</td>';
660 echo '<td>' . jirafeau_human_size($l['file_size']) . '</td>';
661 echo '<td>' . ($l['time'] == -1 ? '∞' : jirafeau_get_datetimefield($l['time'])) . '</td>';
662 echo '<td>';
663 if ($l['onetime'] == 'O') {
664 echo 'Y';
665 } else {
666 echo 'N';
667 }
668 echo '</td>';
669 echo '<td>' . jirafeau_get_datetimefield($l['upload_date']) . '</td>';
670 echo '<td>' . $l['ip'] . '</td>';
671 echo '<td>' .
672 '<form method="post">' .
673 '<input type = "hidden" name = "action" value = "download"/>' .
674 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
675 jirafeau_admin_csrf_field() .
676 '<input type = "submit" value = "' . t('DL') . '" />' .
677 '</form>' .
678 '<form method="post">' .
679 '<input type = "hidden" name = "action" value = "delete_link"/>' .
680 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
681 jirafeau_admin_csrf_field() .
682 '<input type = "submit" value = "' . t('DEL_LINK') . '" />' .
683 '</form>' .
684 '<form method="post">' .
685 '<input type = "hidden" name = "action" value = "delete_file"/>' .
686 '<input type = "hidden" name = "hash" value = "' . $l['hash'] . '"/>' .
687 jirafeau_admin_csrf_field() .
688 '<input type = "submit" value = "' . t('DEL_FILE_LINKS') . '" />' .
689 '</form>' .
690 '</td>';
691 echo '</tr>';
692 }
693 }
694 }
695 echo '</table></fieldset>';
696 }
697
698 /**
699 * Clean expired files.
700 * @return number of cleaned files.
701 */
702 function jirafeau_admin_clean()
703 {
704 $count = 0;
705 /* Get all links files. */
706 $stack = array(VAR_LINKS);
707 while (($d = array_shift($stack)) && $d != null) {
708 $dir = scandir($d);
709
710 foreach ($dir as $node) {
711 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
712 preg_match('/\.tmp/i', "$node")) {
713 continue;
714 }
715
716 if (is_dir($d . $node)) {
717 /* Push new found directory. */
718 $stack[] = $d . $node . '/';
719 } elseif (is_file($d . $node)) {
720 /* Read link informations. */
721 $l = jirafeau_get_link(basename($node));
722 if (!count($l)) {
723 continue;
724 }
725 $p = s2p($l['hash']);
726 if ($l['time'] > 0 && $l['time'] < time() || // expired
727 !file_exists(VAR_FILES . $p . $l['hash']) || // invalid
728 !file_exists(VAR_FILES . $p . $l['hash'] . '_count')) { // invalid
729 jirafeau_delete_link($node);
730 $count++;
731 }
732 }
733 }
734 }
735 return $count;
736 }
737
738
739 /**
740 * Clean old async transferts.
741 * @return number of cleaned files.
742 */
743 function jirafeau_admin_clean_async()
744 {
745 $count = 0;
746 /* Get all links files. */
747 $stack = array(VAR_ASYNC);
748 while (($d = array_shift($stack)) && $d != null) {
749 $dir = scandir($d);
750
751 foreach ($dir as $node) {
752 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
753 preg_match('/\.tmp/i', "$node")) {
754 continue;
755 }
756
757 if (is_dir($d . $node)) {
758 /* Push new found directory. */
759 $stack[] = $d . $node . '/';
760 } elseif (is_file($d . $node)) {
761 /* Read async informations. */
762 $a = jirafeau_get_async_ref(basename($node));
763 if (!count($a)) {
764 continue;
765 }
766 /* Delete transferts older than 1 hour. */
767 if (time() - $a['last_edited'] > 3600) {
768 jirafeau_async_delete(basename($node));
769 $count++;
770 }
771 }
772 }
773 }
774 return $count;
775 }
776 /**
777 * Read async transfert informations
778 * @return array containing informations.
779 */
780 function jirafeau_get_async_ref($ref)
781 {
782 $out = array();
783 $refinfos = VAR_ASYNC . s2p("$ref") . "$ref";
784
785 if (!file_exists($refinfos)) {
786 return $out;
787 }
788
789 $c = file($refinfos);
790 $out['file_name'] = trim($c[0]);
791 $out['mime_type'] = trim($c[1]);
792 $out['key'] = trim($c[2], NL);
793 $out['time'] = trim($c[3]);
794 $out['onetime'] = trim($c[4]);
795 $out['ip'] = trim($c[5]);
796 $out['last_edited'] = trim($c[6]);
797 $out['next_code'] = trim($c[7]);
798 return $out;
799 }
800
801 /**
802 * Delete async transfert informations
803 */
804 function jirafeau_async_delete($ref)
805 {
806 $p = s2p("$ref");
807 if (file_exists(VAR_ASYNC . $p . $ref)) {
808 unlink(VAR_ASYNC . $p . $ref);
809 }
810 if (file_exists(VAR_ASYNC . $p . $ref . '_data')) {
811 unlink(VAR_ASYNC . $p . $ref . '_data');
812 }
813 $parse = VAR_ASYNC . $p;
814 $scan = array();
815 while (file_exists($parse)
816 && ($scan = scandir($parse))
817 && count($scan) == 2 // '.' and '..' folders => empty.
818 && basename($parse) != basename(VAR_ASYNC)) {
819 rmdir($parse);
820 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
821 }
822 }
823
824 /**
825 * Init a new asynchronous upload.
826 * @param $finename Name of the file to send
827 * @param $one_time One time upload parameter
828 * @param $key eventual password (or blank)
829 * @param $time time limit
830 * @param $ip ip address of the client
831 * @return a string containing a temporary reference followed by a code or the string 'Error'
832 */
833 function jirafeau_async_init($filename, $type, $one_time, $key, $time, $ip)
834 {
835 $res = 'Error';
836
837 /* Create temporary folder. */
838 $ref;
839 $p;
840 $code = jirafeau_gen_random(4);
841 do {
842 $ref = jirafeau_gen_random(32);
843 $p = VAR_ASYNC . s2p($ref);
844 } while (file_exists($p));
845 @mkdir($p, 0755, true);
846 if (!file_exists($p)) {
847 echo 'Error';
848 return;
849 }
850
851 /* md5 password or empty */
852 $password = '';
853 if (!empty($key)) {
854 $password = md5($key);
855 }
856
857 /* Store informations. */
858 $p .= $ref;
859 $handle = fopen($p, 'w');
860 fwrite($handle,
861 str_replace(NL, '', trim($filename)) . NL .
862 str_replace(NL, '', trim($type)) . NL . $password . NL .
863 $time . NL . ($one_time ? 'O' : 'R') . NL . $ip . NL .
864 time() . NL . $code . NL);
865 fclose($handle);
866
867 return $ref . NL . $code ;
868 }
869
870 /**
871 * Append a piece of file on the asynchronous upload.
872 * @param $ref asynchronous upload reference
873 * @param $file piece of data
874 * @param $code client code for this operation
875 * @param $max_file_size maximum allowed file size
876 * @return a string containing a next code to use or the string "Error"
877 */
878 function jirafeau_async_push($ref, $data, $code, $max_file_size)
879 {
880 /* Get async infos. */
881 $a = jirafeau_get_async_ref($ref);
882
883 /* Check some errors. */
884 if (count($a) == 0
885 || $a['next_code'] != "$code"
886 || empty($data['tmp_name'])
887 || !is_uploaded_file($data['tmp_name'])) {
888 return 'Error';
889 }
890
891 $p = s2p($ref);
892
893 /* File path. */
894 $r_path = $data['tmp_name'];
895 $w_path = VAR_ASYNC . $p . $ref . '_data';
896
897 /* Check that file size is not above upload limit. */
898 if ($max_file_size > 0 &&
899 filesize($r_path) + filesize($w_path) > $max_file_size * 1024 * 1024) {
900 jirafeau_async_delete($ref);
901 return 'Error';
902 }
903
904 /* Concatenate data. */
905 $r = fopen($r_path, 'r');
906 $w = fopen($w_path, 'a');
907 while (!feof($r)) {
908 if (fwrite($w, fread($r, 1024)) === false) {
909 fclose($r);
910 fclose($w);
911 jirafeau_async_delete($ref);
912 return 'Error';
913 }
914 }
915 fclose($r);
916 fclose($w);
917 unlink($r_path);
918
919 /* Update async file. */
920 $code = jirafeau_gen_random(4);
921 $handle = fopen(VAR_ASYNC . $p . $ref, 'w');
922 fwrite($handle,
923 $a['file_name'] . NL. $a['mime_type'] . NL. $a['key'] . NL .
924 $a['time'] . NL . $a['onetime'] . NL . $a['ip'] . NL .
925 time() . NL . $code . NL);
926 fclose($handle);
927 return $code;
928 }
929
930 /**
931 * Finalyze an asynchronous upload.
932 * @param $ref asynchronous upload reference
933 * @param $code client code for this operation
934 * @param $crypt boolean asking to crypt or not
935 * @param $link_name_length link name length
936 * @return a string containing the download reference followed by a delete code or the string 'Error'
937 */
938 function jirafeau_async_end($ref, $code, $crypt, $link_name_length, $file_hash_method)
939 {
940 /* Get async infos. */
941 $a = jirafeau_get_async_ref($ref);
942 if (count($a) == 0
943 || $a['next_code'] != "$code") {
944 return "Error";
945 }
946
947 /* Generate link infos. */
948 $p = VAR_ASYNC . s2p($ref) . $ref . "_data";
949 if (!file_exists($p)) {
950 return 'Error';
951 }
952
953 $crypted = false;
954 $crypt_key = '';
955 if ($crypt == true && extension_loaded('mcrypt') == true) {
956 $crypt_key = jirafeau_encrypt_file($p, $p);
957 if (strlen($crypt_key) > 0) {
958 $crypted = true;
959 }
960 }
961
962 $hash = jirafeau_hash_file($file_hash_method, $p);
963 $size = filesize($p);
964 $np = s2p($hash);
965 $delete_link_code = jirafeau_gen_random(5);
966
967 /* File already exist ? */
968 if (!file_exists(VAR_FILES . $np)) {
969 @mkdir(VAR_FILES . $np, 0755, true);
970 }
971 if (!file_exists(VAR_FILES . $np . $hash)) {
972 rename($p, VAR_FILES . $np . $hash);
973 }
974
975 /* Increment or create count file. */
976 $counter = 0;
977 if (file_exists(VAR_FILES . $np . $hash . '_count')) {
978 $content = file(VAR_FILES . $np . $hash. '_count');
979 $counter = trim($content[0]);
980 }
981 $counter++;
982 $handle = fopen(VAR_FILES . $np . $hash. '_count', 'w');
983 fwrite($handle, $counter);
984 fclose($handle);
985
986 /* Create link. */
987 $link_tmp_name = VAR_LINKS . $hash . rand(0, 10000) . '.tmp';
988 $handle = fopen($link_tmp_name, 'w');
989 fwrite($handle,
990 $a['file_name'] . NL . $a['mime_type'] . NL . $size . NL .
991 $a['key'] . NL . $a['time'] . NL . $hash . NL . $a['onetime'] . NL .
992 time() . NL . $a['ip'] . NL . $delete_link_code . NL . ($crypted ? 'C' : 'O'));
993 fclose($handle);
994 $hash_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
995 $l = s2p("$hash_link");
996 if (!@mkdir(VAR_LINKS . $l, 0755, true) ||
997 !rename($link_tmp_name, VAR_LINKS . $l . $hash_link)) {
998 echo "Error";
999 }
1000
1001 /* Clean async upload. */
1002 jirafeau_async_delete($ref);
1003 return $hash_link . NL . $delete_link_code . NL . urlencode($crypt_key);
1004 }
1005
1006 function jirafeau_crypt_create_iv($base, $size)
1007 {
1008 $iv = '';
1009 while (strlen($iv) < $size) {
1010 $iv = $iv . $base;
1011 }
1012 $iv = substr($iv, 0, $size);
1013 return $iv;
1014 }
1015
1016 /**
1017 * Crypt file and returns decrypt key.
1018 * @param $fp_src file path to the file to crypt.
1019 * @param $fp_dst file path to the file to write crypted file (could be the same).
1020 * @return decrypt key composed of the key and the iv separated by a point ('.')
1021 */
1022 function jirafeau_encrypt_file($fp_src, $fp_dst)
1023 {
1024 $fs = filesize($fp_src);
1025 if ($fs === false || $fs == 0 || !(extension_loaded('mcrypt') == true)) {
1026 return '';
1027 }
1028
1029 /* Prepare module. */
1030 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1031 /* Generate key. */
1032 $crypt_key = jirafeau_gen_random(10);
1033 $hash_key = md5($crypt_key);
1034 $iv = jirafeau_crypt_create_iv($hash_key, mcrypt_enc_get_iv_size($m));
1035 /* Init module. */
1036 mcrypt_generic_init($m, $hash_key, $iv);
1037 /* Crypt file. */
1038 $r = fopen($fp_src, 'r');
1039 $w = fopen($fp_dst, 'c');
1040 while (!feof($r)) {
1041 $enc = mcrypt_generic($m, fread($r, 1024));
1042 if (fwrite($w, $enc) === false) {
1043 return '';
1044 }
1045 }
1046 fclose($r);
1047 fclose($w);
1048 /* Cleanup. */
1049 mcrypt_generic_deinit($m);
1050 mcrypt_module_close($m);
1051 return $crypt_key;
1052 }
1053
1054 /**
1055 * Decrypt file.
1056 * @param $fp_src file path to the file to decrypt.
1057 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1058 * @param $k string composed of the key and the iv separated by a point ('.')
1059 * @return key used to decrypt. a string of length 0 is returned if failed.
1060 */
1061 function jirafeau_decrypt_file($fp_src, $fp_dst, $k)
1062 {
1063 $fs = filesize($fp_src);
1064 if ($fs === false || $fs == 0 || extension_loaded('mcrypt') == false) {
1065 return false;
1066 }
1067
1068 /* Init module */
1069 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1070 /* Extract key and iv. */
1071 $crypt_key = $k;
1072 $hash_key = md5($crypt_key);
1073 $iv = jirafeau_crypt_create_iv($hash_key, mcrypt_enc_get_iv_size($m));
1074 /* Decrypt file. */
1075 $r = fopen($fp_src, 'r');
1076 $w = fopen($fp_dst, 'c');
1077 while (!feof($r)) {
1078 $dec = mdecrypt_generic($m, fread($r, 1024));
1079 if (fwrite($w, $dec) === false) {
1080 return false;
1081 }
1082 }
1083 fclose($r);
1084 fclose($w);
1085 /* Cleanup. */
1086 mcrypt_generic_deinit($m);
1087 mcrypt_module_close($m);
1088 return true;
1089 }
1090
1091 /**
1092 * Check if Jirafeau is password protected for visitors.
1093 * @return true if Jirafeau is password protected, false otherwise.
1094 */
1095 function jirafeau_has_upload_password($cfg)
1096 {
1097 return count($cfg['upload_password']) > 0;
1098 }
1099
1100 /**
1101 * Challenge password for a visitor.
1102 * @param $password password to be challenged
1103 * @return true if password is valid, false otherwise.
1104 */
1105 function jirafeau_challenge_upload_password($cfg, $password)
1106 {
1107 if (!jirafeau_has_upload_password($cfg)) {
1108 return false;
1109 }
1110 foreach ($cfg['upload_password'] as $p) {
1111 if ($password == $p) {
1112 return true;
1113 }
1114 }
1115 return false;
1116 }
1117
1118 /**
1119 * Test if the given IP is whitelisted by the given list.
1120 *
1121 * @param $allowedIpList array of allowed IPs
1122 * @param $challengedIp IP to be challenged
1123 * @return true if IP is authorized, false otherwise.
1124 */
1125 function jirafeau_challenge_ip($allowedIpList, $challengedIp)
1126 {
1127 foreach ($allowedIpList as $i) {
1128 if ($i == $challengedIp) {
1129 return true;
1130 }
1131 // CIDR test for IPv4 only.
1132 if (strpos($i, '/') !== false) {
1133 list($subnet, $mask) = explode('/', $i);
1134 if ((ip2long($challengedIp) & ~((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
1135 return true;
1136 }
1137 }
1138 }
1139 return false;
1140 }
1141
1142 /**
1143 * Check if Jirafeau has a restriction on the IP address for uploading.
1144 * @return true if uploading is IP restricted, false otherwise.
1145 */
1146 function jirafeau_upload_has_ip_restriction($cfg) {
1147 return count($cfg['upload_ip']) > 0;
1148 }
1149
1150 /**
1151 * Test if visitor's IP is authorized to upload at all.
1152 *
1153 * @param $cfg configuration
1154 * @param $challengedIp IP to be challenged
1155 * @return true if IP is authorized, false otherwise.
1156 */
1157 function jirafeau_challenge_upload_ip($cfg, $challengedIp)
1158 {
1159 // If no IP address have been listed, allow upload from any IP
1160 if (!jirafeau_upload_has_ip_restriction($cfg)) {
1161 return true;
1162 }
1163 return jirafeau_challenge_ip($cfg['upload_ip'], $challengedIp);
1164 }
1165
1166 /**
1167 * Test if visitor's IP is authorized to upload without a password.
1168 *
1169 * @param $cfg configuration
1170 * @param $challengedIp IP to be challenged
1171 * @return true if IP is authorized, false otherwise.
1172 */
1173 function jirafeau_challenge_upload_ip_without_password($cfg, $challengedIp)
1174 {
1175 return jirafeau_challenge_ip($cfg['upload_ip_nopassword'], $challengedIp);
1176 }
1177
1178 /**
1179 * Test if visitor's IP is authorized or password is supplied and authorized
1180 * @param $ip IP to be challenged
1181 * @param $password password to be challenged
1182 * @return true if access is valid, false otherwise.
1183 */
1184 function jirafeau_challenge_upload ($cfg, $ip, $password)
1185 {
1186 return jirafeau_challenge_upload_ip_without_password($cfg, $ip) ||
1187 (!jirafeau_has_upload_password($cfg) && !jirafeau_upload_has_ip_restriction($cfg)) ||
1188 (jirafeau_challenge_upload_password($cfg, $password) && jirafeau_challenge_upload_ip($cfg, $ip));
1189 }
1190
1191 /** Tell if we have some HTTP headers generated by a proxy */
1192 function has_http_forwarded()
1193 {
1194 return
1195 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1196 !empty($_SERVER['http_X_forwarded_for']);
1197 }
1198
1199 /**
1200 * Generate IP list from HTTP headers generated by a proxy
1201 * @return array of IP strings
1202 */
1203 function get_ip_list_http_forwarded()
1204 {
1205 $ip_list = array();
1206 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1207 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1208 if ($l === false) {
1209 return array();
1210 }
1211 foreach ($l as $ip) {
1212 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1213 }
1214 }
1215 if (!empty($_SERVER['http_X_forwarded_for'])) {
1216 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1217 foreach ($l as $ip) {
1218 // Separate IP from port
1219 $ipa = explode(':', $ip);
1220 if ($ipa === false) {
1221 continue;
1222 }
1223 $ip = $ipa[0];
1224 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1225 }
1226 }
1227 return $ip_list;
1228 }
1229
1230 /**
1231 * Get the ip address of the client from REMOTE_ADDR
1232 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1233 * @returns the client ip address
1234 */
1235 function get_ip_address($cfg)
1236 {
1237 $remote = $_SERVER['REMOTE_ADDR'];
1238 if (count($cfg['proxy_ip']) == 0 || !has_http_forwarded()) {
1239 return $remote;
1240 }
1241
1242 $ip_list = get_ip_list_http_forwarded();
1243 if (count($ip_list) == 0) {
1244 return $remote;
1245 }
1246
1247 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1248 if ($remote != $proxy_ip) {
1249 continue;
1250 }
1251 // Take the last IP (the one which has been set by the defined proxy).
1252 return end($ip_list);
1253 }
1254 return $remote;
1255 }
1256
1257 /**
1258 * Convert hexadecimal string to base64
1259 */
1260 function hex_to_base64($hex)
1261 {
1262 $b = '';
1263 foreach (str_split($hex, 2) as $pair) {
1264 $b .= chr(hexdec($pair));
1265 }
1266 return base64_encode($b);
1267 }
1268
1269 /**
1270 * Replace markers in templates.
1271 *
1272 * Available markers have the scheme "###MARKERNAME###".
1273 *
1274 * @param $content string Template text with markers
1275 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1276 * @return Template with replaced markers
1277 */
1278 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1279 {
1280 $patterns = array(
1281 '/###ORGANISATION###/',
1282 '/###CONTACTPERSON###/',
1283 '/###WEBROOT###/'
1284 );
1285 $replacements = array(
1286 $GLOBALS['cfg']['organisation'],
1287 $GLOBALS['cfg']['contactperson'],
1288 $GLOBALS['cfg']['web_root']
1289 );
1290 $content = preg_replace($patterns, $replacements, $content);
1291
1292 if (true === $htmllinebreaks) {
1293 $content = nl2br($content);
1294 }
1295
1296 return $content;
1297 }
1298
1299 function jirafeau_escape($string)
1300 {
1301 return htmlspecialchars($string, ENT_QUOTES);
1302 }
1303
1304 function jirafeau_admin_session_start()
1305 {
1306 $_SESSION['admin_auth'] = true;
1307 $_SESSION['admin_csrf'] = md5(uniqid(mt_rand(), true));
1308 }
1309
1310 function jirafeau_admin_session_end()
1311 {
1312 $_SESSION = array();
1313 session_destroy();
1314 }
1315
1316 function jirafeau_admin_session_logged()
1317 {
1318 return isset($_SESSION['admin_auth']) &&
1319 isset($_SESSION['admin_csrf']) &&
1320 isset($_POST['admin_csrf']) &&
1321 $_SESSION['admin_auth'] === true &&
1322 $_SESSION['admin_csrf'] === $_POST['admin_csrf'];
1323 }
1324
1325 function jirafeau_admin_csrf_field()
1326 {
1327 return "<input type='hidden' name='admin_csrf' value='". $_SESSION['admin_csrf'] . "'/>";
1328 }

patrick-canterino.de