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

patrick-canterino.de