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

patrick-canterino.de