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

patrick-canterino.de