]> git.p6c8.net - jirafeau.git/blob - lib/functions.php
Merge branch 'lib-minor' into 'master'
[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>' . $l['onetime'] . '</td>';
627 echo '<td>' . strftime ('%c', $l['upload_date']) . '</td>';
628 echo '<td>' . $l['ip'] . '</td>';
629 echo '<td>' .
630 '<form action = "admin.php" method = "post">' .
631 '<input type = "hidden" name = "action" value = "delete_link"/>' .
632 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
633 '<input type = "submit" value = "' . t('Del link') . '" />' .
634 '</form>' .
635 '<form action = "admin.php" method = "post">' .
636 '<input type = "hidden" name = "action" value = "delete_file"/>' .
637 '<input type = "hidden" name = "md5" value = "' . $l['md5'] . '"/>' .
638 '<input type = "submit" value = "' . t('Del file and links') . '" />' .
639 '</form>' .
640 '</td>';
641 echo '</tr>';
642 }
643 }
644 }
645 echo '</table></fieldset>';
646 }
647
648 /**
649 * Clean expired files.
650 * @return number of cleaned files.
651 */
652 function
653 jirafeau_admin_clean ()
654 {
655 $count = 0;
656 /* Get all links files. */
657 $stack = array (VAR_LINKS);
658 while (($d = array_shift ($stack)) && $d != NULL)
659 {
660 $dir = scandir ($d);
661
662 foreach ($dir as $node)
663 {
664 if (strcmp ($node, '.') == 0 || strcmp ($node, '..') == 0 ||
665 preg_match ('/\.tmp/i', "$node"))
666 continue;
667
668 if (is_dir ($d . $node))
669 {
670 /* Push new found directory. */
671 $stack[] = $d . $node . '/';
672 }
673 elseif (is_file ($d . $node))
674 {
675 /* Read link informations. */
676 $l = jirafeau_get_link (basename ($node));
677 if (!count ($l))
678 continue;
679 $p = s2p ($l['md5']);
680 if ($l['time'] > 0 && $l['time'] < time () || // expired
681 !file_exists (VAR_FILES . $p . $l['md5']) || // invalid
682 !file_exists (VAR_FILES . $p . $l['md5'] . '_count')) // invalid
683 {
684 jirafeau_delete_link ($node);
685 $count++;
686 }
687 }
688 }
689 }
690 return $count;
691 }
692
693
694 /**
695 * Clean old async transferts.
696 * @return number of cleaned files.
697 */
698 function
699 jirafeau_admin_clean_async ()
700 {
701 $count = 0;
702 /* Get all links files. */
703 $stack = array (VAR_ASYNC);
704 while (($d = array_shift ($stack)) && $d != NULL)
705 {
706 $dir = scandir ($d);
707
708 foreach ($dir as $node)
709 {
710 if (strcmp ($node, '.') == 0 || strcmp ($node, '..') == 0 ||
711 preg_match ('/\.tmp/i', "$node"))
712 continue;
713
714 if (is_dir ($d . $node))
715 {
716 /* Push new found directory. */
717 $stack[] = $d . $node . '/';
718 }
719 elseif (is_file ($d . $node))
720 {
721 /* Read async informations. */
722 $a = jirafeau_get_async_ref (basename ($node));
723 if (!count ($a))
724 continue;
725 /* Delete transferts older than 1 hour. */
726 if (date ('U') - $a['last_edited'] > 3600)
727 {
728 jirafeau_async_delete (basename ($node));
729 $count++;
730 }
731 }
732 }
733 }
734 return $count;
735 }
736 /**
737 * Read async transfert informations
738 * @return array containing informations.
739 */
740 function
741 jirafeau_get_async_ref ($ref)
742 {
743 $out = array ();
744 $refinfos = VAR_ASYNC . s2p ("$ref") . "$ref";
745
746 if (!file_exists ($refinfos))
747 return $out;
748
749 $c = file ($refinfos);
750 $out['file_name'] = trim ($c[0]);
751 $out['mime_type'] = trim ($c[1]);
752 $out['key'] = trim ($c[2], NL);
753 $out['time'] = trim ($c[3]);
754 $out['onetime'] = trim ($c[4]);
755 $out['ip'] = trim ($c[5]);
756 $out['last_edited'] = trim ($c[6]);
757 $out['next_code'] = trim ($c[7]);
758 return $out;
759 }
760
761 /**
762 * Delete async transfert informations
763 */
764 function
765 jirafeau_async_delete ($ref)
766 {
767 $p = s2p ("$ref");
768 if (file_exists (VAR_ASYNC . $p . $ref))
769 unlink (VAR_ASYNC . $p . $ref);
770 if (file_exists (VAR_ASYNC . $p . $ref . '_data'))
771 unlink (VAR_ASYNC . $p . $ref . '_data');
772 $parse = VAR_ASYNC . $p;
773 $scan = array();
774 while (file_exists ($parse)
775 && ($scan = scandir ($parse))
776 && count ($scan) == 2 // '.' and '..' folders => empty.
777 && basename ($parse) != basename (VAR_ASYNC))
778 {
779 rmdir ($parse);
780 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
781 }
782 }
783
784 /**
785 * Init a new asynchronous upload.
786 * @param $finename Name of the file to send
787 * @param $one_time One time upload parameter
788 * @param $key eventual password (or blank)
789 * @param $time time limit
790 * @param $ip ip address of the client
791 * @return a string containing a temporary reference followed by a code or the string 'Error'
792 */
793 function
794 jirafeau_async_init ($filename, $type, $one_time, $key, $time, $ip)
795 {
796 $res = 'Error';
797
798 /* Create temporary folder. */
799 $ref;
800 $p;
801 $code = jirafeau_gen_random (4);
802 do
803 {
804 $ref = jirafeau_gen_random (32);
805 $p = VAR_ASYNC . s2p ($ref);
806 } while (file_exists ($p));
807 @mkdir ($p, 0755, true);
808 if (!file_exists ($p))
809 {
810 echo 'Error';
811 return;
812 }
813
814 /* md5 password or empty */
815 $password = '';
816 if (!empty ($key))
817 $password = md5 ($key);
818
819 /* Store informations. */
820 $p .= $ref;
821 $handle = fopen ($p, 'w');
822 fwrite ($handle,
823 str_replace (NL, '', trim ($filename)) . NL .
824 str_replace (NL, '', trim ($type)) . NL . $password . NL .
825 $time . NL . ($one_time ? 'O' : 'R') . NL . $ip . NL .
826 date ('U') . NL . $code . NL);
827 fclose ($handle);
828
829 return $ref . NL . $code ;
830 }
831
832 /**
833 * Append a piece of file on the asynchronous upload.
834 * @param $ref asynchronous upload reference
835 * @param $file piece of data
836 * @param $code client code for this operation
837 * @param $max_file_size maximum allowed file size
838 * @return a string containing a next code to use or the string "Error"
839 */
840 function
841 jirafeau_async_push ($ref, $data, $code, $max_file_size)
842 {
843 /* Get async infos. */
844 $a = jirafeau_get_async_ref ($ref);
845
846 /* Check some errors. */
847 if (count ($a) == 0
848 || $a['next_code'] != "$code"
849 || empty ($data['tmp_name'])
850 || !is_uploaded_file ($data['tmp_name']))
851 return 'Error';
852
853 $p = s2p ($ref);
854
855 /* File path. */
856 $r_path = $data['tmp_name'];
857 $w_path = VAR_ASYNC . $p . $ref . '_data';
858
859 /* Check that file size is not above upload limit. */
860 if ($max_file_size > 0 &&
861 filesize ($r_path) + filesize ($w_path) > $max_file_size * 1024 * 1024)
862 {
863 jirafeau_async_delete ($ref);
864 return 'Error';
865 }
866
867 /* Concatenate data. */
868 $r = fopen ($r_path, 'r');
869 $w = fopen ($w_path, 'a');
870 while (!feof ($r))
871 {
872 if (fwrite ($w, fread ($r, 1024)) === false)
873 {
874 fclose ($r);
875 fclose ($w);
876 jirafeau_async_delete ($ref);
877 return 'Error';
878 }
879 }
880 fclose ($r);
881 fclose ($w);
882 unlink ($r_path);
883
884 /* Update async file. */
885 $code = jirafeau_gen_random (4);
886 $handle = fopen (VAR_ASYNC . $p . $ref, 'w');
887 fwrite ($handle,
888 $a['file_name'] . NL. $a['mime_type'] . NL. $a['key'] . NL .
889 $a['time'] . NL . $a['onetime'] . NL . $a['ip'] . NL .
890 date ('U') . NL . $code . NL);
891 fclose ($handle);
892 return $code;
893 }
894
895 /**
896 * Finalyze an asynchronous upload.
897 * @param $ref asynchronous upload reference
898 * @param $code client code for this operation
899 * @param $crypt boolean asking to crypt or not
900 * @param $link_name_length link name length
901 * @return a string containing the download reference followed by a delete code or the string 'Error'
902 */
903 function
904 jirafeau_async_end ($ref, $code, $crypt, $link_name_length)
905 {
906 /* Get async infos. */
907 $a = jirafeau_get_async_ref ($ref);
908 if (count ($a) == 0
909 || $a['next_code'] != "$code")
910 return "Error";
911
912 /* Generate link infos. */
913 $p = VAR_ASYNC . s2p ($ref) . $ref . "_data";
914 if (!file_exists($p))
915 return 'Error';
916
917 $crypted = false;
918 $crypt_key = '';
919 if ($crypt == true && extension_loaded('mcrypt') == true)
920 {
921 $crypt_key = jirafeau_encrypt_file ($p, $p);
922 if (strlen($crypt_key) > 0)
923 $crypted = true;
924 }
925
926 $md5 = md5_file ($p);
927 $size = filesize($p);
928 $np = s2p ($md5);
929 $delete_link_code = jirafeau_gen_random (5);
930
931 /* File already exist ? */
932 if (!file_exists (VAR_FILES . $np))
933 @mkdir (VAR_FILES . $np, 0755, true);
934 if (!file_exists (VAR_FILES . $np . $md5))
935 rename ($p, VAR_FILES . $np . $md5);
936
937 /* Increment or create count file. */
938 $counter = 0;
939 if (file_exists (VAR_FILES . $np . $md5 . '_count'))
940 {
941 $content = file (VAR_FILES . $np . $md5. '_count');
942 $counter = trim ($content[0]);
943 }
944 $counter++;
945 $handle = fopen (VAR_FILES . $np . $md5. '_count', 'w');
946 fwrite ($handle, $counter);
947 fclose ($handle);
948
949 /* Create link. */
950 $link_tmp_name = VAR_LINKS . $md5 . rand (0, 10000) . '.tmp';
951 $handle = fopen ($link_tmp_name, 'w');
952 fwrite ($handle,
953 $a['file_name'] . NL . $a['mime_type'] . NL . $size . NL .
954 $a['key'] . NL . $a['time'] . NL . $md5 . NL . $a['onetime'] . NL .
955 date ('U') . NL . $a['ip'] . NL . $delete_link_code . NL . ($crypted ? 'C' : 'O'));
956 fclose ($handle);
957 $md5_link = substr(base_16_to_64 (md5_file ($link_tmp_name)), 0, $link_name_length);
958 $l = s2p ("$md5_link");
959 if (!@mkdir (VAR_LINKS . $l, 0755, true) ||
960 !rename ($link_tmp_name, VAR_LINKS . $l . $md5_link))
961 echo "Error";
962
963 /* Clean async upload. */
964 jirafeau_async_delete ($ref);
965 return $md5_link . NL . $delete_link_code . NL . urlencode($crypt_key);
966 }
967
968 function
969 jirafeau_crypt_create_iv($base, $size)
970 {
971 $iv = '';
972 while (strlen ($iv) < $size)
973 $iv = $iv . $base;
974 $iv = substr($iv, 0, $size);
975 return $iv;
976 }
977
978 /**
979 * Crypt file and returns decrypt key.
980 * @param $fp_src file path to the file to crypt.
981 * @param $fp_dst file path to the file to write crypted file (could be the same).
982 * @return decrypt key composed of the key and the iv separated by a point ('.')
983 */
984 function
985 jirafeau_encrypt_file ($fp_src, $fp_dst)
986 {
987 $fs = filesize ($fp_src);
988 if ($fs === false || $fs == 0 || !(extension_loaded('mcrypt') == true))
989 return '';
990
991 /* Prepare module. */
992 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
993 /* Generate key. */
994 $crypt_key = jirafeau_gen_random (10);
995 $md5_key = md5($crypt_key);
996 $iv = jirafeau_crypt_create_iv ($md5_key, mcrypt_enc_get_iv_size($m));
997 /* Init module. */
998 mcrypt_generic_init($m, $md5_key, $iv);
999 /* Crypt file. */
1000 $r = fopen ($fp_src, 'r');
1001 $w = fopen ($fp_dst, 'c');
1002 while (!feof ($r))
1003 {
1004 $enc = mcrypt_generic($m, fread ($r, 1024));
1005 if (fwrite ($w, $enc) === false)
1006 return '';
1007 }
1008 fclose ($r);
1009 fclose ($w);
1010 /* Cleanup. */
1011 mcrypt_generic_deinit($m);
1012 mcrypt_module_close($m);
1013 return $crypt_key;
1014 }
1015
1016 /**
1017 * Decrypt file.
1018 * @param $fp_src file path to the file to decrypt.
1019 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1020 * @param $k string composed of the key and the iv separated by a point ('.')
1021 * @return key used to decrypt. a string of length 0 is returned if failed.
1022 */
1023 function
1024 jirafeau_decrypt_file ($fp_src, $fp_dst, $k)
1025 {
1026 $fs = filesize ($fp_src);
1027 if ($fs === false || $fs == 0 || extension_loaded('mcrypt') == false)
1028 return false;
1029
1030 /* Init module */
1031 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1032 /* Extract key and iv. */
1033 $crypt_key = $k;
1034 $md5_key = md5($crypt_key);
1035 $iv = jirafeau_crypt_create_iv ($md5_key, mcrypt_enc_get_iv_size($m));
1036 /* Decrypt file. */
1037 $r = fopen ($fp_src, 'r');
1038 $w = fopen ($fp_dst, 'c');
1039 while (!feof ($r))
1040 {
1041 $dec = mdecrypt_generic($m, fread ($r, 1024));
1042 if (fwrite ($w, $dec) === false)
1043 return false;
1044 }
1045 fclose ($r);
1046 fclose ($w);
1047 /* Cleanup. */
1048 mcrypt_generic_deinit($m);
1049 mcrypt_module_close($m);
1050 return true;
1051 }
1052
1053 /**
1054 * Check if Jirafeau is password protected for visitors.
1055 * @return true if Jirafeau is password protected, false otherwise.
1056 */
1057 function
1058 jirafeau_has_upload_password ($cfg)
1059 {
1060 return count ($cfg['upload_password']) > 0;
1061 }
1062
1063 /**
1064 * Challenge password for a visitor.
1065 * @param $password password to be challenged
1066 * @return true if password is valid, false otherwise.
1067 */
1068 function
1069 jirafeau_challenge_upload_password ($cfg, $password)
1070 {
1071 if (!jirafeau_has_upload_password($cfg))
1072 return false;
1073 forEach ($cfg['upload_password'] as $p)
1074 if ($password == $p)
1075 return true;
1076 return false;
1077 }
1078
1079 /**
1080 * Test if visitor's IP is authorized to upload.
1081 * @param $ip IP to be challenged
1082 * @return true if IP is authorized, false otherwise.
1083 */
1084 function
1085 jirafeau_challenge_upload_ip ($cfg, $ip)
1086 {
1087 if (count ($cfg['upload_ip']) == 0)
1088 return true;
1089 forEach ($cfg['upload_ip'] as $i)
1090 {
1091 if ($i == $ip)
1092 return true;
1093 // CIDR test for IPv4 only.
1094 if (strpos ($i, '/') !== false)
1095 {
1096 list ($subnet, $mask) = explode('/', $i);
1097 if ((ip2long ($ip) & ~((1 << (32 - $mask)) - 1) ) == ip2long ($subnet))
1098 return true;
1099 }
1100 }
1101 return false;
1102 }
1103
1104 /** Tell if we have some HTTP headers generated by a proxy */
1105 function
1106 has_http_forwarded()
1107 {
1108 return
1109 !empty ($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1110 !empty ($_SERVER['http_X_forwarded_for']);
1111 }
1112
1113 /**
1114 * Generate IP list from HTTP headers generated by a proxy
1115 * @return array of IP strings
1116 */
1117 function
1118 get_ip_list_http_forwarded()
1119 {
1120 $ip_list = array();
1121 if (!empty ($_SERVER['HTTP_X_FORWARDED_FOR']))
1122 {
1123 $l = explode (',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1124 foreach ($l as $ip)
1125 array_push ($ip_list, preg_replace ('/\s+/', '', $ip));
1126 }
1127 if (!empty ($_SERVER['http_X_forwarded_for']))
1128 {
1129 $l = explode (',', $_SERVER['http_X_forwarded_for']);
1130 foreach ($l as $ip)
1131 {
1132 // Separate IP from port
1133 $ip = explode (':', $ip)[0];
1134 array_push ($ip_list, preg_replace ('/\s+/', '', $ip));
1135 }
1136 }
1137 return $ip_list;
1138 }
1139
1140 /**
1141 * Get the ip address of the client from REMOTE_ADDR
1142 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1143 * @returns the client ip address
1144 */
1145 function
1146 get_ip_address($cfg)
1147 {
1148 $remote = $_SERVER['REMOTE_ADDR'];
1149 if (count ($cfg['proxy_ip']) == 0 || !has_http_forwarded ())
1150 return $remote;
1151
1152 $ip_list = get_ip_list_http_forwarded ();
1153 if (count ($ip_list) == 0)
1154 return $remote;
1155
1156 foreach ($cfg['proxy_ip'] as $proxy_ip)
1157 {
1158 if ($remote != $proxy_ip)
1159 continue;
1160 // Take the last IP (the one which has been set by the defined proxy).
1161 return end ($ip_list);
1162 }
1163 return $remote;
1164 }
1165
1166 /**
1167 * Convert hexadecimal string to base64
1168 */
1169 function hex_to_base64($hex)
1170 {
1171 $b = '';
1172 foreach (str_split ($hex, 2) as $pair)
1173 $b .= chr (hexdec ($pair));
1174 return base64_encode ($b);
1175 }
1176
1177 /**
1178 * Read alias informations
1179 * @return array containing informations.
1180 */
1181 function
1182 jirafeau_get_alias ($hash)
1183 {
1184 $out = array ();
1185 $link = VAR_ALIAS . s2p ("$hash") . $hash;
1186
1187 if (!file_exists ($link))
1188 return $out;
1189
1190 $c = file ($link);
1191 $out['md5_password'] = trim ($c[0]);
1192 $out['ip'] = trim ($c[1]);
1193 $out['update_date'] = trim ($c[2]);
1194 $out['destination'] = trim ($c[3], NL);
1195
1196 return $out;
1197 }
1198
1199 /** Create an alias to a jirafeau's link.
1200 * @param $alias alias name
1201 * @param $destination reference of the destination
1202 * @param $password password to protect alias
1203 * @param $ip client's IP
1204 * @return a string containing the edit code of the alias or the string "Error"
1205 */
1206 function
1207 jirafeau_alias_create ($alias, $destination, $password, $ip)
1208 {
1209 /* Check that alias and password are long enough. */
1210 if (strlen ($alias) < 8 ||
1211 strlen ($alias) > 32 ||
1212 strlen ($password) < 8 ||
1213 strlen ($password) > 32)
1214 return 'Error';
1215
1216 /* Check that destination exists. */
1217 $l = jirafeau_get_link ($destination);
1218 if (!count ($l))
1219 return 'Error';
1220
1221 /* Check that alias does not already exists. */
1222 $alias = md5 ($alias);
1223 $p = VAR_ALIAS . s2p ($alias);
1224 if (file_exists ($p))
1225 return 'Error';
1226
1227 /* Create alias folder. */
1228 @mkdir ($p, 0755, true);
1229 if (!file_exists ($p))
1230 return 'Error';
1231
1232 /* Generate password. */
1233 $md5_password = md5 ($password);
1234
1235 /* Store informations. */
1236 $p .= $alias;
1237 $handle = fopen ($p, 'w');
1238 fwrite ($handle,
1239 $md5_password . NL .
1240 $ip . NL .
1241 date ('U') . NL .
1242 $destination . NL);
1243 fclose ($handle);
1244
1245 return 'Ok';
1246 }
1247
1248 /** Update an alias.
1249 * @param $alias alias to update
1250 * @param $destination reference of the new destination
1251 * @param $password password to protect alias
1252 * @param $new_password optional new password to protect alias
1253 * @param $ip client's IP
1254 * @return "Ok" or "Error" string
1255 */
1256 function
1257 jirafeau_alias_update ($alias, $destination, $password,
1258 $new_password, $ip)
1259 {
1260 $alias = md5 ($alias);
1261 /* Check that alias exits. */
1262 $a = jirafeau_get_alias ($alias);
1263 if (!count ($a))
1264 return 'Error';
1265
1266 /* Check that destination exists. */
1267 $l = jirafeau_get_link ($a["destination"]);
1268 if (!count ($l))
1269 return 'Error';
1270
1271 /* Check password. */
1272 if ($a["md5_password"] != md5 ($password))
1273 return 'Error';
1274
1275 $p = $a['md5_password'];
1276 if (strlen ($new_password) >= 8 &&
1277 strlen ($new_password) <= 32)
1278 $p = md5 ($new_password);
1279 else if (strlen ($new_password) > 0)
1280 return 'Error';
1281
1282 /* Rewrite informations. */
1283 $p = VAR_ALIAS . s2p ($alias) . $alias;
1284 $handle = fopen ($p, 'w');
1285 fwrite ($handle,
1286 $p . NL .
1287 $ip . NL .
1288 date ('U') . NL .
1289 $destination . NL);
1290 fclose ($handle);
1291 return 'Ok';
1292 }
1293
1294 /** Get an alias.
1295 * @param $alias alias to get
1296 * @return alias destination or "Error" string
1297 */
1298 function
1299 jirafeau_alias_get ($alias)
1300 {
1301 $alias = md5 ($alias);
1302 /* Check that alias exits. */
1303 $a = jirafeau_get_alias ($alias);
1304 if (!count ($a))
1305 return 'Error';
1306
1307 return $a['destination'];
1308 }
1309
1310 function
1311 jirafeau_clean_rm_alias ($alias)
1312 {
1313 $p = s2p ("$alias");
1314 if (file_exists (VAR_ALIAS . $p . $alias))
1315 unlink (VAR_ALIAS . $p . $alias);
1316 $parse = VAR_ALIAS . $p;
1317 $scan = array();
1318 while (file_exists ($parse)
1319 && ($scan = scandir ($parse))
1320 && count ($scan) == 2 // '.' and '..' folders => empty.
1321 && basename ($parse) != basename (VAR_ALIAS))
1322 {
1323 rmdir ($parse);
1324 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
1325 }
1326 }
1327
1328 /** Delete an alias.
1329 * @param $alias alias to delete
1330 * @param $password password to protect alias
1331 * @return "Ok" or "Error" string
1332 */
1333 function
1334 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