]>
git.p6c8.net - jirafeau.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 jirafeau_human_size ($octets)
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);
100 return round ($o, 1) . $u[$p];
104 jirafeau_clean_rm_link ($link)
107 if (file_exists (VAR_LINKS
. $p . $link))
108 unlink (VAR_LINKS
. $p . $link);
109 $parse = VAR_LINKS
. $p;
111 while (file_exists ($parse)
112 && ($scan = scandir ($parse))
113 && count ($scan) == 2 // '.' and '..' folders => empty.
114 && basename ($parse) != basename (VAR_LINKS
))
117 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
122 jirafeau_clean_rm_file ($md5)
125 $f = VAR_FILES
. $p . $md5;
126 if (file_exists ($f) && is_file ($f))
128 if (file_exists ($f . '_count') && is_file ($f . '_count'))
129 unlink ($f . '_count');
130 $parse = VAR_FILES
. $p;
132 while (file_exists ($parse)
133 && ($scan = scandir ($parse))
134 && count ($scan) == 2 // '.' and '..' folders => empty.
135 && basename ($parse) != basename (VAR_FILES
))
138 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
143 * transforms a php.ini string representing a value in an integer
144 * @param $value the value from php.ini
145 * @returns an integer for this value
147 function jirafeau_ini_to_bytes ($value)
149 $modifier = substr ($value, -1);
150 $bytes = substr ($value, 0, -1);
151 switch (strtoupper ($modifier))
170 * gets the maximum upload size according to php.ini
171 * @returns the maximum upload size in bytes
174 jirafeau_get_max_upload_size_bytes ()
176 return min (jirafeau_ini_to_bytes (ini_get ('post_max_size')),
177 jirafeau_ini_to_bytes (ini_get ('upload_max_filesize')));
181 * gets the maximum upload size according to php.ini
182 * @returns the maximum upload size string
185 jirafeau_get_max_upload_size ()
187 return jirafeau_human_size(
188 min (jirafeau_ini_to_bytes (ini_get ('post_max_size')),
189 jirafeau_ini_to_bytes (ini_get ('upload_max_filesize'))));
193 * gets a string explaining the error
194 * @param $code the error code
195 * @returns a string explaining the error
198 jirafeau_upload_errstr ($code)
202 case UPLOAD_ERR_INI_SIZE
:
203 case UPLOAD_ERR_FORM_SIZE
:
204 return t('Your file exceeds the maximum authorized file size. ');
207 case UPLOAD_ERR_PARTIAL
:
208 case UPLOAD_ERR_NO_FILE
:
211 ('Your file was not uploaded correctly. You may succeed in retrying. ');
214 case UPLOAD_ERR_NO_TMP_DIR
:
215 case UPLOAD_ERR_CANT_WRITE
:
216 case UPLOAD_ERR_EXTENSION
:
217 return t('Internal error. You may not succeed in retrying. ');
223 return t('Unknown error. ');
226 /** Remove link and it's file
227 * @param $link the link's name (hash)
231 jirafeau_delete_link ($link)
233 $l = jirafeau_get_link ($link);
237 jirafeau_clean_rm_link ($link);
243 if (file_exists (VAR_FILES
. $p . $md5. '_count'))
245 $content = file (VAR_FILES
. $p . $md5. '_count');
246 $counter = trim ($content[0]);
252 $handle = fopen (VAR_FILES
. $p . $md5. '_count', 'w');
253 fwrite ($handle, $counter);
258 jirafeau_clean_rm_file ($md5);
262 * Delete a file and it's links.
265 jirafeau_delete_file ($md5)
268 /* Get all links files. */
269 $stack = array (VAR_LINKS
);
270 while (($d = array_shift ($stack)) && $d != NULL)
274 foreach ($dir as $node)
276 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
277 preg_match ('/\.tmp/i', "$node"))
280 if (is_dir ($d . $node))
282 /* Push new found directory. */
283 $stack[] = $d . $node . '/';
285 elseif (is_file ($d . $node))
287 /* Read link informations. */
288 $l = jirafeau_get_link (basename ($node));
291 if ($l['md5'] == $md5)
294 jirafeau_delete_link ($node);
299 jirafeau_clean_rm_file ($md5);
304 * handles an uploaded file
305 * @param $file the file struct given by $_FILE[]
306 * @param $one_time_download is the file a one time download ?
307 * @param $key if not empty, protect the file with this key
308 * @param $time the time of validity of the file
309 * @param $ip uploader's ip
310 * @param $crypt boolean asking to crypt or not
311 * @param $link_name_length size of the link name
312 * @returns an array containing some information
313 * 'error' => information on possible errors
314 * 'link' => the link name of the uploaded file
315 * 'delete_link' => the link code to delete file
318 jirafeau_upload ($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length)
320 if (empty ($file['tmp_name']) ||
!is_uploaded_file ($file['tmp_name']))
324 array ('has_error' => true,
325 'why' => jirafeau_upload_errstr ($file['error'])),
327 'delete_link' => ''));
330 /* array representing no error */
331 $noerr = array ('has_error' => false, 'why' => '');
333 /* Crypt file if option is enabled. */
336 if ($crypt == true && extension_loaded('mcrypt'))
338 $crypt_key = jirafeau_encrypt_file ($file['tmp_name'], $file['tmp_name']);
339 if (strlen($crypt_key) > 0)
343 /* file informations */
344 $md5 = md5_file ($file['tmp_name']);
345 $name = str_replace (NL
, '', trim ($file['name']));
346 $mime_type = $file['type'];
347 $size = $file['size'];
349 /* does file already exist ? */
352 if (file_exists (VAR_FILES
. $p . $md5))
354 $rc = unlink ($file['tmp_name']);
356 elseif ((file_exists (VAR_FILES
. $p) || @mkdir
(VAR_FILES
. $p, 0755, true))
357 && move_uploaded_file ($file['tmp_name'], VAR_FILES
. $p . $md5))
365 array ('has_error' => true,
366 'why' => t('Internal error during file creation.')),
368 'delete_link' => ''));
371 /* Increment or create count file. */
373 if (file_exists (VAR_FILES
. $p . $md5 . '_count'))
375 $content = file (VAR_FILES
. $p . $md5. '_count');
376 $counter = trim ($content[0]);
379 $handle = fopen (VAR_FILES
. $p . $md5. '_count', 'w');
380 fwrite ($handle, $counter);
383 /* Create delete code. */
384 $delete_link_code = jirafeau_gen_random (5);
386 /* md5 password or empty. */
389 $password = md5 ($key);
391 /* create link file */
392 $link_tmp_name = VAR_LINKS
. $md5 . rand (0, 10000) . '.tmp';
393 $handle = fopen ($link_tmp_name, 'w');
395 $name . NL
. $mime_type . NL
. $size . NL
. $password . NL
. $time .
396 NL
. $md5. NL
. ($one_time_download ?
'O' : 'R') . NL
. date ('U') .
397 NL
. $ip . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
399 $md5_link = substr(base_16_to_64 (md5_file ($link_tmp_name)), 0, $link_name_length);
400 $l = s2p ("$md5_link");
401 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
402 !rename ($link_tmp_name, VAR_LINKS
. $l . $md5_link))
404 if (file_exists ($link_tmp_name))
405 unlink ($link_tmp_name);
410 $handle = fopen (VAR_FILES
. $p . $md5. '_count', 'w');
411 fwrite ($handle, $counter);
416 jirafeau_clean_rm_file ($md5_link);
420 array ('has_error' => true,
421 'why' => t('Internal error during file creation. ')),
423 'delete_link' => ''));
425 return (array ('error' => $noerr,
427 'delete_link' => $delete_link_code,
428 'crypt_key' => $crypt_key));
432 * tells if a mime-type is viewable in a browser
433 * @param $mime the mime type
434 * @returns a boolean telling if a mime type is viewable
437 jirafeau_is_viewable ($mime)
441 /* Actually, verify if mime-type is an image or a text. */
442 $viewable = array ('image', 'text');
443 $decomposed = explode ('/', $mime);
444 return in_array ($decomposed[0], $viewable);
449 // Error handling functions.
450 //! Global array that contains all registered errors.
451 $error_list = array ();
454 * Adds an error to the list of errors.
455 * @param $title the error's title
456 * @param $description is a human-friendly description of the problem.
459 add_error ($title, $description)
462 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
466 * Informs whether any error has been registered yet.
467 * @return true if there are errors.
473 return !empty ($error_list);
477 * Displays all the errors.
485 echo '<div class="error">';
486 foreach ($error_list as $error)
494 function check_errors ()
496 if (file_exists (JIRAFEAU_ROOT
. 'install.php')
497 && !file_exists (JIRAFEAU_ROOT
. 'lib/config.local.php'))
499 header('Location: install.php');
503 /* check if the destination dirs are writable */
504 $writable = is_writable (VAR_FILES
) && is_writable (VAR_LINKS
);
506 /* Checking for errors. */
507 if (!is_writable (VAR_FILES
))
508 add_error (t('The file directory is not writable!'), VAR_FILES
);
510 if (!is_writable (VAR_LINKS
))
511 add_error (t('The link directory is not writable!'), VAR_LINKS
);
513 if (!is_writable (VAR_ASYNC
))
514 add_error (t('The async directory is not writable!'), VAR_ASYNC
);
516 if (!is_writable (VAR_BLOCK
))
517 add_error (t('The block directory is not writable!'), VAR_BLOCK
);
521 * Read link informations
522 * @return array containing informations.
525 jirafeau_get_link ($hash)
528 $link = VAR_LINKS
. s2p ("$hash") . $hash;
530 if (!file_exists ($link))
534 $out['file_name'] = trim ($c[0]);
535 $out['mime_type'] = trim ($c[1]);
536 $out['file_size'] = trim ($c[2]);
537 $out['key'] = trim ($c[3], NL
);
538 $out['time'] = trim ($c[4]);
539 $out['md5'] = trim ($c[5]);
540 $out['onetime'] = trim ($c[6]);
541 $out['upload_date'] = trim ($c[7]);
542 $out['ip'] = trim ($c[8]);
543 $out['link_code'] = trim ($c[9]);
544 if (trim ($c[10]) == 'C')
545 $out['crypted'] = true;
551 * List files in admin interface.
554 jirafeau_admin_list ($name, $file_hash, $link_hash)
556 echo '<fieldset><legend>';
558 echo t('Filename') . ": $name ";
559 if (!empty ($file_hash))
560 echo t('file') . ": $file_hash ";
561 if (!empty ($link_hash))
562 echo t('link') . ": $link_hash ";
563 if (empty ($name) && empty ($file_hash) && empty ($link_hash))
564 echo t('List all files');
568 echo '<td>' . t('Filename') . '</td>';
569 echo '<td>' . t('Type') . '</td>';
570 echo '<td>' . t('Size') . '</td>';
571 echo '<td>' . t('Expire') . '</td>';
572 echo '<td>' . t('Onetime') . '</td>';
573 echo '<td>' . t('Upload date') . '</td>';
574 echo '<td>' . t('Origin') . '</td>';
575 echo '<td>' . t('Action') . '</td>';
578 /* Get all links files. */
579 $stack = array (VAR_LINKS
);
580 while (($d = array_shift ($stack)) && $d != NULL)
583 foreach ($dir as $node)
585 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
586 preg_match ('/\.tmp/i', "$node"))
588 if (is_dir ($d . $node))
590 /* Push new found directory. */
591 $stack[] = $d . $node . '/';
593 elseif (is_file ($d . $node))
595 /* Read link informations. */
596 $l = jirafeau_get_link ($node);
601 if (!empty ($name) && !preg_match ("/$name/i", $l['file_name']))
603 if (!empty ($file_hash) && $file_hash != $l['md5'])
605 if (!empty ($link_hash) && $link_hash != $node)
607 /* Print link informations. */
610 '<form action = "admin.php" method = "post">' .
611 '<input type = "hidden" name = "action" value = "download"/>' .
612 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
613 '<input type = "submit" value = "' . $l['file_name'] . '" />' .
616 echo '<td>' . $l['mime_type'] . '</td>';
617 echo '<td>' . jirafeau_human_size ($l['file_size']) . '</td>';
618 echo '<td>' . ($l['time'] == -1 ?
'' : strftime ('%c', $l['time'])) .
620 echo '<td>' . $l['onetime'] . '</td>';
621 echo '<td>' . strftime ('%c', $l['upload_date']) . '</td>';
622 echo '<td>' . $l['ip'] . '</td>';
624 '<form action = "admin.php" method = "post">' .
625 '<input type = "hidden" name = "action" value = "delete_link"/>' .
626 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
627 '<input type = "submit" value = "' . t('Del link') . '" />' .
629 '<form action = "admin.php" method = "post">' .
630 '<input type = "hidden" name = "action" value = "delete_file"/>' .
631 '<input type = "hidden" name = "md5" value = "' . $l['md5'] . '"/>' .
632 '<input type = "submit" value = "' . t('Del file and links') . '" />' .
639 echo '</table></fieldset>';
643 * Clean expired files.
644 * @return number of cleaned files.
647 jirafeau_admin_clean ()
650 /* Get all links files. */
651 $stack = array (VAR_LINKS
);
652 while (($d = array_shift ($stack)) && $d != NULL)
656 foreach ($dir as $node)
658 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
659 preg_match ('/\.tmp/i', "$node"))
662 if (is_dir ($d . $node))
664 /* Push new found directory. */
665 $stack[] = $d . $node . '/';
667 elseif (is_file ($d . $node))
669 /* Read link informations. */
670 $l = jirafeau_get_link (basename ($node));
673 $p = s2p ($l['md5']);
674 if ($l['time'] > 0 && $l['time'] < time () ||
// expired
675 !file_exists (VAR_FILES
. $p . $l['md5']) ||
// invalid
676 !file_exists (VAR_FILES
. $p . $l['md5'] . '_count')) // invalid
678 jirafeau_delete_link ($node);
689 * Clean old async transferts.
690 * @return number of cleaned files.
693 jirafeau_admin_clean_async ()
696 /* Get all links files. */
697 $stack = array (VAR_ASYNC
);
698 while (($d = array_shift ($stack)) && $d != NULL)
702 foreach ($dir as $node)
704 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
705 preg_match ('/\.tmp/i', "$node"))
708 if (is_dir ($d . $node))
710 /* Push new found directory. */
711 $stack[] = $d . $node . '/';
713 elseif (is_file ($d . $node))
715 /* Read async informations. */
716 $a = jirafeau_get_async_ref (basename ($node));
719 /* Delete transferts older than 1 hour. */
720 if (date ('U') - $a['last_edited'] > 3600)
722 jirafeau_async_delete (basename ($node));
731 * Read async transfert informations
732 * @return array containing informations.
735 jirafeau_get_async_ref ($ref)
738 $refinfos = VAR_ASYNC
. s2p ("$ref") . "$ref";
740 if (!file_exists ($refinfos))
743 $c = file ($refinfos);
744 $out['file_name'] = trim ($c[0]);
745 $out['mime_type'] = trim ($c[1]);
746 $out['key'] = trim ($c[2], NL
);
747 $out['time'] = trim ($c[3]);
748 $out['onetime'] = trim ($c[4]);
749 $out['ip'] = trim ($c[5]);
750 $out['last_edited'] = trim ($c[6]);
751 $out['next_code'] = trim ($c[7]);
756 * Delete async transfert informations
759 jirafeau_async_delete ($ref)
762 if (file_exists (VAR_ASYNC
. $p . $ref))
763 unlink (VAR_ASYNC
. $p . $ref);
764 if (file_exists (VAR_ASYNC
. $p . $ref . '_data'))
765 unlink (VAR_ASYNC
. $p . $ref . '_data');
766 $parse = VAR_ASYNC
. $p;
768 while (file_exists ($parse)
769 && ($scan = scandir ($parse))
770 && count ($scan) == 2 // '.' and '..' folders => empty.
771 && basename ($parse) != basename (VAR_ASYNC
))
774 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
779 * Init a new asynchronous upload.
780 * @param $finename Name of the file to send
781 * @param $one_time One time upload parameter
782 * @param $key eventual password (or blank)
783 * @param $time time limit
784 * @param $ip ip address of the client
785 * @return a string containing a temporary reference followed by a code or the string "Error"
788 jirafeau_async_init ($filename, $type, $one_time, $key, $time, $ip)
792 /* Create temporary folder. */
795 $code = jirafeau_gen_random (4);
798 $ref = jirafeau_gen_random (32);
799 $p = VAR_ASYNC
. s2p ($ref);
800 } while (file_exists ($p));
801 @mkdir
($p, 0755, true);
802 if (!file_exists ($p))
808 /* md5 password or empty */
811 $password = md5 ($key);
813 /* Store informations. */
815 $handle = fopen ($p, 'w');
817 str_replace (NL
, '', trim ($filename)) . NL
.
818 str_replace (NL
, '', trim ($type)) . NL
. $password . NL
.
819 $time . NL
. ($one_time ?
'O' : 'R') . NL
. $ip . NL
.
820 date ('U') . NL
. $code . NL
);
823 return $ref . NL
. $code ;
827 * Append a piece of file on the asynchronous upload.
828 * @param $ref asynchronous upload reference
829 * @param $file piece of data
830 * @param $code client code for this operation
831 * @return a string containing a next code to use or the string "Error"
834 jirafeau_async_push ($ref, $data, $code)
836 /* Get async infos. */
837 $a = jirafeau_get_async_ref ($ref);
839 /* Check some errors. */
841 ||
$a['next_code'] != "$code"
842 ||
empty ($data['tmp_name'])
843 ||
!is_uploaded_file ($data['tmp_name']))
848 /* Concatenate data. */
849 $r = fopen ($data['tmp_name'], 'r');
850 $w = fopen (VAR_ASYNC
. $p . $ref . '_data', 'a');
853 if (fwrite ($w, fread ($r, 1024)) === false)
857 jirafeau_async_delete ($ref);
863 unlink ($data['tmp_name']);
865 /* Update async file. */
866 $code = jirafeau_gen_random (4);
867 $handle = fopen (VAR_ASYNC
. $p . $ref, 'w');
869 $a['file_name'] . NL
. $a['mime_type'] . NL
. $a['key'] . NL
.
870 $a['time'] . NL
. $a['onetime'] . NL
. $a['ip'] . NL
.
871 date ('U') . NL
. $code . NL
);
877 * Finalyze an asynchronous upload.
878 * @param $ref asynchronous upload reference
879 * @param $code client code for this operation
880 * @param $crypt boolean asking to crypt or not
881 * @param $link_name_length link name lenght
882 * @return a string containing the download reference followed by a delete code or the string "Error"
885 jirafeau_async_end ($ref, $code, $crypt, $link_name_length)
887 /* Get async infos. */
888 $a = jirafeau_get_async_ref ($ref);
890 ||
$a['next_code'] != "$code")
893 /* Generate link infos. */
894 $p = VAR_ASYNC
. s2p ($ref) . $ref . "_data";
895 if (!file_exists($p))
900 if ($crypt == true && extension_loaded('mcrypt'))
902 $crypt_key = jirafeau_encrypt_file ($p, $p);
903 if (strlen($crypt_key) > 0)
907 $md5 = md5_file ($p);
908 $size = filesize($p);
910 $delete_link_code = jirafeau_gen_random (5);
912 /* File already exist ? */
913 if (!file_exists (VAR_FILES
. $np))
914 @mkdir
(VAR_FILES
. $np, 0755, true);
915 if (!file_exists (VAR_FILES
. $np . $md5))
916 rename ($p, VAR_FILES
. $np . $md5);
918 /* Increment or create count file. */
920 if (file_exists (VAR_FILES
. $np . $md5 . '_count'))
922 $content = file (VAR_FILES
. $np . $md5. '_count');
923 $counter = trim ($content[0]);
926 $handle = fopen (VAR_FILES
. $np . $md5. '_count', 'w');
927 fwrite ($handle, $counter);
931 $link_tmp_name = VAR_LINKS
. $md5 . rand (0, 10000) . '.tmp';
932 $handle = fopen ($link_tmp_name, 'w');
934 $a['file_name'] . NL
. $a['mime_type'] . NL
. $size . NL
.
935 $a['key'] . NL
. $a['time'] . NL
. $md5 . NL
. $a['onetime'] . NL
.
936 date ('U') . NL
. $a['ip'] . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
938 $md5_link = substr(base_16_to_64 (md5_file ($link_tmp_name)), 0, $link_name_length);
939 $l = s2p ("$md5_link");
940 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
941 !rename ($link_tmp_name, VAR_LINKS
. $l . $md5_link))
944 /* Clean async upload. */
945 jirafeau_async_delete ($ref);
946 return $md5_link . NL
. $delete_link_code . NL
. urlencode($crypt_key);
951 * @param $id identifier of the block.
954 jirafeau_block_delete_ ($id)
956 $p = VAR_BLOCK
. s2p ($id);
957 if (!file_exists ($p))
960 if (file_exists ($p . $id))
962 if (file_exists ($p . $id . '_infos'))
963 unlink ($p . $id . '_infos');
966 while (file_exists ($parse)
967 && ($scan = scandir ($parse))
968 && count ($scan) == 2 // '.' and '..' folders => empty.
969 && basename ($parse) != basename (VAR_BLOCK
))
972 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
977 * Create a file filled with zeros.
978 * @param $size size of the file.
979 * @return a string corresponding to an id or the string "Error"
982 jirafeau_block_init ($size)
984 if (!ctype_digit ($size) ||
$size <= 0)
991 $id = jirafeau_gen_random (32);
992 $p = VAR_BLOCK
. s2p ($id);
993 } while (file_exists ($p));
994 @mkdir
($p, 0755, true);
995 if (!file_exists ($p))
1003 $h = fopen ($p, 'w');
1004 $fill = str_repeat ("\0", 1024);
1005 for ($cnt = 0; $cnt < $size; $cnt +
= 1024)
1007 if ($size - $cnt < 1024)
1008 $fill = str_repeat ("\0", $size - $cnt);
1009 if (fwrite ($h, $fill) === false)
1012 jirafeau_block_delete_ ($id);
1018 /* Generate a write/delete code. */
1019 $code = jirafeau_gen_random (12);
1021 /* Add block infos. */
1022 if (file_put_contents ($p . '_infos', date ('U') . NL
. $size . NL
. $code) === FALSE)
1024 jirafeau_block_delete_ ($id);
1028 return $id . NL
. $code;
1031 /** Get block size in bytes.
1032 * @param $id identifier of the block
1033 * @return block size in bytes
1036 jirafeau_block_get_size ($id)
1038 $p = VAR_BLOCK
. s2p ($id) . $id;
1039 if (!file_exists ($p))
1043 $f = file ($p . '_infos');
1044 $date = trim ($f[0]);
1045 $block_size = trim ($f[1]);
1046 $stored_code = trim ($f[2]);
1048 if (date ('U') - $date > JIRAFEAU_HOUR
1049 && date ('U') - $date < JIRAFEAU_MONTH
)
1051 if (file_put_contents ($p . '_infos', date ('U') . NL
. $block_size . NL
. $stored_code) === FALSE)
1053 jirafeau_block_delete_ ($id);
1058 elseif (date ('U') - $date >= JIRAFEAU_MONTH
)
1060 echo date ('U'). " $date ";
1061 jirafeau_block_delete_ ($id);
1069 * Read some data in a block.
1070 * @param $id identifier of the block
1071 * @param $start where to read data (starting from zero).
1072 * @param $length length to read.
1076 jirafeau_block_read ($id, $start, $length)
1078 if (!ctype_digit ($start) ||
$start < 0
1079 ||
!ctype_digit ($length) ||
$length <= 0)
1085 $p = VAR_BLOCK
. s2p ($id) . $id;
1086 if (!file_exists ($p))
1093 $f = file ($p . '_infos');
1094 $date = trim ($f[0]);
1095 $block_size = trim ($f[1]);
1096 $stored_code = trim ($f[2]);
1098 if (date ('U') - $date > JIRAFEAU_HOUR
1099 && date ('U') - $date < JIRAFEAU_MONTH
)
1101 if (file_put_contents ($p . '_infos', date ('U') . NL
. $block_size . NL
. $stored_code) === FALSE)
1103 jirafeau_block_delete_ ($id);
1109 elseif (date ('U') - $date >= JIRAFEAU_MONTH
)
1111 echo date ('U'). " $date ";
1112 jirafeau_block_delete_ ($id);
1117 if ($start +
$length > $block_size)
1124 header ('Content-Length: ' . $length);
1125 header ('Content-Disposition: attachment');
1127 $r = fopen ($p, 'r');
1128 if (fseek ($r, $start) != 0)
1134 for ($cnt = 0; $cnt < $length && !feof ($r); $cnt +
= 1024)
1136 if ($length - $cnt < 1024)
1137 $c = $length - $cnt;
1138 print fread ($r, $c);
1145 * Write some data in a block.
1146 * @param $id identifier of the block
1147 * @param $start where to writing data (starting from zero).
1148 * @param $data data to write.
1149 * @param $code code to allow writing.
1150 * @return string "Ok" or string "Error".
1153 jirafeau_block_write ($id, $start, $data, $code)
1155 if (!ctype_digit ($start) ||
$start < 0
1156 ||
strlen ($code) == 0)
1159 $p = VAR_BLOCK
. s2p ($id) . $id;
1160 if (!file_exists ($p))
1164 $f = file ($p . '_infos');
1165 $date = trim ($f[0]);
1166 $block_size = trim ($f[1]);
1167 $stored_code = trim ($f[2]);
1169 if (date ('U') - $date > JIRAFEAU_HOUR
1170 && date ('U') - $date < JIRAFEAU_MONTH
)
1172 if (file_put_contents ($p . '_infos', date ('U') . NL
. $block_size . NL
. $stored_code) === FALSE)
1174 jirafeau_block_delete_ ($id);
1179 elseif (date ('U') - $date >= JIRAFEAU_MONTH
)
1181 jirafeau_block_delete_ ($id);
1186 if ($stored_code != $code)
1193 $size = $data['size'];
1196 if ($start +
$size > $block_size)
1200 $r = fopen ($data['tmp_name'], 'r');
1203 $w = fopen ($p, 'r+');
1204 if (fseek ($w, $start) != 0)
1207 /* Write content. */
1209 for ($cnt = 0; $cnt <= $size && !feof ($w); $cnt +
= 1024)
1211 if ($size - $cnt < 1024)
1213 $d = fread ($r, $c);
1218 unlink ($data['tmp_name']);
1224 * @param $id identifier of the block.
1225 * @param $code code to allow writing.
1226 * @return string "Ok" or string "Error".
1229 jirafeau_block_delete ($id, $code)
1231 $p = VAR_BLOCK
. s2p ($id) . $id;
1233 if (!file_exists ($p))
1236 $f = file ($p . '_infos');
1237 $date = trim ($f[0]);
1238 $block_size = trim ($f[1]);
1239 $stored_code = trim ($f[2]);
1241 if ($code != $stored_code)
1244 jirafeau_block_delete_ ($id);
1249 * Clean old unused blocks.
1250 * @return number of cleaned blocks.
1253 jirafeau_admin_clean_block ()
1256 /* Get all blocks. */
1257 $stack = array (VAR_BLOCK
);
1258 while (($d = array_shift ($stack)) && $d != NULL)
1260 $dir = scandir ($d);
1262 foreach ($dir as $node)
1264 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0)
1267 if (is_dir ($d . $node))
1269 /* Push new found directory. */
1270 $stack[] = $d . $node . '/';
1272 elseif (is_file ($d . $node) && preg_match ('/\_infos/i', "$node"))
1274 /* Read block informations. */
1275 $f = file ($d . $node);
1276 $date = trim ($f[0]);
1277 $block_size = trim ($f[1]);
1278 if (date ('U') - $date >= JIRAFEAU_MONTH
)
1280 jirafeau_block_delete_ (substr($node, 0, -6));
1290 jirafeau_crypt_create_iv($base, $size)
1293 while (strlen ($iv) < $size)
1295 $iv = substr($iv, 0, $size);
1300 * Crypt file and returns decrypt key.
1301 * @param $fp_src file path to the file to crypt.
1302 * @param $fp_dst file path to the file to write crypted file (could be the same).
1303 * @return decrypt key composed of the key and the iv separated by a point ('.')
1306 jirafeau_encrypt_file ($fp_src, $fp_dst)
1308 $fs = filesize ($fp_src);
1309 if ($fs === false ||
$fs == 0 ||
!extension_loaded('mcrypt'))
1312 /* Prepare module. */
1313 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1315 $crypt_key = jirafeau_gen_random (10);
1316 $md5_key = md5($crypt_key);
1317 $iv = jirafeau_crypt_create_iv ($md5_key, mcrypt_enc_get_iv_size($m));
1319 mcrypt_generic_init($m, $md5_key, $iv);
1321 $r = fopen ($fp_src, 'r');
1322 $w = fopen ($fp_dst, 'c');
1325 $enc = mcrypt_generic($m, fread ($r, 1024));
1326 if (fwrite ($w, $enc) === false)
1332 mcrypt_generic_deinit($m);
1333 mcrypt_module_close($m);
1339 * @param $fp_src file path to the file to decrypt.
1340 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1341 * @param $k string composed of the key and the iv separated by a point ('.')
1342 * @return key used to decrypt. a string of length 0 is returned if failed.
1345 jirafeau_decrypt_file ($fp_src, $fp_dst, $k)
1347 $fs = filesize ($fp_src);
1348 if ($fs === false ||
$fs == 0 ||
!extension_loaded('mcrypt'))
1352 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1353 /* Extract key and iv. */
1355 $md5_key = md5($crypt_key);
1356 $iv = jirafeau_crypt_create_iv ($md5_key, mcrypt_enc_get_iv_size($m));
1358 $r = fopen ($fp_src, 'r');
1359 $w = fopen ($fp_dst, 'c');
1362 $dec = mdecrypt_generic($m, fread ($r, 1024));
1363 if (fwrite ($w, $dec) === false)
1369 mcrypt_generic_deinit($m);
1370 mcrypt_module_close($m);
patrick-canterino.de