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

patrick-canterino.de