]> git.p6c8.net - jirafeau_project.git/blob - lib/functions.php
Translated using Weblate (German)
[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($md5)
163 {
164 $p = s2p("$md5");
165 $f = VAR_FILES . $p . $md5;
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 $md5 = $l['md5'];
265 $p = s2p("$md5");
266
267 $counter = 1;
268 if (file_exists(VAR_FILES . $p . $md5. '_count')) {
269 $content = file(VAR_FILES . $p . $md5. '_count');
270 $counter = trim($content[0]);
271 }
272 $counter--;
273
274 if ($counter >= 1) {
275 $handle = fopen(VAR_FILES . $p . $md5. '_count', 'w');
276 fwrite($handle, $counter);
277 fclose($handle);
278 }
279
280 if ($counter == 0) {
281 jirafeau_clean_rm_file($md5);
282 }
283 }
284
285 /**
286 * Delete a file and it's links.
287 */
288 function jirafeau_delete_file($md5)
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['md5'] == $md5) {
312 $count++;
313 jirafeau_delete_link($node);
314 }
315 }
316 }
317 }
318 jirafeau_clean_rm_file($md5);
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 $md5 = 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("$md5");
372 if (file_exists(VAR_FILES . $p . $md5)) {
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 . $md5)) {
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 . $md5 . '_count')) {
390 $content = file(VAR_FILES . $p . $md5. '_count');
391 $counter = trim($content[0]);
392 }
393 $counter++;
394 $handle = fopen(VAR_FILES . $p . $md5. '_count', 'w');
395 fwrite($handle, $counter);
396 fclose($handle);
397
398 /* Create delete code. */
399 $delete_link_code = jirafeau_gen_random(5);
400
401 /* md5 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 . $md5 . 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 . $md5. NL . ($one_time_download ? 'O' : 'R') . NL . time() .
413 NL . $ip . NL. $delete_link_code . NL . ($crypted ? 'C' : 'O'));
414 fclose($handle);
415 $md5_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
416 $l = s2p("$md5_link");
417 if (!@mkdir(VAR_LINKS . $l, 0755, true) ||
418 !rename($link_tmp_name, VAR_LINKS . $l . $md5_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 . $md5. '_count', 'w');
426 fwrite($handle, $counter);
427 fclose($handle);
428 } else {
429 jirafeau_clean_rm_file($md5_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' => $md5_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['md5'] = 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>';
571 echo '<tr>';
572 echo '<td>' . t('FILENAME') . '</td>';
573 echo '<td>' . t('TYPE') . '</td>';
574 echo '<td>' . t('SIZE') . '</td>';
575 echo '<td>' . t('EXPIRE') . '</td>';
576 echo '<td>' . t('ONETIME') . '</td>';
577 echo '<td>' . t('UPLOAD_DATE') . '</td>';
578 echo '<td>' . t('ORIGIN') . '</td>';
579 echo '<td>' . t('ACTION') . '</td>';
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['md5']) {
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 = "md5" value = "' . $l['md5'] . '"/>' .
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['md5']);
684 if ($l['time'] > 0 && $l['time'] < time() || // expired
685 !file_exists(VAR_FILES . $p . $l['md5']) || // invalid
686 !file_exists(VAR_FILES . $p . $l['md5'] . '_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 $md5 = md5_file($p);
921 $size = filesize($p);
922 $np = s2p($md5);
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 . $md5)) {
930 rename($p, VAR_FILES . $np . $md5);
931 }
932
933 /* Increment or create count file. */
934 $counter = 0;
935 if (file_exists(VAR_FILES . $np . $md5 . '_count')) {
936 $content = file(VAR_FILES . $np . $md5. '_count');
937 $counter = trim($content[0]);
938 }
939 $counter++;
940 $handle = fopen(VAR_FILES . $np . $md5. '_count', 'w');
941 fwrite($handle, $counter);
942 fclose($handle);
943
944 /* Create link. */
945 $link_tmp_name = VAR_LINKS . $md5 . 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 . $md5 . NL . $a['onetime'] . NL .
950 time() . NL . $a['ip'] . NL . $delete_link_code . NL . ($crypted ? 'C' : 'O'));
951 fclose($handle);
952 $md5_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
953 $l = s2p("$md5_link");
954 if (!@mkdir(VAR_LINKS . $l, 0755, true) ||
955 !rename($link_tmp_name, VAR_LINKS . $l . $md5_link)) {
956 echo "Error";
957 }
958
959 /* Clean async upload. */
960 jirafeau_async_delete($ref);
961 return $md5_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 $md5_key = md5($crypt_key);
992 $iv = jirafeau_crypt_create_iv($md5_key, mcrypt_enc_get_iv_size($m));
993 /* Init module. */
994 mcrypt_generic_init($m, $md5_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 $md5_key = md5($crypt_key);
1031 $iv = jirafeau_crypt_create_iv($md5_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 visitor's IP is authorized to upload.
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_upload_ip($allowedIpList, $challengedIp)
1084 {
1085 // skip if list is empty = all IPs allowed
1086 if (count($allowedIpList) == 0) {
1087 return true;
1088 }
1089 // test given IP against each allowed IP
1090 foreach ($allowedIpList as $i) {
1091 if ($i == $challengedIp) {
1092 return true;
1093 }
1094 // CIDR test for IPv4 only.
1095 if (strpos($i, '/') !== false) {
1096 list($subnet, $mask) = explode('/', $i);
1097 if ((ip2long($challengedIp) & ~((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
1098 return true;
1099 }
1100 }
1101 }
1102 return false;
1103 }
1104
1105 /**
1106 * Test if visitor's IP is authorized or password is supplied and authorized
1107 * @param $ip IP to be challenged
1108 * @param $password password to be challenged
1109 * @return true if access is valid, false otherwise.
1110 */
1111 function jirafeau_challenge_upload ($cfg, $ip, $password)
1112 {
1113 // Allow if no ip restrictaion and no password restriction
1114 if ((count ($cfg['upload_ip']) == 0) and (count ($cfg['upload_password']) == 0)) {
1115 return true;
1116 }
1117
1118 // Allow if ip is in array (no password)
1119 foreach ($cfg['upload_ip_nopassword'] as $i) {
1120 if ($i == $ip) {
1121 return true;
1122 }
1123 // CIDR test for IPv4 only.
1124 if (strpos ($i, '/') !== false)
1125 {
1126 list ($subnet, $mask) = explode('/', $i);
1127 if ((ip2long ($ip) & ~((1 << (32 - $mask)) - 1) ) == ip2long ($subnet)) {
1128 return true;
1129 }
1130 }
1131 }
1132
1133 // Allow if ip is in array
1134 foreach ($cfg['upload_ip'] as $i) {
1135 if ($i == $ip) {
1136 return true;
1137 }
1138 // CIDR test for IPv4 only.
1139 if (strpos ($i, '/') !== false)
1140 {
1141 list ($subnet, $mask) = explode('/', $i);
1142 if ((ip2long ($ip) & ~((1 << (32 - $mask)) - 1) ) == ip2long ($subnet)) {
1143 return true;
1144 }
1145 }
1146 }
1147 if (!jirafeau_has_upload_password($cfg)) {
1148 return false;
1149 }
1150
1151 foreach ($cfg['upload_password'] as $p) {
1152 if ($password == $p) {
1153 return true;
1154 }
1155 }
1156 return false;
1157 }
1158
1159 /** Tell if we have some HTTP headers generated by a proxy */
1160 function has_http_forwarded()
1161 {
1162 return
1163 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1164 !empty($_SERVER['http_X_forwarded_for']);
1165 }
1166
1167 /**
1168 * Generate IP list from HTTP headers generated by a proxy
1169 * @return array of IP strings
1170 */
1171 function get_ip_list_http_forwarded()
1172 {
1173 $ip_list = array();
1174 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1175 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1176 if ($l === false) {
1177 return array();
1178 }
1179 foreach ($l as $ip) {
1180 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1181 }
1182 }
1183 if (!empty($_SERVER['http_X_forwarded_for'])) {
1184 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1185 foreach ($l as $ip) {
1186 // Separate IP from port
1187 $ipa = explode(':', $ip);
1188 if ($ipa === false) {
1189 continue;
1190 }
1191 $ip = $ipa[0];
1192 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1193 }
1194 }
1195 return $ip_list;
1196 }
1197
1198 /**
1199 * Get the ip address of the client from REMOTE_ADDR
1200 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1201 * @returns the client ip address
1202 */
1203 function get_ip_address($cfg)
1204 {
1205 $remote = $_SERVER['REMOTE_ADDR'];
1206 if (count($cfg['proxy_ip']) == 0 || !has_http_forwarded()) {
1207 return $remote;
1208 }
1209
1210 $ip_list = get_ip_list_http_forwarded();
1211 if (count($ip_list) == 0) {
1212 return $remote;
1213 }
1214
1215 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1216 if ($remote != $proxy_ip) {
1217 continue;
1218 }
1219 // Take the last IP (the one which has been set by the defined proxy).
1220 return end($ip_list);
1221 }
1222 return $remote;
1223 }
1224
1225 /**
1226 * Convert hexadecimal string to base64
1227 */
1228 function hex_to_base64($hex)
1229 {
1230 $b = '';
1231 foreach (str_split($hex, 2) as $pair) {
1232 $b .= chr(hexdec($pair));
1233 }
1234 return base64_encode($b);
1235 }
1236
1237 /**
1238 * Replace markers in templates.
1239 *
1240 * Available markers have the scheme "###MARKERNAME###".
1241 *
1242 * @param $content string Template text with markers
1243 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1244 * @return Template with replaced markers
1245 */
1246 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1247 {
1248 $patterns = array(
1249 '/###ORGANISATION###/',
1250 '/###CONTACTPERSON###/',
1251 '/###WEBROOT###/'
1252 );
1253 $replacements = array(
1254 $GLOBALS['cfg']['organisation'],
1255 $GLOBALS['cfg']['contactperson'],
1256 $GLOBALS['cfg']['web_root']
1257 );
1258 $content = preg_replace($patterns, $replacements, $content);
1259
1260 if (true === $htmllinebreaks) {
1261 $content = nl2br($content);
1262 }
1263
1264 return $content;
1265 }
1266
1267 function jirafeau_escape($string)
1268 {
1269 return htmlspecialchars($string, ENT_QUOTES);
1270 }
1271
1272 function jirafeau_admin_session_start()
1273 {
1274 $_SESSION['admin_auth'] = true;
1275 $_SESSION['admin_csrf'] = md5(uniqid(mt_rand(), true));
1276 }
1277
1278 function jirafeau_admin_session_end()
1279 {
1280 $_SESSION = array();
1281 session_destroy();
1282 }
1283
1284 function jirafeau_admin_session_logged()
1285 {
1286 return isset($_SESSION['admin_auth']) &&
1287 isset($_SESSION['admin_csrf']) &&
1288 isset($_POST['admin_csrf']) &&
1289 $_SESSION['admin_auth'] === true &&
1290 $_SESSION['admin_csrf'] === $_POST['admin_csrf'];
1291 }
1292
1293 function jirafeau_admin_csrf_field()
1294 {
1295 return "<input type='hidden' name='admin_csrf' value='". $_SESSION['admin_csrf'] . "'/>";
1296 }

patrick-canterino.de