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

patrick-canterino.de