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

patrick-canterino.de