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

patrick-canterino.de