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

patrick-canterino.de