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

patrick-canterino.de