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

patrick-canterino.de