]>
git.p6c8.net - jirafeau_project.git/blob - lib/functions.php
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>
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.
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.
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/>.
22 * Transform a string in a path by seperating each letters by a '/'.
23 * @return path finishing with a '/'
29 for ($i = 0; $i < strlen ($s); $i++
)
35 * Convert base 16 to base 64
36 * @returns A string based on 64 characters (0-9, a-z, A-Z, "-" and "_")
41 $m = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_';
42 $hex2bin = array ('0000', # 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.
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;
76 * Generate a random code.
77 * @param $l code length
78 * @return random code.
81 jirafeau_gen_random ($l)
87 for ($i = 0; $i < $l; $i++
)
88 $code .= dechex (rand (0, 15));
94 if ( isset($_SERVER['HTTPS']) ) {
95 if ( 'on' == strtolower($_SERVER['HTTPS']) )
97 if ( '1' == $_SERVER['HTTPS'] )
99 } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
106 jirafeau_human_size ($octets)
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];
116 jirafeau_clean_rm_link ($link)
119 if (file_exists (VAR_LINKS
. $p . $link))
120 unlink (VAR_LINKS
. $p . $link);
121 $parse = VAR_LINKS
. $p;
123 while (file_exists ($parse)
124 && ($scan = scandir ($parse))
125 && count ($scan) == 2 // '.' and '..' folders => empty.
126 && basename ($parse) != basename (VAR_LINKS
))
129 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
134 jirafeau_clean_rm_file ($md5)
137 $f = VAR_FILES
. $p . $md5;
138 if (file_exists ($f) && is_file ($f))
140 if (file_exists ($f . '_count') && is_file ($f . '_count'))
141 unlink ($f . '_count');
142 $parse = VAR_FILES
. $p;
144 while (file_exists ($parse)
145 && ($scan = scandir ($parse))
146 && count ($scan) == 2 // '.' and '..' folders => empty.
147 && basename ($parse) != basename (VAR_FILES
))
150 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
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
159 function jirafeau_ini_to_bytes ($value)
161 $modifier = substr ($value, -1);
162 $bytes = substr ($value, 0, -1);
163 switch (strtoupper ($modifier))
182 * gets the maximum upload size according to php.ini
183 * @returns the maximum upload size in bytes
186 jirafeau_get_max_upload_size_bytes ()
188 return min (jirafeau_ini_to_bytes (ini_get ('post_max_size')),
189 jirafeau_ini_to_bytes (ini_get ('upload_max_filesize')));
193 * gets the maximum upload size according to php.ini
194 * @returns the maximum upload size string
197 jirafeau_get_max_upload_size ()
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'))));
205 * gets a string explaining the error
206 * @param $code the error code
207 * @returns a string explaining the error
210 jirafeau_upload_errstr ($code)
214 case UPLOAD_ERR_INI_SIZE
:
215 case UPLOAD_ERR_FORM_SIZE
:
216 return t('Your file exceeds the maximum authorized file size. ');
219 case UPLOAD_ERR_PARTIAL
:
220 case UPLOAD_ERR_NO_FILE
:
223 ('Your file was not uploaded correctly. You may succeed in retrying. ');
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. ');
235 return t('Unknown error. ');
238 /** Remove link and it's file
239 * @param $link the link's name (hash)
243 jirafeau_delete_link ($link)
245 $l = jirafeau_get_link ($link);
249 jirafeau_clean_rm_link ($link);
255 if (file_exists (VAR_FILES
. $p . $md5. '_count'))
257 $content = file (VAR_FILES
. $p . $md5. '_count');
258 $counter = trim ($content[0]);
264 $handle = fopen (VAR_FILES
. $p . $md5. '_count', 'w');
265 fwrite ($handle, $counter);
270 jirafeau_clean_rm_file ($md5);
274 * Delete a file and it's links.
277 jirafeau_delete_file ($md5)
280 /* Get all links files. */
281 $stack = array (VAR_LINKS
);
282 while (($d = array_shift ($stack)) && $d != NULL)
286 foreach ($dir as $node)
288 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
289 preg_match ('/\.tmp/i', "$node"))
292 if (is_dir ($d . $node))
294 /* Push new found directory. */
295 $stack[] = $d . $node . '/';
297 elseif (is_file ($d . $node))
299 /* Read link informations. */
300 $l = jirafeau_get_link (basename ($node));
303 if ($l['md5'] == $md5)
306 jirafeau_delete_link ($node);
311 jirafeau_clean_rm_file ($md5);
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
330 jirafeau_upload ($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length)
332 if (empty ($file['tmp_name']) ||
!is_uploaded_file ($file['tmp_name']))
336 array ('has_error' => true,
337 'why' => jirafeau_upload_errstr ($file['error'])),
339 'delete_link' => ''));
342 /* array representing no error */
343 $noerr = array ('has_error' => false, 'why' => '');
345 /* Crypt file if option is enabled. */
348 if ($crypt == true && extension_loaded('mcrypt'))
350 $crypt_key = jirafeau_encrypt_file ($file['tmp_name'], $file['tmp_name']);
351 if (strlen($crypt_key) > 0)
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'];
361 /* does file already exist ? */
364 if (file_exists (VAR_FILES
. $p . $md5))
366 $rc = unlink ($file['tmp_name']);
368 elseif ((file_exists (VAR_FILES
. $p) || @mkdir
(VAR_FILES
. $p, 0755, true))
369 && move_uploaded_file ($file['tmp_name'], VAR_FILES
. $p . $md5))
377 array ('has_error' => true,
378 'why' => t('Internal error during file creation.')),
380 'delete_link' => ''));
383 /* Increment or create count file. */
385 if (file_exists (VAR_FILES
. $p . $md5 . '_count'))
387 $content = file (VAR_FILES
. $p . $md5. '_count');
388 $counter = trim ($content[0]);
391 $handle = fopen (VAR_FILES
. $p . $md5. '_count', 'w');
392 fwrite ($handle, $counter);
395 /* Create delete code. */
396 $delete_link_code = jirafeau_gen_random (5);
398 /* md5 password or empty. */
401 $password = md5 ($key);
403 /* create link file */
404 $link_tmp_name = VAR_LINKS
. $md5 . rand (0, 10000) . '.tmp';
405 $handle = fopen ($link_tmp_name, 'w');
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'));
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))
416 if (file_exists ($link_tmp_name))
417 unlink ($link_tmp_name);
422 $handle = fopen (VAR_FILES
. $p . $md5. '_count', 'w');
423 fwrite ($handle, $counter);
428 jirafeau_clean_rm_file ($md5_link);
432 array ('has_error' => true,
433 'why' => t('Internal error during file creation. ')),
435 'delete_link' => ''));
437 return (array ('error' => $noerr,
439 'delete_link' => $delete_link_code,
440 'crypt_key' => $crypt_key));
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
449 jirafeau_is_viewable ($mime)
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);
461 // Error handling functions.
462 //! Global array that contains all registered errors.
463 $error_list = array ();
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.
471 add_error ($title, $description)
474 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
478 * Informs whether any error has been registered yet.
479 * @return true if there are errors.
485 return !empty ($error_list);
489 * Displays all the errors.
497 echo '<div class="error">';
498 foreach ($error_list as $error)
506 function check_errors ()
508 if (file_exists (JIRAFEAU_ROOT
. 'install.php')
509 && !file_exists (JIRAFEAU_ROOT
. 'lib/config.local.php'))
511 header('Location: install.php');
515 /* check if the destination dirs are writable */
516 $writable = is_writable (VAR_FILES
) && is_writable (VAR_LINKS
);
518 /* Checking for errors. */
519 if (!is_writable (VAR_FILES
))
520 add_error (t('The file directory is not writable!'), VAR_FILES
);
522 if (!is_writable (VAR_LINKS
))
523 add_error (t('The link directory is not writable!'), VAR_LINKS
);
525 if (!is_writable (VAR_ASYNC
))
526 add_error (t('The async directory is not writable!'), VAR_ASYNC
);
528 if (!is_writable (VAR_BLOCK
))
529 add_error (t('The block directory is not writable!'), VAR_BLOCK
);
533 * Read link informations
534 * @return array containing informations.
537 jirafeau_get_link ($hash)
540 $link = VAR_LINKS
. s2p ("$hash") . $hash;
542 if (!file_exists ($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;
563 * List files in admin interface.
566 jirafeau_admin_list ($name, $file_hash, $link_hash)
568 echo '<fieldset><legend>';
570 echo t('Filename') . ": $name ";
571 if (!empty ($file_hash))
572 echo t('file') . ": $file_hash ";
573 if (!empty ($link_hash))
574 echo t('link') . ": $link_hash ";
575 if (empty ($name) && empty ($file_hash) && empty ($link_hash))
576 echo t('List all files');
580 echo '<td>' . t('Filename') . '</td>';
581 echo '<td>' . t('Type') . '</td>';
582 echo '<td>' . t('Size') . '</td>';
583 echo '<td>' . t('Expire') . '</td>';
584 echo '<td>' . t('Onetime') . '</td>';
585 echo '<td>' . t('Upload date') . '</td>';
586 echo '<td>' . t('Origin') . '</td>';
587 echo '<td>' . t('Action') . '</td>';
590 /* Get all links files. */
591 $stack = array (VAR_LINKS
);
592 while (($d = array_shift ($stack)) && $d != NULL)
595 foreach ($dir as $node)
597 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
598 preg_match ('/\.tmp/i', "$node"))
600 if (is_dir ($d . $node))
602 /* Push new found directory. */
603 $stack[] = $d . $node . '/';
605 elseif (is_file ($d . $node))
607 /* Read link informations. */
608 $l = jirafeau_get_link ($node);
613 if (!empty ($name) && !preg_match ("/$name/i", $l['file_name']))
615 if (!empty ($file_hash) && $file_hash != $l['md5'])
617 if (!empty ($link_hash) && $link_hash != $node)
619 /* Print link informations. */
622 '<form action = "admin.php" method = "post">' .
623 '<input type = "hidden" name = "action" value = "download"/>' .
624 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
625 '<input type = "submit" value = "' . $l['file_name'] . '" />' .
628 echo '<td>' . $l['mime_type'] . '</td>';
629 echo '<td>' . jirafeau_human_size ($l['file_size']) . '</td>';
630 echo '<td>' . ($l['time'] == -1 ?
'' : strftime ('%c', $l['time'])) .
632 echo '<td>' . $l['onetime'] . '</td>';
633 echo '<td>' . strftime ('%c', $l['upload_date']) . '</td>';
634 echo '<td>' . $l['ip'] . '</td>';
636 '<form action = "admin.php" method = "post">' .
637 '<input type = "hidden" name = "action" value = "delete_link"/>' .
638 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
639 '<input type = "submit" value = "' . t('Del link') . '" />' .
641 '<form action = "admin.php" method = "post">' .
642 '<input type = "hidden" name = "action" value = "delete_file"/>' .
643 '<input type = "hidden" name = "md5" value = "' . $l['md5'] . '"/>' .
644 '<input type = "submit" value = "' . t('Del file and links') . '" />' .
651 echo '</table></fieldset>';
655 * Clean expired files.
656 * @return number of cleaned files.
659 jirafeau_admin_clean ()
662 /* Get all links files. */
663 $stack = array (VAR_LINKS
);
664 while (($d = array_shift ($stack)) && $d != NULL)
668 foreach ($dir as $node)
670 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
671 preg_match ('/\.tmp/i', "$node"))
674 if (is_dir ($d . $node))
676 /* Push new found directory. */
677 $stack[] = $d . $node . '/';
679 elseif (is_file ($d . $node))
681 /* Read link informations. */
682 $l = jirafeau_get_link (basename ($node));
685 $p = s2p ($l['md5']);
686 if ($l['time'] > 0 && $l['time'] < time () ||
// expired
687 !file_exists (VAR_FILES
. $p . $l['md5']) ||
// invalid
688 !file_exists (VAR_FILES
. $p . $l['md5'] . '_count')) // invalid
690 jirafeau_delete_link ($node);
701 * Clean old async transferts.
702 * @return number of cleaned files.
705 jirafeau_admin_clean_async ()
708 /* Get all links files. */
709 $stack = array (VAR_ASYNC
);
710 while (($d = array_shift ($stack)) && $d != NULL)
714 foreach ($dir as $node)
716 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
717 preg_match ('/\.tmp/i', "$node"))
720 if (is_dir ($d . $node))
722 /* Push new found directory. */
723 $stack[] = $d . $node . '/';
725 elseif (is_file ($d . $node))
727 /* Read async informations. */
728 $a = jirafeau_get_async_ref (basename ($node));
731 /* Delete transferts older than 1 hour. */
732 if (date ('U') - $a['last_edited'] > 3600)
734 jirafeau_async_delete (basename ($node));
743 * Read async transfert informations
744 * @return array containing informations.
747 jirafeau_get_async_ref ($ref)
750 $refinfos = VAR_ASYNC
. s2p ("$ref") . "$ref";
752 if (!file_exists ($refinfos))
755 $c = file ($refinfos);
756 $out['file_name'] = trim ($c[0]);
757 $out['mime_type'] = trim ($c[1]);
758 $out['key'] = trim ($c[2], NL
);
759 $out['time'] = trim ($c[3]);
760 $out['onetime'] = trim ($c[4]);
761 $out['ip'] = trim ($c[5]);
762 $out['last_edited'] = trim ($c[6]);
763 $out['next_code'] = trim ($c[7]);
768 * Delete async transfert informations
771 jirafeau_async_delete ($ref)
774 if (file_exists (VAR_ASYNC
. $p . $ref))
775 unlink (VAR_ASYNC
. $p . $ref);
776 if (file_exists (VAR_ASYNC
. $p . $ref . '_data'))
777 unlink (VAR_ASYNC
. $p . $ref . '_data');
778 $parse = VAR_ASYNC
. $p;
780 while (file_exists ($parse)
781 && ($scan = scandir ($parse))
782 && count ($scan) == 2 // '.' and '..' folders => empty.
783 && basename ($parse) != basename (VAR_ASYNC
))
786 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
791 * Init a new asynchronous upload.
792 * @param $finename Name of the file to send
793 * @param $one_time One time upload parameter
794 * @param $key eventual password (or blank)
795 * @param $time time limit
796 * @param $ip ip address of the client
797 * @return a string containing a temporary reference followed by a code or the string "Error"
800 jirafeau_async_init ($filename, $type, $one_time, $key, $time, $ip)
804 /* Create temporary folder. */
807 $code = jirafeau_gen_random (4);
810 $ref = jirafeau_gen_random (32);
811 $p = VAR_ASYNC
. s2p ($ref);
812 } while (file_exists ($p));
813 @mkdir
($p, 0755, true);
814 if (!file_exists ($p))
820 /* md5 password or empty */
823 $password = md5 ($key);
825 /* Store informations. */
827 $handle = fopen ($p, 'w');
829 str_replace (NL
, '', trim ($filename)) . NL
.
830 str_replace (NL
, '', trim ($type)) . NL
. $password . NL
.
831 $time . NL
. ($one_time ?
'O' : 'R') . NL
. $ip . NL
.
832 date ('U') . NL
. $code . NL
);
835 return $ref . NL
. $code ;
839 * Append a piece of file on the asynchronous upload.
840 * @param $ref asynchronous upload reference
841 * @param $file piece of data
842 * @param $code client code for this operation
843 * @return a string containing a next code to use or the string "Error"
846 jirafeau_async_push ($ref, $data, $code)
848 /* Get async infos. */
849 $a = jirafeau_get_async_ref ($ref);
851 /* Check some errors. */
853 ||
$a['next_code'] != "$code"
854 ||
empty ($data['tmp_name'])
855 ||
!is_uploaded_file ($data['tmp_name']))
860 /* Concatenate data. */
861 $r = fopen ($data['tmp_name'], 'r');
862 $w = fopen (VAR_ASYNC
. $p . $ref . '_data', 'a');
865 if (fwrite ($w, fread ($r, 1024)) === false)
869 jirafeau_async_delete ($ref);
875 unlink ($data['tmp_name']);
877 /* Update async file. */
878 $code = jirafeau_gen_random (4);
879 $handle = fopen (VAR_ASYNC
. $p . $ref, 'w');
881 $a['file_name'] . NL
. $a['mime_type'] . NL
. $a['key'] . NL
.
882 $a['time'] . NL
. $a['onetime'] . NL
. $a['ip'] . NL
.
883 date ('U') . NL
. $code . NL
);
889 * Finalyze an asynchronous upload.
890 * @param $ref asynchronous upload reference
891 * @param $code client code for this operation
892 * @param $crypt boolean asking to crypt or not
893 * @param $link_name_length link name lenght
894 * @return a string containing the download reference followed by a delete code or the string "Error"
897 jirafeau_async_end ($ref, $code, $crypt, $link_name_length)
899 /* Get async infos. */
900 $a = jirafeau_get_async_ref ($ref);
902 ||
$a['next_code'] != "$code")
905 /* Generate link infos. */
906 $p = VAR_ASYNC
. s2p ($ref) . $ref . "_data";
907 if (!file_exists($p))
912 if ($crypt == true && extension_loaded('mcrypt'))
914 $crypt_key = jirafeau_encrypt_file ($p, $p);
915 if (strlen($crypt_key) > 0)
919 $md5 = md5_file ($p);
920 $size = filesize($p);
922 $delete_link_code = jirafeau_gen_random (5);
924 /* File already exist ? */
925 if (!file_exists (VAR_FILES
. $np))
926 @mkdir
(VAR_FILES
. $np, 0755, true);
927 if (!file_exists (VAR_FILES
. $np . $md5))
928 rename ($p, VAR_FILES
. $np . $md5);
930 /* Increment or create count file. */
932 if (file_exists (VAR_FILES
. $np . $md5 . '_count'))
934 $content = file (VAR_FILES
. $np . $md5. '_count');
935 $counter = trim ($content[0]);
938 $handle = fopen (VAR_FILES
. $np . $md5. '_count', 'w');
939 fwrite ($handle, $counter);
943 $link_tmp_name = VAR_LINKS
. $md5 . rand (0, 10000) . '.tmp';
944 $handle = fopen ($link_tmp_name, 'w');
946 $a['file_name'] . NL
. $a['mime_type'] . NL
. $size . NL
.
947 $a['key'] . NL
. $a['time'] . NL
. $md5 . NL
. $a['onetime'] . NL
.
948 date ('U') . NL
. $a['ip'] . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
950 $md5_link = substr(base_16_to_64 (md5_file ($link_tmp_name)), 0, $link_name_length);
951 $l = s2p ("$md5_link");
952 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
953 !rename ($link_tmp_name, VAR_LINKS
. $l . $md5_link))
956 /* Clean async upload. */
957 jirafeau_async_delete ($ref);
958 return $md5_link . NL
. $delete_link_code . NL
. urlencode($crypt_key);
963 * @param $id identifier of the block.
966 jirafeau_block_delete_ ($id)
968 $p = VAR_BLOCK
. s2p ($id);
969 if (!file_exists ($p))
972 if (file_exists ($p . $id))
974 if (file_exists ($p . $id . '_infos'))
975 unlink ($p . $id . '_infos');
978 while (file_exists ($parse)
979 && ($scan = scandir ($parse))
980 && count ($scan) == 2 // '.' and '..' folders => empty.
981 && basename ($parse) != basename (VAR_BLOCK
))
984 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
989 * Create a file filled with zeros.
990 * @param $size size of the file.
991 * @return a string corresponding to an id or the string "Error"
994 jirafeau_block_init ($size)
996 if (!ctype_digit ($size) ||
$size <= 0)
1003 $id = jirafeau_gen_random (32);
1004 $p = VAR_BLOCK
. s2p ($id);
1005 } while (file_exists ($p));
1006 @mkdir
($p, 0755, true);
1007 if (!file_exists ($p))
1015 $h = fopen ($p, 'w');
1016 $fill = str_repeat ("\0", 1024);
1017 for ($cnt = 0; $cnt < $size; $cnt +
= 1024)
1019 if ($size - $cnt < 1024)
1020 $fill = str_repeat ("\0", $size - $cnt);
1021 if (fwrite ($h, $fill) === false)
1024 jirafeau_block_delete_ ($id);
1030 /* Generate a write/delete code. */
1031 $code = jirafeau_gen_random (12);
1033 /* Add block infos. */
1034 if (file_put_contents ($p . '_infos', date ('U') . NL
. $size . NL
. $code) === FALSE)
1036 jirafeau_block_delete_ ($id);
1040 return $id . NL
. $code;
1043 /** Get block size in bytes.
1044 * @param $id identifier of the block
1045 * @return block size in bytes
1048 jirafeau_block_get_size ($id)
1050 $p = VAR_BLOCK
. s2p ($id) . $id;
1051 if (!file_exists ($p))
1055 $f = file ($p . '_infos');
1056 $date = trim ($f[0]);
1057 $block_size = trim ($f[1]);
1058 $stored_code = trim ($f[2]);
1060 if (date ('U') - $date > JIRAFEAU_HOUR
1061 && date ('U') - $date < JIRAFEAU_MONTH
)
1063 if (file_put_contents ($p . '_infos', date ('U') . NL
. $block_size . NL
. $stored_code) === FALSE)
1065 jirafeau_block_delete_ ($id);
1070 elseif (date ('U') - $date >= JIRAFEAU_MONTH
)
1072 echo date ('U'). " $date ";
1073 jirafeau_block_delete_ ($id);
1081 * Read some data in a block.
1082 * @param $id identifier of the block
1083 * @param $start where to read data (starting from zero).
1084 * @param $length length to read.
1088 jirafeau_block_read ($id, $start, $length)
1090 if (!ctype_digit ($start) ||
$start < 0
1091 ||
!ctype_digit ($length) ||
$length <= 0)
1097 $p = VAR_BLOCK
. s2p ($id) . $id;
1098 if (!file_exists ($p))
1105 $f = file ($p . '_infos');
1106 $date = trim ($f[0]);
1107 $block_size = trim ($f[1]);
1108 $stored_code = trim ($f[2]);
1110 if (date ('U') - $date > JIRAFEAU_HOUR
1111 && date ('U') - $date < JIRAFEAU_MONTH
)
1113 if (file_put_contents ($p . '_infos', date ('U') . NL
. $block_size . NL
. $stored_code) === FALSE)
1115 jirafeau_block_delete_ ($id);
1121 elseif (date ('U') - $date >= JIRAFEAU_MONTH
)
1123 echo date ('U'). " $date ";
1124 jirafeau_block_delete_ ($id);
1129 if ($start +
$length > $block_size)
1136 header ('Content-Length: ' . $length);
1137 header ('Content-Disposition: attachment');
1139 $r = fopen ($p, 'r');
1140 if (fseek ($r, $start) != 0)
1146 for ($cnt = 0; $cnt < $length && !feof ($r); $cnt +
= 1024)
1148 if ($length - $cnt < 1024)
1149 $c = $length - $cnt;
1150 print fread ($r, $c);
1157 * Write some data in a block.
1158 * @param $id identifier of the block
1159 * @param $start where to writing data (starting from zero).
1160 * @param $data data to write.
1161 * @param $code code to allow writing.
1162 * @return string "Ok" or string "Error".
1165 jirafeau_block_write ($id, $start, $data, $code)
1167 if (!ctype_digit ($start) ||
$start < 0
1168 ||
strlen ($code) == 0)
1171 $p = VAR_BLOCK
. s2p ($id) . $id;
1172 if (!file_exists ($p))
1176 $f = file ($p . '_infos');
1177 $date = trim ($f[0]);
1178 $block_size = trim ($f[1]);
1179 $stored_code = trim ($f[2]);
1181 if (date ('U') - $date > JIRAFEAU_HOUR
1182 && date ('U') - $date < JIRAFEAU_MONTH
)
1184 if (file_put_contents ($p . '_infos', date ('U') . NL
. $block_size . NL
. $stored_code) === FALSE)
1186 jirafeau_block_delete_ ($id);
1191 elseif (date ('U') - $date >= JIRAFEAU_MONTH
)
1193 jirafeau_block_delete_ ($id);
1198 if ($stored_code != $code)
1205 $size = $data['size'];
1208 if ($start +
$size > $block_size)
1212 $r = fopen ($data['tmp_name'], 'r');
1215 $w = fopen ($p, 'r+');
1216 if (fseek ($w, $start) != 0)
1219 /* Write content. */
1221 for ($cnt = 0; $cnt <= $size && !feof ($w); $cnt +
= 1024)
1223 if ($size - $cnt < 1024)
1225 $d = fread ($r, $c);
1230 unlink ($data['tmp_name']);
1236 * @param $id identifier of the block.
1237 * @param $code code to allow writing.
1238 * @return string "Ok" or string "Error".
1241 jirafeau_block_delete ($id, $code)
1243 $p = VAR_BLOCK
. s2p ($id) . $id;
1245 if (!file_exists ($p))
1248 $f = file ($p . '_infos');
1249 $date = trim ($f[0]);
1250 $block_size = trim ($f[1]);
1251 $stored_code = trim ($f[2]);
1253 if ($code != $stored_code)
1256 jirafeau_block_delete_ ($id);
1261 * Clean old unused blocks.
1262 * @return number of cleaned blocks.
1265 jirafeau_admin_clean_block ()
1268 /* Get all blocks. */
1269 $stack = array (VAR_BLOCK
);
1270 while (($d = array_shift ($stack)) && $d != NULL)
1272 $dir = scandir ($d);
1274 foreach ($dir as $node)
1276 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0)
1279 if (is_dir ($d . $node))
1281 /* Push new found directory. */
1282 $stack[] = $d . $node . '/';
1284 elseif (is_file ($d . $node) && preg_match ('/\_infos/i', "$node"))
1286 /* Read block informations. */
1287 $f = file ($d . $node);
1288 $date = trim ($f[0]);
1289 $block_size = trim ($f[1]);
1290 if (date ('U') - $date >= JIRAFEAU_MONTH
)
1292 jirafeau_block_delete_ (substr($node, 0, -6));
1302 jirafeau_crypt_create_iv($base, $size)
1305 while (strlen ($iv) < $size)
1307 $iv = substr($iv, 0, $size);
1312 * Crypt file and returns decrypt key.
1313 * @param $fp_src file path to the file to crypt.
1314 * @param $fp_dst file path to the file to write crypted file (could be the same).
1315 * @return decrypt key composed of the key and the iv separated by a point ('.')
1318 jirafeau_encrypt_file ($fp_src, $fp_dst)
1320 $fs = filesize ($fp_src);
1321 if ($fs === false ||
$fs == 0 ||
!extension_loaded('mcrypt'))
1324 /* Prepare module. */
1325 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1327 $crypt_key = jirafeau_gen_random (10);
1328 $md5_key = md5($crypt_key);
1329 $iv = jirafeau_crypt_create_iv ($md5_key, mcrypt_enc_get_iv_size($m));
1331 mcrypt_generic_init($m, $md5_key, $iv);
1333 $r = fopen ($fp_src, 'r');
1334 $w = fopen ($fp_dst, 'c');
1337 $enc = mcrypt_generic($m, fread ($r, 1024));
1338 if (fwrite ($w, $enc) === false)
1344 mcrypt_generic_deinit($m);
1345 mcrypt_module_close($m);
1351 * @param $fp_src file path to the file to decrypt.
1352 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1353 * @param $k string composed of the key and the iv separated by a point ('.')
1354 * @return key used to decrypt. a string of length 0 is returned if failed.
1357 jirafeau_decrypt_file ($fp_src, $fp_dst, $k)
1359 $fs = filesize ($fp_src);
1360 if ($fs === false ||
$fs == 0 ||
!extension_loaded('mcrypt'))
1364 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1365 /* Extract key and iv. */
1367 $md5_key = md5($crypt_key);
1368 $iv = jirafeau_crypt_create_iv ($md5_key, mcrypt_enc_get_iv_size($m));
1370 $r = fopen ($fp_src, 'r');
1371 $w = fopen ($fp_dst, 'c');
1374 $dec = mdecrypt_generic($m, fread ($r, 1024));
1375 if (fwrite ($w, $dec) === false)
1381 mcrypt_generic_deinit($m);
1382 mcrypt_module_close($m);
patrick-canterino.de