]> git.p6c8.net - jirafeau.git/blob - lib/functions.php
add some readme
[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 *
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 }
102 return false;
103 }
104
105 function
106 jirafeau_human_size ($octets)
107 {
108 $u = array ('B', 'KB', 'MB', 'GB', 'TB');
109 $o = max ($octets, 0);
110 $p = min (floor (($o ? log ($o) : 0) / log (1024)), count ($u) - 1);
111 $o /= pow (1024, $p);
112 return round ($o, 1) . $u[$p];
113 }
114
115 function
116 jirafeau_clean_rm_link ($link)
117 {
118 $p = s2p ("$link");
119 if (file_exists (VAR_LINKS . $p . $link))
120 unlink (VAR_LINKS . $p . $link);
121 $parse = VAR_LINKS . $p;
122 $scan = array();
123 while (file_exists ($parse)
124 && ($scan = scandir ($parse))
125 && count ($scan) == 2 // '.' and '..' folders => empty.
126 && basename ($parse) != basename (VAR_LINKS))
127 {
128 rmdir ($parse);
129 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
130 }
131 }
132
133 function
134 jirafeau_clean_rm_file ($md5)
135 {
136 $p = s2p ("$md5");
137 $f = VAR_FILES . $p . $md5;
138 if (file_exists ($f) && is_file ($f))
139 unlink ($f);
140 if (file_exists ($f . '_count') && is_file ($f . '_count'))
141 unlink ($f . '_count');
142 $parse = VAR_FILES . $p;
143 $scan = array();
144 while (file_exists ($parse)
145 && ($scan = scandir ($parse))
146 && count ($scan) == 2 // '.' and '..' folders => empty.
147 && basename ($parse) != basename (VAR_FILES))
148 {
149 rmdir ($parse);
150 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
151 }
152 }
153
154 /**
155 * transforms a php.ini string representing a value in an integer
156 * @param $value the value from php.ini
157 * @returns an integer for this value
158 */
159 function jirafeau_ini_to_bytes ($value)
160 {
161 $modifier = substr ($value, -1);
162 $bytes = substr ($value, 0, -1);
163 switch (strtoupper ($modifier))
164 {
165 case 'P':
166 $bytes *= 1024;
167 case 'T':
168 $bytes *= 1024;
169 case 'G':
170 $bytes *= 1024;
171 case 'M':
172 $bytes *= 1024;
173 case 'K':
174 $bytes *= 1024;
175 default:
176 break;
177 }
178 return $bytes;
179 }
180
181 /**
182 * gets the maximum upload size according to php.ini
183 * @returns the maximum upload size in bytes
184 */
185 function
186 jirafeau_get_max_upload_size_bytes ()
187 {
188 return min (jirafeau_ini_to_bytes (ini_get ('post_max_size')),
189 jirafeau_ini_to_bytes (ini_get ('upload_max_filesize')));
190 }
191
192 /**
193 * gets the maximum upload size according to php.ini
194 * @returns the maximum upload size string
195 */
196 function
197 jirafeau_get_max_upload_size ()
198 {
199 return jirafeau_human_size(
200 min (jirafeau_ini_to_bytes (ini_get ('post_max_size')),
201 jirafeau_ini_to_bytes (ini_get ('upload_max_filesize'))));
202 }
203
204 /**
205 * gets a string explaining the error
206 * @param $code the error code
207 * @returns a string explaining the error
208 */
209 function
210 jirafeau_upload_errstr ($code)
211 {
212 switch ($code)
213 {
214 case UPLOAD_ERR_INI_SIZE:
215 case UPLOAD_ERR_FORM_SIZE:
216 return t('Your file exceeds the maximum authorized file size. ');
217 break;
218
219 case UPLOAD_ERR_PARTIAL:
220 case UPLOAD_ERR_NO_FILE:
221 return
222 t
223 ('Your file was not uploaded correctly. You may succeed in retrying. ');
224 break;
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 break;
231
232 default:
233 break;
234 }
235 return t('Unknown error. ');
236 }
237
238 /** Remove link and it's file
239 * @param $link the link's name (hash)
240 */
241
242 function
243 jirafeau_delete_link ($link)
244 {
245 $l = jirafeau_get_link ($link);
246 if (!count ($l))
247 return;
248
249 jirafeau_clean_rm_link ($link);
250
251 $md5 = $l['md5'];
252 $p = s2p ("$md5");
253
254 $counter = 1;
255 if (file_exists (VAR_FILES . $p . $md5. '_count'))
256 {
257 $content = file (VAR_FILES . $p . $md5. '_count');
258 $counter = trim ($content[0]);
259 }
260 $counter--;
261
262 if ($counter >= 1)
263 {
264 $handle = fopen (VAR_FILES . $p . $md5. '_count', 'w');
265 fwrite ($handle, $counter);
266 fclose ($handle);
267 }
268
269 if ($counter == 0)
270 jirafeau_clean_rm_file ($md5);
271 }
272
273 /**
274 * Delete a file and it's links.
275 */
276 function
277 jirafeau_delete_file ($md5)
278 {
279 $count = 0;
280 /* Get all links files. */
281 $stack = array (VAR_LINKS);
282 while (($d = array_shift ($stack)) && $d != NULL)
283 {
284 $dir = scandir ($d);
285
286 foreach ($dir as $node)
287 {
288 if (strcmp ($node, '.') == 0 || strcmp ($node, '..') == 0 ||
289 preg_match ('/\.tmp/i', "$node"))
290 continue;
291
292 if (is_dir ($d . $node))
293 {
294 /* Push new found directory. */
295 $stack[] = $d . $node . '/';
296 }
297 elseif (is_file ($d . $node))
298 {
299 /* Read link informations. */
300 $l = jirafeau_get_link (basename ($node));
301 if (!count ($l))
302 continue;
303 if ($l['md5'] == $md5)
304 {
305 $count++;
306 jirafeau_delete_link ($node);
307 }
308 }
309 }
310 }
311 jirafeau_clean_rm_file ($md5);
312 return $count;
313 }
314
315 /**
316 * handles an uploaded file
317 * @param $file the file struct given by $_FILE[]
318 * @param $one_time_download is the file a one time download ?
319 * @param $key if not empty, protect the file with this key
320 * @param $time the time of validity of the file
321 * @param $ip uploader's ip
322 * @param $crypt boolean asking to crypt or not
323 * @param $link_name_length size of the link name
324 * @returns an array containing some information
325 * 'error' => information on possible errors
326 * 'link' => the link name of the uploaded file
327 * 'delete_link' => the link code to delete file
328 */
329 function
330 jirafeau_upload ($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length)
331 {
332 if (empty ($file['tmp_name']) || !is_uploaded_file ($file['tmp_name']))
333 {
334 return (array(
335 'error' =>
336 array ('has_error' => true,
337 'why' => jirafeau_upload_errstr ($file['error'])),
338 'link' => '',
339 'delete_link' => ''));
340 }
341
342 /* array representing no error */
343 $noerr = array ('has_error' => false, 'why' => '');
344
345 /* Crypt file if option is enabled. */
346 $crypted = false;
347 $crypt_key = '';
348 if ($crypt == true && !(extension_loaded('mcrypt') == true))
349 error_log ("PHP extension mcrypt not loaded, won't encrypt in Jirafeau");
350 if ($crypt == true && extension_loaded('mcrypt') == true)
351 {
352 $crypt_key = jirafeau_encrypt_file ($file['tmp_name'], $file['tmp_name']);
353 if (strlen($crypt_key) > 0)
354 $crypted = true;
355 }
356
357 /* file informations */
358 $md5 = md5_file ($file['tmp_name']);
359 $name = str_replace (NL, '', trim ($file['name']));
360 $mime_type = $file['type'];
361 $size = $file['size'];
362
363 /* does file already exist ? */
364 $rc = false;
365 $p = s2p ("$md5");
366 if (file_exists (VAR_FILES . $p . $md5))
367 {
368 $rc = unlink ($file['tmp_name']);
369 }
370 elseif ((file_exists (VAR_FILES . $p) || @mkdir (VAR_FILES . $p, 0755, true))
371 && move_uploaded_file ($file['tmp_name'], VAR_FILES . $p . $md5))
372 {
373 $rc = true;
374 }
375 if (!$rc)
376 {
377 return (array(
378 'error' =>
379 array ('has_error' => true,
380 'why' => t('Internal error during file creation.')),
381 'link' =>'',
382 'delete_link' => ''));
383 }
384
385 /* Increment or create count file. */
386 $counter = 0;
387 if (file_exists (VAR_FILES . $p . $md5 . '_count'))
388 {
389 $content = file (VAR_FILES . $p . $md5. '_count');
390 $counter = trim ($content[0]);
391 }
392 $counter++;
393 $handle = fopen (VAR_FILES . $p . $md5. '_count', 'w');
394 fwrite ($handle, $counter);
395 fclose ($handle);
396
397 /* Create delete code. */
398 $delete_link_code = jirafeau_gen_random (5);
399
400 /* md5 password or empty. */
401 $password = '';
402 if (!empty ($key))
403 $password = md5 ($key);
404
405 /* create link file */
406 $link_tmp_name = VAR_LINKS . $md5 . rand (0, 10000) . '.tmp';
407 $handle = fopen ($link_tmp_name, 'w');
408 fwrite ($handle,
409 $name . NL. $mime_type . NL. $size . NL. $password . NL. $time .
410 NL . $md5. NL . ($one_time_download ? 'O' : 'R') . NL . date ('U') .
411 NL . $ip . NL. $delete_link_code . NL . ($crypted ? 'C' : 'O'));
412 fclose ($handle);
413 $md5_link = substr(base_16_to_64 (md5_file ($link_tmp_name)), 0, $link_name_length);
414 $l = s2p ("$md5_link");
415 if (!@mkdir (VAR_LINKS . $l, 0755, true) ||
416 !rename ($link_tmp_name, VAR_LINKS . $l . $md5_link))
417 {
418 if (file_exists ($link_tmp_name))
419 unlink ($link_tmp_name);
420
421 $counter--;
422 if ($counter >= 1)
423 {
424 $handle = fopen (VAR_FILES . $p . $md5. '_count', 'w');
425 fwrite ($handle, $counter);
426 fclose ($handle);
427 }
428 else
429 {
430 jirafeau_clean_rm_file ($md5_link);
431 }
432 return (array(
433 'error' =>
434 array ('has_error' => true,
435 'why' => t('Internal error during file creation. ')),
436 'link' =>'',
437 'delete_link' => ''));
438 }
439 return (array ('error' => $noerr,
440 'link' => $md5_link,
441 'delete_link' => $delete_link_code,
442 'crypt_key' => $crypt_key));
443 }
444
445 /**
446 * tells if a mime-type is viewable in a browser
447 * @param $mime the mime type
448 * @returns a boolean telling if a mime type is viewable
449 */
450 function
451 jirafeau_is_viewable ($mime)
452 {
453 if (!empty ($mime))
454 {
455 /* Actually, verify if mime-type is an image or a text. */
456 $viewable = array ('image', 'text', 'video', 'audio');
457 $decomposed = explode ('/', $mime);
458 return in_array ($decomposed[0], $viewable);
459 }
460 return false;
461 }
462
463 // Error handling functions.
464 //! Global array that contains all registered errors.
465 $error_list = array ();
466
467 /**
468 * Adds an error to the list of errors.
469 * @param $title the error's title
470 * @param $description is a human-friendly description of the problem.
471 */
472 function
473 add_error ($title, $description)
474 {
475 global $error_list;
476 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
477 }
478
479 /**
480 * Informs whether any error has been registered yet.
481 * @return true if there are errors.
482 */
483 function
484 has_error ()
485 {
486 global $error_list;
487 return !empty ($error_list);
488 }
489
490 /**
491 * Displays all the errors.
492 */
493 function
494 show_errors ()
495 {
496 if (has_error ())
497 {
498 global $error_list;
499 echo '<div class="error">';
500 foreach ($error_list as $error)
501 {
502 echo $error;
503 }
504 echo '</div>';
505 }
506 }
507
508 function check_errors ($cfg)
509 {
510 if (file_exists (JIRAFEAU_ROOT . 'install.php')
511 && !($cfg['installation_done'] === true))
512 {
513 header('Location: install.php');
514 exit;
515 }
516
517 /* check if the destination dirs are writable */
518 $writable = is_writable (VAR_FILES) && is_writable (VAR_LINKS);
519
520 /* Checking for errors. */
521 if (!is_writable (VAR_FILES))
522 add_error (t('The file directory is not writable!'), VAR_FILES);
523
524 if (!is_writable (VAR_LINKS))
525 add_error (t('The link directory is not writable!'), VAR_LINKS);
526
527 if (!is_writable (VAR_ASYNC))
528 add_error (t('The async directory is not writable!'), VAR_ASYNC);
529 }
530
531 /**
532 * Read link informations
533 * @return array containing informations.
534 */
535 function
536 jirafeau_get_link ($hash)
537 {
538 $out = array ();
539 $link = VAR_LINKS . s2p ("$hash") . $hash;
540
541 if (!file_exists ($link))
542 return $out;
543
544 $c = file ($link);
545 $out['file_name'] = trim ($c[0]);
546 $out['mime_type'] = trim ($c[1]);
547 $out['file_size'] = trim ($c[2]);
548 $out['key'] = trim ($c[3], NL);
549 $out['time'] = trim ($c[4]);
550 $out['md5'] = trim ($c[5]);
551 $out['onetime'] = trim ($c[6]);
552 $out['upload_date'] = trim ($c[7]);
553 $out['ip'] = trim ($c[8]);
554 $out['link_code'] = trim ($c[9]);
555 if (trim ($c[10]) == 'C')
556 $out['crypted'] = true;
557 else
558 $out['crypted'] = false;
559
560 return $out;
561 }
562
563 /**
564 * List files in admin interface.
565 */
566 function
567 jirafeau_admin_list ($name, $file_hash, $link_hash)
568 {
569 echo '<fieldset><legend>';
570 if (!empty ($name))
571 echo t('Filename') . ": $name ";
572 if (!empty ($file_hash))
573 echo t('file') . ": $file_hash ";
574 if (!empty ($link_hash))
575 echo t('link') . ": $link_hash ";
576 if (empty ($name) && empty ($file_hash) && empty ($link_hash))
577 echo t('List all files');
578 echo '</legend>';
579 echo '<table>';
580 echo '<tr>';
581 echo '<td>' . t('Filename') . '</td>';
582 echo '<td>' . t('Type') . '</td>';
583 echo '<td>' . t('Size') . '</td>';
584 echo '<td>' . t('Expire') . '</td>';
585 echo '<td>' . t('Onetime') . '</td>';
586 echo '<td>' . t('Upload date') . '</td>';
587 echo '<td>' . t('Origin') . '</td>';
588 echo '<td>' . t('Action') . '</td>';
589 echo '</tr>';
590
591 /* Get all links files. */
592 $stack = array (VAR_LINKS);
593 while (($d = array_shift ($stack)) && $d != NULL)
594 {
595 $dir = scandir ($d);
596 foreach ($dir as $node)
597 {
598 if (strcmp ($node, '.') == 0 || strcmp ($node, '..') == 0 ||
599 preg_match ('/\.tmp/i', "$node"))
600 continue;
601 if (is_dir ($d . $node))
602 {
603 /* Push new found directory. */
604 $stack[] = $d . $node . '/';
605 }
606 elseif (is_file ($d . $node))
607 {
608 /* Read link informations. */
609 $l = jirafeau_get_link ($node);
610 if (!count ($l))
611 continue;
612
613 /* Filter. */
614 if (!empty ($name) && !preg_match ("/$name/i", $l['file_name']))
615 continue;
616 if (!empty ($file_hash) && $file_hash != $l['md5'])
617 continue;
618 if (!empty ($link_hash) && $link_hash != $node)
619 continue;
620 /* Print link informations. */
621 echo '<tr>';
622 echo '<td>' .
623 '<form action = "admin.php" method = "post">' .
624 '<input type = "hidden" name = "action" value = "download"/>' .
625 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
626 '<input type = "submit" value = "' . $l['file_name'] . '" />' .
627 '</form>';
628 echo '</td>';
629 echo '<td>' . $l['mime_type'] . '</td>';
630 echo '<td>' . jirafeau_human_size ($l['file_size']) . '</td>';
631 echo '<td>' . ($l['time'] == -1 ? '' : strftime ('%c', $l['time'])) .
632 '</td>';
633 echo '<td>' . $l['onetime'] . '</td>';
634 echo '<td>' . strftime ('%c', $l['upload_date']) . '</td>';
635 echo '<td>' . $l['ip'] . '</td>';
636 echo '<td>' .
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 (date ('U') - $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 date ('U') . 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 date ('U') . 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 lenght
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 date ('U') . 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') == true))
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 jirafeau_has_upload_password ($cfg)
1065 {
1066 return count ($cfg['upload_password']) > 0;
1067 }
1068
1069 /**
1070 * Challenge password for a visitor.
1071 * @param $password password to be challenged
1072 * @return true if password is valid, false otherwise.
1073 */
1074 function jirafeau_challenge_upload_password ($cfg, $password)
1075 {
1076 if (!jirafeau_has_upload_password($cfg))
1077 return false;
1078 forEach ($cfg['upload_password'] as $p)
1079 if ($password == $p)
1080 return true;
1081 return false;
1082 }
1083

patrick-canterino.de