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

patrick-canterino.de