]> git.p6c8.net - jirafeau.git/blob - lib/functions.php
[FEATURE] No logout button for upload_ip_nopassword
[jirafeau.git] / lib / functions.php
1 <?php
2 /*
3 * Jirafeau, your web file repository
4 * Copyright (C) 2008 Julien "axolotl" BERNARD <axolotl@magieeternelle.org>
5 * Copyright (C) 2015 Jerome Jutteau <j.jutteau@gmail.com>
6 * Copyright (C) 2015 Nicola Spanti (RyDroid) <dev@nicola-spanti.info>
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU Affero General Public License as
10 * published by the Free Software Foundation, either version 3 of the
11 * License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Affero General Public License for more details.
17 *
18 * You should have received a copy of the GNU Affero General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22 /**
23 * Transform a string in a path by seperating each letters by a '/'.
24 * @return path finishing with a '/'
25 */
26 function s2p($s)
27 {
28 $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 /* Checking for errors. */
502 if (!is_writable(VAR_FILES)) {
503 add_error(t('FILE_DIR_W'), VAR_FILES);
504 }
505
506 if (!is_writable(VAR_LINKS)) {
507 add_error(t('LINK_DIR_W'), VAR_LINKS);
508 }
509
510 if (!is_writable(VAR_ASYNC)) {
511 add_error(t('ASYNC_DIR_W'), VAR_ASYNC);
512 }
513 }
514
515 /**
516 * Read link informations
517 * @return array containing informations.
518 */
519 function jirafeau_get_link($hash)
520 {
521 $out = array();
522 $link = VAR_LINKS . s2p("$hash") . $hash;
523
524 if (!file_exists($link)) {
525 return $out;
526 }
527
528 $c = file($link);
529 $out['file_name'] = trim($c[0]);
530 $out['mime_type'] = trim($c[1]);
531 $out['file_size'] = trim($c[2]);
532 $out['key'] = trim($c[3], NL);
533 $out['time'] = trim($c[4]);
534 $out['md5'] = trim($c[5]);
535 $out['onetime'] = trim($c[6]);
536 $out['upload_date'] = trim($c[7]);
537 $out['ip'] = trim($c[8]);
538 $out['link_code'] = trim($c[9]);
539 $out['crypted'] = trim($c[10]) == 'C';
540
541 return $out;
542 }
543
544 /**
545 * List files in admin interface.
546 */
547 function jirafeau_admin_list($name, $file_hash, $link_hash)
548 {
549 echo '<fieldset><legend>';
550 if (!empty($name)) {
551 echo t('FILENAME') . ": " . jirafeau_escape($name);
552 }
553 if (!empty($file_hash)) {
554 echo t('FILE') . ": " . jirafeau_escape($file_hash);
555 }
556 if (!empty($link_hash)) {
557 echo t('LINK') . ": " . jirafeau_escape($link_hash);
558 }
559 if (empty($name) && empty($file_hash) && empty($link_hash)) {
560 echo t('LS_FILES');
561 }
562 echo '</legend>';
563 echo '<table>';
564 echo '<tr>';
565 echo '<td>' . t('FILENAME') . '</td>';
566 echo '<td>' . t('TYPE') . '</td>';
567 echo '<td>' . t('SIZE') . '</td>';
568 echo '<td>' . t('EXPIRE') . '</td>';
569 echo '<td>' . t('ONETIME') . '</td>';
570 echo '<td>' . t('UPLOAD_DATE') . '</td>';
571 echo '<td>' . t('ORIGIN') . '</td>';
572 echo '<td>' . t('ACTION') . '</td>';
573 echo '</tr>';
574
575 /* Get all links files. */
576 $stack = array(VAR_LINKS);
577 while (($d = array_shift($stack)) && $d != null) {
578 $dir = scandir($d);
579 foreach ($dir as $node) {
580 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
581 preg_match('/\.tmp/i', "$node")) {
582 continue;
583 }
584 if (is_dir($d . $node)) {
585 /* Push new found directory. */
586 $stack[] = $d . $node . '/';
587 } elseif (is_file($d . $node)) {
588 /* Read link informations. */
589 $l = jirafeau_get_link($node);
590 if (!count($l)) {
591 continue;
592 }
593
594 /* Filter. */
595 if (!empty($name) && !@preg_match("/$name/i", jirafeau_escape($l['file_name']))) {
596 continue;
597 }
598 if (!empty($file_hash) && $file_hash != $l['md5']) {
599 continue;
600 }
601 if (!empty($link_hash) && $link_hash != $node) {
602 continue;
603 }
604 /* Print link informations. */
605 echo '<tr>';
606 echo '<td>' .
607 '<strong><a id="upload_link" href="f.php?h='. jirafeau_escape($node) .'" title="' .
608 t('DL_PAGE') . '">' . jirafeau_escape($l['file_name']) . '</a></strong>';
609 echo '</td>';
610 echo '<td>' . jirafeau_escape($l['mime_type']) . '</td>';
611 echo '<td>' . jirafeau_human_size($l['file_size']) . '</td>';
612 echo '<td>' . ($l['time'] == -1 ? '∞' : jirafeau_get_datetimefield($l['time'])) . '</td>';
613 echo '<td>';
614 if ($l['onetime'] == 'O') {
615 echo 'Y';
616 } else {
617 echo 'N';
618 }
619 echo '</td>';
620 echo '<td>' . jirafeau_get_datetimefield($l['upload_date']) . '</td>';
621 echo '<td>' . $l['ip'] . '</td>';
622 echo '<td>' .
623 '<form method="post">' .
624 '<input type = "hidden" name = "action" value = "download"/>' .
625 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
626 jirafeau_admin_csrf_field() .
627 '<input type = "submit" value = "' . t('DL') . '" />' .
628 '</form>' .
629 '<form method="post">' .
630 '<input type = "hidden" name = "action" value = "delete_link"/>' .
631 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
632 jirafeau_admin_csrf_field() .
633 '<input type = "submit" value = "' . t('DEL_LINK') . '" />' .
634 '</form>' .
635 '<form method="post">' .
636 '<input type = "hidden" name = "action" value = "delete_file"/>' .
637 '<input type = "hidden" name = "md5" value = "' . $l['md5'] . '"/>' .
638 jirafeau_admin_csrf_field() .
639 '<input type = "submit" value = "' . t('DEL_FILE_LINKS') . '" />' .
640 '</form>' .
641 '</td>';
642 echo '</tr>';
643 }
644 }
645 }
646 echo '</table></fieldset>';
647 }
648
649 /**
650 * Clean expired files.
651 * @return number of cleaned files.
652 */
653 function jirafeau_admin_clean()
654 {
655 $count = 0;
656 /* Get all links files. */
657 $stack = array(VAR_LINKS);
658 while (($d = array_shift($stack)) && $d != null) {
659 $dir = scandir($d);
660
661 foreach ($dir as $node) {
662 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
663 preg_match('/\.tmp/i', "$node")) {
664 continue;
665 }
666
667 if (is_dir($d . $node)) {
668 /* Push new found directory. */
669 $stack[] = $d . $node . '/';
670 } elseif (is_file($d . $node)) {
671 /* Read link informations. */
672 $l = jirafeau_get_link(basename($node));
673 if (!count($l)) {
674 continue;
675 }
676 $p = s2p($l['md5']);
677 if ($l['time'] > 0 && $l['time'] < time() || // expired
678 !file_exists(VAR_FILES . $p . $l['md5']) || // invalid
679 !file_exists(VAR_FILES . $p . $l['md5'] . '_count')) { // invalid
680 jirafeau_delete_link($node);
681 $count++;
682 }
683 }
684 }
685 }
686 return $count;
687 }
688
689
690 /**
691 * Clean old async transferts.
692 * @return number of cleaned files.
693 */
694 function jirafeau_admin_clean_async()
695 {
696 $count = 0;
697 /* Get all links files. */
698 $stack = array(VAR_ASYNC);
699 while (($d = array_shift($stack)) && $d != null) {
700 $dir = scandir($d);
701
702 foreach ($dir as $node) {
703 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
704 preg_match('/\.tmp/i', "$node")) {
705 continue;
706 }
707
708 if (is_dir($d . $node)) {
709 /* Push new found directory. */
710 $stack[] = $d . $node . '/';
711 } elseif (is_file($d . $node)) {
712 /* Read async informations. */
713 $a = jirafeau_get_async_ref(basename($node));
714 if (!count($a)) {
715 continue;
716 }
717 /* Delete transferts older than 1 hour. */
718 if (time() - $a['last_edited'] > 3600) {
719 jirafeau_async_delete(basename($node));
720 $count++;
721 }
722 }
723 }
724 }
725 return $count;
726 }
727 /**
728 * Read async transfert informations
729 * @return array containing informations.
730 */
731 function jirafeau_get_async_ref($ref)
732 {
733 $out = array();
734 $refinfos = VAR_ASYNC . s2p("$ref") . "$ref";
735
736 if (!file_exists($refinfos)) {
737 return $out;
738 }
739
740 $c = file($refinfos);
741 $out['file_name'] = trim($c[0]);
742 $out['mime_type'] = trim($c[1]);
743 $out['key'] = trim($c[2], NL);
744 $out['time'] = trim($c[3]);
745 $out['onetime'] = trim($c[4]);
746 $out['ip'] = trim($c[5]);
747 $out['last_edited'] = trim($c[6]);
748 $out['next_code'] = trim($c[7]);
749 return $out;
750 }
751
752 /**
753 * Delete async transfert informations
754 */
755 function jirafeau_async_delete($ref)
756 {
757 $p = s2p("$ref");
758 if (file_exists(VAR_ASYNC . $p . $ref)) {
759 unlink(VAR_ASYNC . $p . $ref);
760 }
761 if (file_exists(VAR_ASYNC . $p . $ref . '_data')) {
762 unlink(VAR_ASYNC . $p . $ref . '_data');
763 }
764 $parse = VAR_ASYNC . $p;
765 $scan = array();
766 while (file_exists($parse)
767 && ($scan = scandir($parse))
768 && count($scan) == 2 // '.' and '..' folders => empty.
769 && basename($parse) != basename(VAR_ASYNC)) {
770 rmdir($parse);
771 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
772 }
773 }
774
775 /**
776 * Init a new asynchronous upload.
777 * @param $finename Name of the file to send
778 * @param $one_time One time upload parameter
779 * @param $key eventual password (or blank)
780 * @param $time time limit
781 * @param $ip ip address of the client
782 * @return a string containing a temporary reference followed by a code or the string 'Error'
783 */
784 function jirafeau_async_init($filename, $type, $one_time, $key, $time, $ip)
785 {
786 $res = 'Error';
787
788 /* Create temporary folder. */
789 $ref;
790 $p;
791 $code = jirafeau_gen_random(4);
792 do {
793 $ref = jirafeau_gen_random(32);
794 $p = VAR_ASYNC . s2p($ref);
795 } while (file_exists($p));
796 @mkdir($p, 0755, true);
797 if (!file_exists($p)) {
798 echo 'Error';
799 return;
800 }
801
802 /* md5 password or empty */
803 $password = '';
804 if (!empty($key)) {
805 $password = md5($key);
806 }
807
808 /* Store informations. */
809 $p .= $ref;
810 $handle = fopen($p, 'w');
811 fwrite($handle,
812 str_replace(NL, '', trim($filename)) . NL .
813 str_replace(NL, '', trim($type)) . NL . $password . NL .
814 $time . NL . ($one_time ? 'O' : 'R') . NL . $ip . NL .
815 time() . NL . $code . NL);
816 fclose($handle);
817
818 return $ref . NL . $code ;
819 }
820
821 /**
822 * Append a piece of file on the asynchronous upload.
823 * @param $ref asynchronous upload reference
824 * @param $file piece of data
825 * @param $code client code for this operation
826 * @param $max_file_size maximum allowed file size
827 * @return a string containing a next code to use or the string "Error"
828 */
829 function jirafeau_async_push($ref, $data, $code, $max_file_size)
830 {
831 /* Get async infos. */
832 $a = jirafeau_get_async_ref($ref);
833
834 /* Check some errors. */
835 if (count($a) == 0
836 || $a['next_code'] != "$code"
837 || empty($data['tmp_name'])
838 || !is_uploaded_file($data['tmp_name'])) {
839 return 'Error';
840 }
841
842 $p = s2p($ref);
843
844 /* File path. */
845 $r_path = $data['tmp_name'];
846 $w_path = VAR_ASYNC . $p . $ref . '_data';
847
848 /* Check that file size is not above upload limit. */
849 if ($max_file_size > 0 &&
850 filesize($r_path) + filesize($w_path) > $max_file_size * 1024 * 1024) {
851 jirafeau_async_delete($ref);
852 return 'Error';
853 }
854
855 /* Concatenate data. */
856 $r = fopen($r_path, 'r');
857 $w = fopen($w_path, 'a');
858 while (!feof($r)) {
859 if (fwrite($w, fread($r, 1024)) === false) {
860 fclose($r);
861 fclose($w);
862 jirafeau_async_delete($ref);
863 return 'Error';
864 }
865 }
866 fclose($r);
867 fclose($w);
868 unlink($r_path);
869
870 /* Update async file. */
871 $code = jirafeau_gen_random(4);
872 $handle = fopen(VAR_ASYNC . $p . $ref, 'w');
873 fwrite($handle,
874 $a['file_name'] . NL. $a['mime_type'] . NL. $a['key'] . NL .
875 $a['time'] . NL . $a['onetime'] . NL . $a['ip'] . NL .
876 time() . NL . $code . NL);
877 fclose($handle);
878 return $code;
879 }
880
881 /**
882 * Finalyze an asynchronous upload.
883 * @param $ref asynchronous upload reference
884 * @param $code client code for this operation
885 * @param $crypt boolean asking to crypt or not
886 * @param $link_name_length link name length
887 * @return a string containing the download reference followed by a delete code or the string 'Error'
888 */
889 function jirafeau_async_end($ref, $code, $crypt, $link_name_length)
890 {
891 /* Get async infos. */
892 $a = jirafeau_get_async_ref($ref);
893 if (count($a) == 0
894 || $a['next_code'] != "$code") {
895 return "Error";
896 }
897
898 /* Generate link infos. */
899 $p = VAR_ASYNC . s2p($ref) . $ref . "_data";
900 if (!file_exists($p)) {
901 return 'Error';
902 }
903
904 $crypted = false;
905 $crypt_key = '';
906 if ($crypt == true && extension_loaded('mcrypt') == true) {
907 $crypt_key = jirafeau_encrypt_file($p, $p);
908 if (strlen($crypt_key) > 0) {
909 $crypted = true;
910 }
911 }
912
913 $md5 = md5_file($p);
914 $size = filesize($p);
915 $np = s2p($md5);
916 $delete_link_code = jirafeau_gen_random(5);
917
918 /* File already exist ? */
919 if (!file_exists(VAR_FILES . $np)) {
920 @mkdir(VAR_FILES . $np, 0755, true);
921 }
922 if (!file_exists(VAR_FILES . $np . $md5)) {
923 rename($p, VAR_FILES . $np . $md5);
924 }
925
926 /* Increment or create count file. */
927 $counter = 0;
928 if (file_exists(VAR_FILES . $np . $md5 . '_count')) {
929 $content = file(VAR_FILES . $np . $md5. '_count');
930 $counter = trim($content[0]);
931 }
932 $counter++;
933 $handle = fopen(VAR_FILES . $np . $md5. '_count', 'w');
934 fwrite($handle, $counter);
935 fclose($handle);
936
937 /* Create link. */
938 $link_tmp_name = VAR_LINKS . $md5 . rand(0, 10000) . '.tmp';
939 $handle = fopen($link_tmp_name, 'w');
940 fwrite($handle,
941 $a['file_name'] . NL . $a['mime_type'] . NL . $size . NL .
942 $a['key'] . NL . $a['time'] . NL . $md5 . NL . $a['onetime'] . NL .
943 time() . NL . $a['ip'] . NL . $delete_link_code . NL . ($crypted ? 'C' : 'O'));
944 fclose($handle);
945 $md5_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
946 $l = s2p("$md5_link");
947 if (!@mkdir(VAR_LINKS . $l, 0755, true) ||
948 !rename($link_tmp_name, VAR_LINKS . $l . $md5_link)) {
949 echo "Error";
950 }
951
952 /* Clean async upload. */
953 jirafeau_async_delete($ref);
954 return $md5_link . NL . $delete_link_code . NL . urlencode($crypt_key);
955 }
956
957 function jirafeau_crypt_create_iv($base, $size)
958 {
959 $iv = '';
960 while (strlen($iv) < $size) {
961 $iv = $iv . $base;
962 }
963 $iv = substr($iv, 0, $size);
964 return $iv;
965 }
966
967 /**
968 * Crypt file and returns decrypt key.
969 * @param $fp_src file path to the file to crypt.
970 * @param $fp_dst file path to the file to write crypted file (could be the same).
971 * @return decrypt key composed of the key and the iv separated by a point ('.')
972 */
973 function jirafeau_encrypt_file($fp_src, $fp_dst)
974 {
975 $fs = filesize($fp_src);
976 if ($fs === false || $fs == 0 || !(extension_loaded('mcrypt') == true)) {
977 return '';
978 }
979
980 /* Prepare module. */
981 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
982 /* Generate key. */
983 $crypt_key = jirafeau_gen_random(10);
984 $md5_key = md5($crypt_key);
985 $iv = jirafeau_crypt_create_iv($md5_key, mcrypt_enc_get_iv_size($m));
986 /* Init module. */
987 mcrypt_generic_init($m, $md5_key, $iv);
988 /* Crypt file. */
989 $r = fopen($fp_src, 'r');
990 $w = fopen($fp_dst, 'c');
991 while (!feof($r)) {
992 $enc = mcrypt_generic($m, fread($r, 1024));
993 if (fwrite($w, $enc) === false) {
994 return '';
995 }
996 }
997 fclose($r);
998 fclose($w);
999 /* Cleanup. */
1000 mcrypt_generic_deinit($m);
1001 mcrypt_module_close($m);
1002 return $crypt_key;
1003 }
1004
1005 /**
1006 * Decrypt file.
1007 * @param $fp_src file path to the file to decrypt.
1008 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1009 * @param $k string composed of the key and the iv separated by a point ('.')
1010 * @return key used to decrypt. a string of length 0 is returned if failed.
1011 */
1012 function jirafeau_decrypt_file($fp_src, $fp_dst, $k)
1013 {
1014 $fs = filesize($fp_src);
1015 if ($fs === false || $fs == 0 || extension_loaded('mcrypt') == false) {
1016 return false;
1017 }
1018
1019 /* Init module */
1020 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1021 /* Extract key and iv. */
1022 $crypt_key = $k;
1023 $md5_key = md5($crypt_key);
1024 $iv = jirafeau_crypt_create_iv($md5_key, mcrypt_enc_get_iv_size($m));
1025 /* Decrypt file. */
1026 $r = fopen($fp_src, 'r');
1027 $w = fopen($fp_dst, 'c');
1028 while (!feof($r)) {
1029 $dec = mdecrypt_generic($m, fread($r, 1024));
1030 if (fwrite($w, $dec) === false) {
1031 return false;
1032 }
1033 }
1034 fclose($r);
1035 fclose($w);
1036 /* Cleanup. */
1037 mcrypt_generic_deinit($m);
1038 mcrypt_module_close($m);
1039 return true;
1040 }
1041
1042 /**
1043 * Check if Jirafeau is password protected for visitors.
1044 * @return true if Jirafeau is password protected, false otherwise.
1045 */
1046 function jirafeau_has_upload_password($cfg)
1047 {
1048 return count($cfg['upload_password']) > 0;
1049 }
1050
1051 /**
1052 * Challenge password for a visitor.
1053 * @param $password password to be challenged
1054 * @return true if password is valid, false otherwise.
1055 */
1056 function jirafeau_challenge_upload_password($cfg, $password)
1057 {
1058 if (!jirafeau_has_upload_password($cfg)) {
1059 return false;
1060 }
1061 foreach ($cfg['upload_password'] as $p) {
1062 if ($password == $p) {
1063 return true;
1064 }
1065 }
1066 return false;
1067 }
1068
1069 /**
1070 * Test if visitor's IP is authorized to upload.
1071 *
1072 * @param $allowedIpList array of allowed IPs
1073 * @param $challengedIp IP to be challenged
1074 * @return true if IP is authorized, false otherwise.
1075 */
1076 function jirafeau_challenge_upload_ip($allowedIpList, $challengedIp)
1077 {
1078 // skip if list is empty = all IPs allowed
1079 if (count($allowedIpList) == 0) {
1080 return true;
1081 }
1082 // test given IP against each allowed IP
1083 foreach ($allowedIpList as $i) {
1084 if ($i == $challengedIp) {
1085 return true;
1086 }
1087 // CIDR test for IPv4 only.
1088 if (strpos($i, '/') !== false) {
1089 list($subnet, $mask) = explode('/', $i);
1090 if ((ip2long($challengedIp) & ~((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
1091 return true;
1092 }
1093 }
1094 }
1095 return false;
1096 }
1097
1098 /**
1099 * Test if visitor's IP is authorized or password is supplied and authorized
1100 * @param $ip IP to be challenged
1101 * @param $password password to be challenged
1102 * @return true if access is valid, false otherwise.
1103 */
1104 function jirafeau_challenge_upload ($cfg, $ip, $password)
1105 {
1106 // Allow if no ip restrictaion and no password restriction
1107 if ((count ($cfg['upload_ip']) == 0) and (count ($cfg['upload_password']) == 0)) {
1108 return true;
1109 }
1110
1111 // Allow if ip is in array
1112 foreach ($cfg['upload_ip'] as $i) {
1113 if ($i == $ip) {
1114 return true;
1115 }
1116 // CIDR test for IPv4 only.
1117 if (strpos ($i, '/') !== false)
1118 {
1119 list ($subnet, $mask) = explode('/', $i);
1120 if ((ip2long ($ip) & ~((1 << (32 - $mask)) - 1) ) == ip2long ($subnet)) {
1121 return true;
1122 }
1123 }
1124 }
1125 if (!jirafeau_has_upload_password($cfg)) {
1126 return false;
1127 }
1128
1129 foreach ($cfg['upload_password'] as $p) {
1130 if ($password == $p) {
1131 return true;
1132 }
1133 }
1134 return false;
1135 }
1136
1137 /** Tell if we have some HTTP headers generated by a proxy */
1138 function has_http_forwarded()
1139 {
1140 return
1141 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1142 !empty($_SERVER['http_X_forwarded_for']);
1143 }
1144
1145 /**
1146 * Generate IP list from HTTP headers generated by a proxy
1147 * @return array of IP strings
1148 */
1149 function get_ip_list_http_forwarded()
1150 {
1151 $ip_list = array();
1152 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1153 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1154 if ($l === false) {
1155 return array();
1156 }
1157 foreach ($l as $ip) {
1158 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1159 }
1160 }
1161 if (!empty($_SERVER['http_X_forwarded_for'])) {
1162 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1163 foreach ($l as $ip) {
1164 // Separate IP from port
1165 $ipa = explode(':', $ip);
1166 if ($ipa === false) {
1167 continue;
1168 }
1169 $ip = $ipa[0];
1170 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1171 }
1172 }
1173 return $ip_list;
1174 }
1175
1176 /**
1177 * Get the ip address of the client from REMOTE_ADDR
1178 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1179 * @returns the client ip address
1180 */
1181 function get_ip_address($cfg)
1182 {
1183 $remote = $_SERVER['REMOTE_ADDR'];
1184 if (count($cfg['proxy_ip']) == 0 || !has_http_forwarded()) {
1185 return $remote;
1186 }
1187
1188 $ip_list = get_ip_list_http_forwarded();
1189 if (count($ip_list) == 0) {
1190 return $remote;
1191 }
1192
1193 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1194 if ($remote != $proxy_ip) {
1195 continue;
1196 }
1197 // Take the last IP (the one which has been set by the defined proxy).
1198 return end($ip_list);
1199 }
1200 return $remote;
1201 }
1202
1203 /**
1204 * Convert hexadecimal string to base64
1205 */
1206 function hex_to_base64($hex)
1207 {
1208 $b = '';
1209 foreach (str_split($hex, 2) as $pair) {
1210 $b .= chr(hexdec($pair));
1211 }
1212 return base64_encode($b);
1213 }
1214
1215 /**
1216 * Replace markers in templates.
1217 *
1218 * Available markers have the scheme "###MARKERNAME###".
1219 *
1220 * @param $content string Template text with markers
1221 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1222 * @return Template with replaced markers
1223 */
1224 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1225 {
1226 $patterns = array(
1227 '/###ORGANISATION###/',
1228 '/###CONTACTPERSON###/',
1229 '/###WEBROOT###/'
1230 );
1231 $replacements = array(
1232 $GLOBALS['cfg']['organisation'],
1233 $GLOBALS['cfg']['contactperson'],
1234 $GLOBALS['cfg']['web_root']
1235 );
1236 $content = preg_replace($patterns, $replacements, $content);
1237
1238 if (true === $htmllinebreaks) {
1239 $content = nl2br($content);
1240 }
1241
1242 return $content;
1243 }
1244
1245 function jirafeau_escape($string)
1246 {
1247 return htmlspecialchars($string, ENT_QUOTES);
1248 }
1249
1250 function jirafeau_admin_session_start()
1251 {
1252 $_SESSION['admin_auth'] = true;
1253 $_SESSION['admin_csrf'] = md5(uniqid(mt_rand(), true));
1254 }
1255
1256 function jirafeau_admin_session_end()
1257 {
1258 $_SESSION = array();
1259 session_destroy();
1260 }
1261
1262 function jirafeau_admin_session_logged()
1263 {
1264 return isset($_SESSION['admin_auth']) &&
1265 isset($_SESSION['admin_csrf']) &&
1266 isset($_POST['admin_csrf']) &&
1267 $_SESSION['admin_auth'] === true &&
1268 $_SESSION['admin_csrf'] === $_POST['admin_csrf'];
1269 }
1270
1271 function jirafeau_admin_csrf_field()
1272 {
1273 return "<input type='hidden' name='admin_csrf' value='". $_SESSION['admin_csrf'] . "'/>";
1274 }

patrick-canterino.de