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

patrick-canterino.de