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

patrick-canterino.de