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

patrick-canterino.de