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

patrick-canterino.de