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

patrick-canterino.de