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

patrick-canterino.de