]> git.p6c8.net - jirafeau_mojo42.git/blob - lib/functions.php
Jirafeau version 3.3.0
[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 // 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 during file creation.')),
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('The async directory is not writable!'), 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') . ": $name ";
557 }
558 if (!empty($file_hash)) {
559 echo t('file') . ": $file_hash ";
560 }
561 if (!empty($link_hash)) {
562 echo t('link') . ": $link_hash ";
563 }
564 if (empty($name) && empty($file_hash) && empty($link_hash)) {
565 echo t('List all 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", htmlspecialchars($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='. htmlspecialchars($node) .'" title="' .
613 t('Download page') . '">' . htmlspecialchars($l['file_name']) . '</a></strong>';
614 echo '</td>';
615 echo '<td>' . $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 '<input type = "submit" value = "' . t('Download') . '" />' .
632 '</form>' .
633 '<form method="post">' .
634 '<input type = "hidden" name = "action" value = "delete_link"/>' .
635 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
636 '<input type = "submit" value = "' . t('Del link') . '" />' .
637 '</form>' .
638 '<form method="post">' .
639 '<input type = "hidden" name = "action" value = "delete_file"/>' .
640 '<input type = "hidden" name = "md5" value = "' . $l['md5'] . '"/>' .
641 '<input type = "submit" value = "' . t('Del file and links') . '" />' .
642 '</form>' .
643 '</td>';
644 echo '</tr>';
645 }
646 }
647 }
648 echo '</table></fieldset>';
649 }
650
651 /**
652 * Clean expired files.
653 * @return number of cleaned files.
654 */
655 function jirafeau_admin_clean()
656 {
657 $count = 0;
658 /* Get all links files. */
659 $stack = array(VAR_LINKS);
660 while (($d = array_shift($stack)) && $d != null) {
661 $dir = scandir($d);
662
663 foreach ($dir as $node) {
664 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
665 preg_match('/\.tmp/i', "$node")) {
666 continue;
667 }
668
669 if (is_dir($d . $node)) {
670 /* Push new found directory. */
671 $stack[] = $d . $node . '/';
672 } elseif (is_file($d . $node)) {
673 /* Read link informations. */
674 $l = jirafeau_get_link(basename($node));
675 if (!count($l)) {
676 continue;
677 }
678 $p = s2p($l['md5']);
679 if ($l['time'] > 0 && $l['time'] < time() || // expired
680 !file_exists(VAR_FILES . $p . $l['md5']) || // invalid
681 !file_exists(VAR_FILES . $p . $l['md5'] . '_count')) { // invalid
682 jirafeau_delete_link($node);
683 $count++;
684 }
685 }
686 }
687 }
688 return $count;
689 }
690
691
692 /**
693 * Clean old async transferts.
694 * @return number of cleaned files.
695 */
696 function jirafeau_admin_clean_async()
697 {
698 $count = 0;
699 /* Get all links files. */
700 $stack = array(VAR_ASYNC);
701 while (($d = array_shift($stack)) && $d != null) {
702 $dir = scandir($d);
703
704 foreach ($dir as $node) {
705 if (strcmp($node, '.') == 0 || strcmp($node, '..') == 0 ||
706 preg_match('/\.tmp/i', "$node")) {
707 continue;
708 }
709
710 if (is_dir($d . $node)) {
711 /* Push new found directory. */
712 $stack[] = $d . $node . '/';
713 } elseif (is_file($d . $node)) {
714 /* Read async informations. */
715 $a = jirafeau_get_async_ref(basename($node));
716 if (!count($a)) {
717 continue;
718 }
719 /* Delete transferts older than 1 hour. */
720 if (time() - $a['last_edited'] > 3600) {
721 jirafeau_async_delete(basename($node));
722 $count++;
723 }
724 }
725 }
726 }
727 return $count;
728 }
729 /**
730 * Read async transfert informations
731 * @return array containing informations.
732 */
733 function jirafeau_get_async_ref($ref)
734 {
735 $out = array();
736 $refinfos = VAR_ASYNC . s2p("$ref") . "$ref";
737
738 if (!file_exists($refinfos)) {
739 return $out;
740 }
741
742 $c = file($refinfos);
743 $out['file_name'] = trim($c[0]);
744 $out['mime_type'] = trim($c[1]);
745 $out['key'] = trim($c[2], NL);
746 $out['time'] = trim($c[3]);
747 $out['onetime'] = trim($c[4]);
748 $out['ip'] = trim($c[5]);
749 $out['last_edited'] = trim($c[6]);
750 $out['next_code'] = trim($c[7]);
751 return $out;
752 }
753
754 /**
755 * Delete async transfert informations
756 */
757 function jirafeau_async_delete($ref)
758 {
759 $p = s2p("$ref");
760 if (file_exists(VAR_ASYNC . $p . $ref)) {
761 unlink(VAR_ASYNC . $p . $ref);
762 }
763 if (file_exists(VAR_ASYNC . $p . $ref . '_data')) {
764 unlink(VAR_ASYNC . $p . $ref . '_data');
765 }
766 $parse = VAR_ASYNC . $p;
767 $scan = array();
768 while (file_exists($parse)
769 && ($scan = scandir($parse))
770 && count($scan) == 2 // '.' and '..' folders => empty.
771 && basename($parse) != basename(VAR_ASYNC)) {
772 rmdir($parse);
773 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
774 }
775 }
776
777 /**
778 * Init a new asynchronous upload.
779 * @param $finename Name of the file to send
780 * @param $one_time One time upload parameter
781 * @param $key eventual password (or blank)
782 * @param $time time limit
783 * @param $ip ip address of the client
784 * @return a string containing a temporary reference followed by a code or the string 'Error'
785 */
786 function jirafeau_async_init($filename, $type, $one_time, $key, $time, $ip)
787 {
788 $res = 'Error';
789
790 /* Create temporary folder. */
791 $ref;
792 $p;
793 $code = jirafeau_gen_random(4);
794 do {
795 $ref = jirafeau_gen_random(32);
796 $p = VAR_ASYNC . s2p($ref);
797 } while (file_exists($p));
798 @mkdir($p, 0755, true);
799 if (!file_exists($p)) {
800 echo 'Error';
801 return;
802 }
803
804 /* md5 password or empty */
805 $password = '';
806 if (!empty($key)) {
807 $password = md5($key);
808 }
809
810 /* Store informations. */
811 $p .= $ref;
812 $handle = fopen($p, 'w');
813 fwrite($handle,
814 str_replace(NL, '', trim($filename)) . NL .
815 str_replace(NL, '', trim($type)) . NL . $password . NL .
816 $time . NL . ($one_time ? 'O' : 'R') . NL . $ip . NL .
817 time() . NL . $code . NL);
818 fclose($handle);
819
820 return $ref . NL . $code ;
821 }
822
823 /**
824 * Append a piece of file on the asynchronous upload.
825 * @param $ref asynchronous upload reference
826 * @param $file piece of data
827 * @param $code client code for this operation
828 * @param $max_file_size maximum allowed file size
829 * @return a string containing a next code to use or the string "Error"
830 */
831 function jirafeau_async_push($ref, $data, $code, $max_file_size)
832 {
833 /* Get async infos. */
834 $a = jirafeau_get_async_ref($ref);
835
836 /* Check some errors. */
837 if (count($a) == 0
838 || $a['next_code'] != "$code"
839 || empty($data['tmp_name'])
840 || !is_uploaded_file($data['tmp_name'])) {
841 return 'Error';
842 }
843
844 $p = s2p($ref);
845
846 /* File path. */
847 $r_path = $data['tmp_name'];
848 $w_path = VAR_ASYNC . $p . $ref . '_data';
849
850 /* Check that file size is not above upload limit. */
851 if ($max_file_size > 0 &&
852 filesize($r_path) + filesize($w_path) > $max_file_size * 1024 * 1024) {
853 jirafeau_async_delete($ref);
854 return 'Error';
855 }
856
857 /* Concatenate data. */
858 $r = fopen($r_path, 'r');
859 $w = fopen($w_path, 'a');
860 while (!feof($r)) {
861 if (fwrite($w, fread($r, 1024)) === false) {
862 fclose($r);
863 fclose($w);
864 jirafeau_async_delete($ref);
865 return 'Error';
866 }
867 }
868 fclose($r);
869 fclose($w);
870 unlink($r_path);
871
872 /* Update async file. */
873 $code = jirafeau_gen_random(4);
874 $handle = fopen(VAR_ASYNC . $p . $ref, 'w');
875 fwrite($handle,
876 $a['file_name'] . NL. $a['mime_type'] . NL. $a['key'] . NL .
877 $a['time'] . NL . $a['onetime'] . NL . $a['ip'] . NL .
878 time() . NL . $code . NL);
879 fclose($handle);
880 return $code;
881 }
882
883 /**
884 * Finalyze an asynchronous upload.
885 * @param $ref asynchronous upload reference
886 * @param $code client code for this operation
887 * @param $crypt boolean asking to crypt or not
888 * @param $link_name_length link name length
889 * @return a string containing the download reference followed by a delete code or the string 'Error'
890 */
891 function jirafeau_async_end($ref, $code, $crypt, $link_name_length)
892 {
893 /* Get async infos. */
894 $a = jirafeau_get_async_ref($ref);
895 if (count($a) == 0
896 || $a['next_code'] != "$code") {
897 return "Error";
898 }
899
900 /* Generate link infos. */
901 $p = VAR_ASYNC . s2p($ref) . $ref . "_data";
902 if (!file_exists($p)) {
903 return 'Error';
904 }
905
906 $crypted = false;
907 $crypt_key = '';
908 if ($crypt == true && extension_loaded('mcrypt') == true) {
909 $crypt_key = jirafeau_encrypt_file($p, $p);
910 if (strlen($crypt_key) > 0) {
911 $crypted = true;
912 }
913 }
914
915 $md5 = md5_file($p);
916 $size = filesize($p);
917 $np = s2p($md5);
918 $delete_link_code = jirafeau_gen_random(5);
919
920 /* File already exist ? */
921 if (!file_exists(VAR_FILES . $np)) {
922 @mkdir(VAR_FILES . $np, 0755, true);
923 }
924 if (!file_exists(VAR_FILES . $np . $md5)) {
925 rename($p, VAR_FILES . $np . $md5);
926 }
927
928 /* Increment or create count file. */
929 $counter = 0;
930 if (file_exists(VAR_FILES . $np . $md5 . '_count')) {
931 $content = file(VAR_FILES . $np . $md5. '_count');
932 $counter = trim($content[0]);
933 }
934 $counter++;
935 $handle = fopen(VAR_FILES . $np . $md5. '_count', 'w');
936 fwrite($handle, $counter);
937 fclose($handle);
938
939 /* Create link. */
940 $link_tmp_name = VAR_LINKS . $md5 . rand(0, 10000) . '.tmp';
941 $handle = fopen($link_tmp_name, 'w');
942 fwrite($handle,
943 $a['file_name'] . NL . $a['mime_type'] . NL . $size . NL .
944 $a['key'] . NL . $a['time'] . NL . $md5 . NL . $a['onetime'] . NL .
945 time() . NL . $a['ip'] . NL . $delete_link_code . NL . ($crypted ? 'C' : 'O'));
946 fclose($handle);
947 $md5_link = substr(base_16_to_64(md5_file($link_tmp_name)), 0, $link_name_length);
948 $l = s2p("$md5_link");
949 if (!@mkdir(VAR_LINKS . $l, 0755, true) ||
950 !rename($link_tmp_name, VAR_LINKS . $l . $md5_link)) {
951 echo "Error";
952 }
953
954 /* Clean async upload. */
955 jirafeau_async_delete($ref);
956 return $md5_link . NL . $delete_link_code . NL . urlencode($crypt_key);
957 }
958
959 function jirafeau_crypt_create_iv($base, $size)
960 {
961 $iv = '';
962 while (strlen($iv) < $size) {
963 $iv = $iv . $base;
964 }
965 $iv = substr($iv, 0, $size);
966 return $iv;
967 }
968
969 /**
970 * Crypt file and returns decrypt key.
971 * @param $fp_src file path to the file to crypt.
972 * @param $fp_dst file path to the file to write crypted file (could be the same).
973 * @return decrypt key composed of the key and the iv separated by a point ('.')
974 */
975 function jirafeau_encrypt_file($fp_src, $fp_dst)
976 {
977 $fs = filesize($fp_src);
978 if ($fs === false || $fs == 0 || !(extension_loaded('mcrypt') == true)) {
979 return '';
980 }
981
982 /* Prepare module. */
983 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
984 /* Generate key. */
985 $crypt_key = jirafeau_gen_random(10);
986 $md5_key = md5($crypt_key);
987 $iv = jirafeau_crypt_create_iv($md5_key, mcrypt_enc_get_iv_size($m));
988 /* Init module. */
989 mcrypt_generic_init($m, $md5_key, $iv);
990 /* Crypt file. */
991 $r = fopen($fp_src, 'r');
992 $w = fopen($fp_dst, 'c');
993 while (!feof($r)) {
994 $enc = mcrypt_generic($m, fread($r, 1024));
995 if (fwrite($w, $enc) === false) {
996 return '';
997 }
998 }
999 fclose($r);
1000 fclose($w);
1001 /* Cleanup. */
1002 mcrypt_generic_deinit($m);
1003 mcrypt_module_close($m);
1004 return $crypt_key;
1005 }
1006
1007 /**
1008 * Decrypt file.
1009 * @param $fp_src file path to the file to decrypt.
1010 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1011 * @param $k string composed of the key and the iv separated by a point ('.')
1012 * @return key used to decrypt. a string of length 0 is returned if failed.
1013 */
1014 function jirafeau_decrypt_file($fp_src, $fp_dst, $k)
1015 {
1016 $fs = filesize($fp_src);
1017 if ($fs === false || $fs == 0 || extension_loaded('mcrypt') == false) {
1018 return false;
1019 }
1020
1021 /* Init module */
1022 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1023 /* Extract key and iv. */
1024 $crypt_key = $k;
1025 $md5_key = md5($crypt_key);
1026 $iv = jirafeau_crypt_create_iv($md5_key, mcrypt_enc_get_iv_size($m));
1027 /* Decrypt file. */
1028 $r = fopen($fp_src, 'r');
1029 $w = fopen($fp_dst, 'c');
1030 while (!feof($r)) {
1031 $dec = mdecrypt_generic($m, fread($r, 1024));
1032 if (fwrite($w, $dec) === false) {
1033 return false;
1034 }
1035 }
1036 fclose($r);
1037 fclose($w);
1038 /* Cleanup. */
1039 mcrypt_generic_deinit($m);
1040 mcrypt_module_close($m);
1041 return true;
1042 }
1043
1044 /**
1045 * Check if Jirafeau is password protected for visitors.
1046 * @return true if Jirafeau is password protected, false otherwise.
1047 */
1048 function jirafeau_has_upload_password($cfg)
1049 {
1050 return count($cfg['upload_password']) > 0;
1051 }
1052
1053 /**
1054 * Challenge password for a visitor.
1055 * @param $password password to be challenged
1056 * @return true if password is valid, false otherwise.
1057 */
1058 function jirafeau_challenge_upload_password($cfg, $password)
1059 {
1060 if (!jirafeau_has_upload_password($cfg)) {
1061 return false;
1062 }
1063 foreach ($cfg['upload_password'] as $p) {
1064 if ($password == $p) {
1065 return true;
1066 }
1067 }
1068 return false;
1069 }
1070
1071 /**
1072 * Test if visitor's IP is authorized to upload.
1073 *
1074 * @param $allowedIpList array of allowed IPs
1075 * @param $challengedIp IP to be challenged
1076 * @return true if IP is authorized, false otherwise.
1077 */
1078 function jirafeau_challenge_upload_ip($allowedIpList, $challengedIp)
1079 {
1080 // skip if list is empty = all IPs allowed
1081 if (count($allowedIpList) == 0) {
1082 return true;
1083 }
1084 // test given IP against each allowed IP
1085 foreach ($allowedIpList as $i) {
1086 if ($i == $challengedIp) {
1087 return true;
1088 }
1089 // CIDR test for IPv4 only.
1090 if (strpos($i, '/') !== false) {
1091 list($subnet, $mask) = explode('/', $i);
1092 if ((ip2long($challengedIp) & ~((1 << (32 - $mask)) - 1)) == ip2long($subnet)) {
1093 return true;
1094 }
1095 }
1096 }
1097 return false;
1098 }
1099
1100 /**
1101 * Test if visitor's IP is authorized or password is supplied and authorized
1102 * @param $ip IP to be challenged
1103 * @param $password password to be challenged
1104 * @return true if access is valid, false otherwise.
1105 */
1106 function jirafeau_challenge_upload ($cfg, $ip, $password)
1107 {
1108 // Allow if no ip restrictaion and no password restriction
1109 if ((count ($cfg['upload_ip']) == 0) and (count ($cfg['upload_password']) == 0)) {
1110 return true;
1111 }
1112
1113 // Allow if ip is in array
1114 foreach ($cfg['upload_ip'] as $i) {
1115 if ($i == $ip) {
1116 return true;
1117 }
1118 // CIDR test for IPv4 only.
1119 if (strpos ($i, '/') !== false)
1120 {
1121 list ($subnet, $mask) = explode('/', $i);
1122 if ((ip2long ($ip) & ~((1 << (32 - $mask)) - 1) ) == ip2long ($subnet)) {
1123 return true;
1124 }
1125 }
1126 }
1127 if (!jirafeau_has_upload_password($cfg)) {
1128 return false;
1129 }
1130
1131 foreach ($cfg['upload_password'] as $p) {
1132 if ($password == $p) {
1133 return true;
1134 }
1135 }
1136 return false;
1137 }
1138
1139 /** Tell if we have some HTTP headers generated by a proxy */
1140 function has_http_forwarded()
1141 {
1142 return
1143 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1144 !empty($_SERVER['http_X_forwarded_for']);
1145 }
1146
1147 /**
1148 * Generate IP list from HTTP headers generated by a proxy
1149 * @return array of IP strings
1150 */
1151 function get_ip_list_http_forwarded()
1152 {
1153 $ip_list = array();
1154 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1155 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1156 if ($l === false) {
1157 return array();
1158 }
1159 foreach ($l as $ip) {
1160 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1161 }
1162 }
1163 if (!empty($_SERVER['http_X_forwarded_for'])) {
1164 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1165 foreach ($l as $ip) {
1166 // Separate IP from port
1167 $ipa = explode(':', $ip);
1168 if ($ipa === false) {
1169 continue;
1170 }
1171 $ip = $ipa[0];
1172 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1173 }
1174 }
1175 return $ip_list;
1176 }
1177
1178 /**
1179 * Get the ip address of the client from REMOTE_ADDR
1180 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1181 * @returns the client ip address
1182 */
1183 function get_ip_address($cfg)
1184 {
1185 $remote = $_SERVER['REMOTE_ADDR'];
1186 if (count($cfg['proxy_ip']) == 0 || !has_http_forwarded()) {
1187 return $remote;
1188 }
1189
1190 $ip_list = get_ip_list_http_forwarded();
1191 if (count($ip_list) == 0) {
1192 return $remote;
1193 }
1194
1195 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1196 if ($remote != $proxy_ip) {
1197 continue;
1198 }
1199 // Take the last IP (the one which has been set by the defined proxy).
1200 return end($ip_list);
1201 }
1202 return $remote;
1203 }
1204
1205 /**
1206 * Convert hexadecimal string to base64
1207 */
1208 function hex_to_base64($hex)
1209 {
1210 $b = '';
1211 foreach (str_split($hex, 2) as $pair) {
1212 $b .= chr(hexdec($pair));
1213 }
1214 return base64_encode($b);
1215 }
1216
1217 /**
1218 * Replace markers in templates.
1219 *
1220 * Available markers have the scheme "###MARKERNAME###".
1221 *
1222 * @param $content string Template text with markers
1223 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1224 * @return Template with replaced markers
1225 */
1226 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1227 {
1228 $patterns = array(
1229 '/###ORGANISATION###/',
1230 '/###CONTACTPERSON###/',
1231 '/###WEBROOT###/'
1232 );
1233 $replacements = array(
1234 $GLOBALS['cfg']['organisation'],
1235 $GLOBALS['cfg']['contactperson'],
1236 $GLOBALS['cfg']['web_root']
1237 );
1238 $content = preg_replace($patterns, $replacements, $content);
1239
1240 if (true === $htmllinebreaks) {
1241 $content = nl2br($content);
1242 }
1243
1244 return $content;
1245 }

patrick-canterino.de