]> git.p6c8.net - jirafeau.git/blob - lib/functions.php
[FEATURE] Contribution Guide: Declare PSR-2 Coding Style
[jirafeau.git] / lib / functions.php
1 <?php
2 /*
3 * Jirafeau, your web file repository
4 * Copyright (C) 2008 Julien "axolotl" BERNARD <axolotl@magieeternelle.org>
5 * Copyright (C) 2015 Jerome Jutteau <j.jutteau@gmail.com>
6 * Copyright (C) 2015 Nicola Spanti (RyDroid) <dev@nicola-spanti.info>
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU Affero General Public License as
10 * published by the Free Software Foundation, either version 3 of the
11 * License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Affero General Public License for more details.
17 *
18 * You should have received a copy of the GNU Affero General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22 /**
23 * Transform a string in a path by seperating each letters by a '/'.
24 * @return path finishing with a '/'
25 */
26 function s2p($s)
27 {
28 $p = '';
29 for ($i = 0; $i < strlen($s); $i++) {
30 $p .= $s{$i} . '/';
31 }
32 return $p;
33 }
34
35 /**
36 * Convert base 16 to base 64
37 * @returns A string based on 64 characters (0-9, a-z, A-Z, "-" and "_")
38 */
39 function base_16_to_64($num)
40 {
41 $m = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_';
42 $hex2bin = array('0000', # 0
43 '0001', # 1
44 '0010', # 2
45 '0011', # 3
46 '0100', # 4
47 '0101', # 5
48 '0110', # 6
49 '0111', # 7
50 '1000', # 8
51 '1001', # 9
52 '1010', # a
53 '1011', # b
54 '1100', # c
55 '1101', # d
56 '1110', # e
57 '1111'); # f
58 $o = '';
59 $b = '';
60 $i = 0;
61 # Convert long hex string to bin.
62 $size = strlen($num);
63 for ($i = 0; $i < $size; $i++) {
64 $b .= $hex2bin{hexdec($num{$i})};
65 }
66 # Convert long bin to base 64.
67 $size *= 4;
68 for ($i = $size - 6; $i >= 0; $i -= 6) {
69 $o = $m{bindec(substr($b, $i, 6))} . $o;
70 }
71 # Some few bits remaining ?
72 if ($i < 0 && $i > -6) {
73 $o = $m{bindec(substr($b, 0, $i + 6))} . $o;
74 }
75 return $o;
76 }
77
78 /**
79 * Generate a random code.
80 * @param $l code length
81 * @return random code.
82 */
83 function jirafeau_gen_random($l)
84 {
85 if ($l <= 0) {
86 return 42;
87 }
88
89 $code="";
90 for ($i = 0; $i < $l; $i++) {
91 $code .= dechex(rand(0, 15));
92 }
93
94 return $code;
95 }
96
97 function is_ssl()
98 {
99 if (isset($_SERVER['HTTPS'])) {
100 if ('on' == strtolower($_SERVER['HTTPS']) ||
101 '1' == $_SERVER['HTTPS']) {
102 return true;
103 }
104 } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
105 return true;
106 } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
107 if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
108 return true;
109 }
110 }
111 return false;
112 }
113
114 function jirafeau_human_size($octets)
115 {
116 $u = array('B', 'KB', 'MB', 'GB', 'TB');
117 $o = max($octets, 0);
118 $p = min(floor(($o ? log($o) : 0) / log(1024)), count($u) - 1);
119 $o /= pow(1024, $p);
120 return round($o, 1) . $u[$p];
121 }
122
123 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 /** Tell if we have some HTTP headers generated by a proxy */
1083 function has_http_forwarded()
1084 {
1085 return
1086 !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1087 !empty($_SERVER['http_X_forwarded_for']);
1088 }
1089
1090 /**
1091 * Generate IP list from HTTP headers generated by a proxy
1092 * @return array of IP strings
1093 */
1094 function get_ip_list_http_forwarded()
1095 {
1096 $ip_list = array();
1097 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1098 $l = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1099 if ($l === false) {
1100 return array();
1101 }
1102 foreach ($l as $ip) {
1103 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1104 }
1105 }
1106 if (!empty($_SERVER['http_X_forwarded_for'])) {
1107 $l = explode(',', $_SERVER['http_X_forwarded_for']);
1108 foreach ($l as $ip) {
1109 // Separate IP from port
1110 $ipa = explode(':', $ip);
1111 if ($ipa === false) {
1112 continue;
1113 }
1114 $ip = $ipa[0];
1115 array_push($ip_list, preg_replace('/\s+/', '', $ip));
1116 }
1117 }
1118 return $ip_list;
1119 }
1120
1121 /**
1122 * Get the ip address of the client from REMOTE_ADDR
1123 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1124 * @returns the client ip address
1125 */
1126 function get_ip_address($cfg)
1127 {
1128 $remote = $_SERVER['REMOTE_ADDR'];
1129 if (count($cfg['proxy_ip']) == 0 || !has_http_forwarded()) {
1130 return $remote;
1131 }
1132
1133 $ip_list = get_ip_list_http_forwarded();
1134 if (count($ip_list) == 0) {
1135 return $remote;
1136 }
1137
1138 foreach ($cfg['proxy_ip'] as $proxy_ip) {
1139 if ($remote != $proxy_ip) {
1140 continue;
1141 }
1142 // Take the last IP (the one which has been set by the defined proxy).
1143 return end($ip_list);
1144 }
1145 return $remote;
1146 }
1147
1148 /**
1149 * Convert hexadecimal string to base64
1150 */
1151 function hex_to_base64($hex)
1152 {
1153 $b = '';
1154 foreach (str_split($hex, 2) as $pair) {
1155 $b .= chr(hexdec($pair));
1156 }
1157 return base64_encode($b);
1158 }
1159
1160 /**
1161 * Read alias informations
1162 * @return array containing informations.
1163 */
1164 function jirafeau_get_alias($hash)
1165 {
1166 $out = array();
1167 $link = VAR_ALIAS . s2p("$hash") . $hash;
1168
1169 if (!file_exists($link)) {
1170 return $out;
1171 }
1172
1173 $c = file($link);
1174 $out['md5_password'] = trim($c[0]);
1175 $out['ip'] = trim($c[1]);
1176 $out['update_date'] = trim($c[2]);
1177 $out['destination'] = trim($c[3], NL);
1178
1179 return $out;
1180 }
1181
1182 /** Create an alias to a jirafeau's link.
1183 * @param $alias alias name
1184 * @param $destination reference of the destination
1185 * @param $password password to protect alias
1186 * @param $ip client's IP
1187 * @return a string containing the edit code of the alias or the string "Error"
1188 */
1189 function jirafeau_alias_create($alias, $destination, $password, $ip)
1190 {
1191 /* Check that alias and password are long enough. */
1192 if (strlen($alias) < 8 ||
1193 strlen($alias) > 32 ||
1194 strlen($password) < 8 ||
1195 strlen($password) > 32) {
1196 return 'Error';
1197 }
1198
1199 /* Check that destination exists. */
1200 $l = jirafeau_get_link($destination);
1201 if (!count($l)) {
1202 return 'Error';
1203 }
1204
1205 /* Check that alias does not already exists. */
1206 $alias = md5($alias);
1207 $p = VAR_ALIAS . s2p($alias);
1208 if (file_exists($p)) {
1209 return 'Error';
1210 }
1211
1212 /* Create alias folder. */
1213 @mkdir($p, 0755, true);
1214 if (!file_exists($p)) {
1215 return 'Error';
1216 }
1217
1218 /* Generate password. */
1219 $md5_password = md5($password);
1220
1221 /* Store informations. */
1222 $p .= $alias;
1223 $handle = fopen($p, 'w');
1224 fwrite($handle,
1225 $md5_password . NL .
1226 $ip . NL .
1227 time() . NL .
1228 $destination . NL);
1229 fclose($handle);
1230
1231 return 'Ok';
1232 }
1233
1234 /** Update an alias.
1235 * @param $alias alias to update
1236 * @param $destination reference of the new destination
1237 * @param $password password to protect alias
1238 * @param $new_password optional new password to protect alias
1239 * @param $ip client's IP
1240 * @return "Ok" or "Error" string
1241 */
1242 function jirafeau_alias_update($alias, $destination, $password,
1243 $new_password, $ip)
1244 {
1245 $alias = md5($alias);
1246 /* Check that alias exits. */
1247 $a = jirafeau_get_alias($alias);
1248 if (!count($a)) {
1249 return 'Error';
1250 }
1251
1252 /* Check that destination exists. */
1253 $l = jirafeau_get_link($a["destination"]);
1254 if (!count($l)) {
1255 return 'Error';
1256 }
1257
1258 /* Check password. */
1259 if ($a["md5_password"] != md5($password)) {
1260 return 'Error';
1261 }
1262
1263 $p = $a['md5_password'];
1264 if (strlen($new_password) >= 8 &&
1265 strlen($new_password) <= 32) {
1266 $p = md5($new_password);
1267 } elseif (strlen($new_password) > 0) {
1268 return 'Error';
1269 }
1270
1271 /* Rewrite informations. */
1272 $p = VAR_ALIAS . s2p($alias) . $alias;
1273 $handle = fopen($p, 'w');
1274 fwrite($handle,
1275 $p . NL .
1276 $ip . NL .
1277 time() . NL .
1278 $destination . NL);
1279 fclose($handle);
1280 return 'Ok';
1281 }
1282
1283 /** Get an alias.
1284 * @param $alias alias to get
1285 * @return alias destination or "Error" string
1286 */
1287 function jirafeau_alias_get($alias)
1288 {
1289 $alias = md5($alias);
1290 /* Check that alias exits. */
1291 $a = jirafeau_get_alias($alias);
1292 if (!count($a)) {
1293 return 'Error';
1294 }
1295
1296 return $a['destination'];
1297 }
1298
1299 function jirafeau_clean_rm_alias($alias)
1300 {
1301 $p = s2p("$alias");
1302 if (file_exists(VAR_ALIAS . $p . $alias)) {
1303 unlink(VAR_ALIAS . $p . $alias);
1304 }
1305 $parse = VAR_ALIAS . $p;
1306 $scan = array();
1307 while (file_exists($parse)
1308 && ($scan = scandir($parse))
1309 && count($scan) == 2 // '.' and '..' folders => empty.
1310 && basename($parse) != basename(VAR_ALIAS)) {
1311 rmdir($parse);
1312 $parse = substr($parse, 0, strlen($parse) - strlen(basename($parse)) - 1);
1313 }
1314 }
1315
1316 /** Delete an alias.
1317 * @param $alias alias to delete
1318 * @param $password password to protect alias
1319 * @return "Ok" or "Error" string
1320 */
1321 function jirafeau_alias_delete($alias, $password)
1322 {
1323 $alias = md5($alias);
1324 /* Check that alias exits. */
1325 $a = jirafeau_get_alias($alias);
1326 if (!count($a)) {
1327 return "Error";
1328 }
1329
1330 /* Check password. */
1331 if ($a["md5_password"] != md5($password)) {
1332 return 'Error';
1333 }
1334
1335 jirafeau_clean_rm_alias($alias);
1336 return 'Ok';
1337 }
1338
1339 /**
1340 * Replace markers in templates.
1341 *
1342 * Available markers have the scheme "###MARKERNAME###".
1343 *
1344 * @param $content string Template text with markers
1345 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1346 * @return Template with replaced markers
1347 */
1348 function jirafeau_replace_markers($content, $htmllinebreaks = false)
1349 {
1350 $patterns = array(
1351 '/###ORGANISATION###/',
1352 '/###CONTACTPERSON###/',
1353 '/###WEBROOT###/'
1354 );
1355 $replacements = array(
1356 $GLOBALS['cfg']['organisation'],
1357 $GLOBALS['cfg']['contactperson'],
1358 $GLOBALS['cfg']['web_root']
1359 );
1360 $content = preg_replace($patterns, $replacements, $content);
1361
1362 if (true === $htmllinebreaks) {
1363 $content = nl2br($content);
1364 }
1365
1366 return $content;
1367 }

patrick-canterino.de