]>
git.p6c8.net - jirafeau_mojo42.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 (!is_int ($link_name_length))
321 $link_name_length = 8;
322 if (empty ($file['tmp_name']) ||
!is_uploaded_file ($file['tmp_name']))
326 array ('has_error' => true,
327 'why' => jirafeau_upload_errstr ($file['error'])),
329 'delete_link' => ''));
332 /* array representing no error */
333 $noerr = array ('has_error' => false, 'why' => '');
335 /* Crypt file if option is enabled. */
338 if ($crypt == true && extension_loaded('mcrypt'))
340 $crypt_key = jirafeau_encrypt_file ($file['tmp_name'], $file['tmp_name']);
341 if (strlen($crypt_key) > 0)
345 /* file informations */
346 $md5 = md5_file ($file['tmp_name']);
347 $name = str_replace (NL
, '', trim ($file['name']));
348 $mime_type = $file['type'];
349 $size = $file['size'];
351 /* does file already exist ? */
354 if (file_exists (VAR_FILES
. $p . $md5))
356 $rc = unlink ($file['tmp_name']);
358 elseif ((file_exists (VAR_FILES
. $p) || @mkdir
(VAR_FILES
. $p, 0755, true))
359 && move_uploaded_file ($file['tmp_name'], VAR_FILES
. $p . $md5))
367 array ('has_error' => true,
368 'why' => t('Internal error during file creation.')),
370 'delete_link' => ''));
373 /* Increment or create count file. */
375 if (file_exists (VAR_FILES
. $p . $md5 . '_count'))
377 $content = file (VAR_FILES
. $p . $md5. '_count');
378 $counter = trim ($content[0]);
381 $handle = fopen (VAR_FILES
. $p . $md5. '_count', 'w');
382 fwrite ($handle, $counter);
385 /* Create delete code. */
386 $delete_link_code = jirafeau_gen_random (5);
388 /* md5 password or empty. */
391 $password = md5 ($key);
393 /* create link file */
394 $link_tmp_name = VAR_LINKS
. $md5 . rand (0, 10000) . '.tmp';
395 $handle = fopen ($link_tmp_name, 'w');
397 $name . NL
. $mime_type . NL
. $size . NL
. $password . NL
. $time .
398 NL
. $md5. NL
. ($one_time_download ?
'O' : 'R') . NL
. date ('U') .
399 NL
. $ip . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
401 $md5_link = substr(base_16_to_64 (md5_file ($link_tmp_name)), 0, $link_name_length);
402 $l = s2p ("$md5_link");
403 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
404 !rename ($link_tmp_name, VAR_LINKS
. $l . $md5_link))
406 if (file_exists ($link_tmp_name))
407 unlink ($link_tmp_name);
412 $handle = fopen (VAR_FILES
. $p . $md5. '_count', 'w');
413 fwrite ($handle, $counter);
418 jirafeau_clean_rm_file ($md5_link);
422 array ('has_error' => true,
423 'why' => t('Internal error during file creation. ')),
425 'delete_link' => ''));
427 return (array ('error' => $noerr,
429 'delete_link' => $delete_link_code,
430 'crypt_key' => $crypt_key));
434 * tells if a mime-type is viewable in a browser
435 * @param $mime the mime type
436 * @returns a boolean telling if a mime type is viewable
439 jirafeau_is_viewable ($mime)
443 /* Actually, verify if mime-type is an image or a text. */
444 $viewable = array ('image', 'text');
445 $decomposed = explode ('/', $mime);
446 return in_array ($decomposed[0], $viewable);
451 // Error handling functions.
452 //! Global array that contains all registered errors.
453 $error_list = array ();
456 * Adds an error to the list of errors.
457 * @param $title the error's title
458 * @param $description is a human-friendly description of the problem.
461 add_error ($title, $description)
464 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
468 * Informs whether any error has been registered yet.
469 * @return true if there are errors.
475 return !empty ($error_list);
479 * Displays all the errors.
487 echo '<div class="error">';
488 foreach ($error_list as $error)
496 function check_errors ()
498 if (file_exists (JIRAFEAU_ROOT
. 'install.php')
499 && !file_exists (JIRAFEAU_ROOT
. 'lib/config.local.php'))
501 header('Location: install.php');
505 /* check if the destination dirs are writable */
506 $writable = is_writable (VAR_FILES
) && is_writable (VAR_LINKS
);
508 /* Checking for errors. */
509 if (!is_writable (VAR_FILES
))
510 add_error (t('The file directory is not writable!'), VAR_FILES
);
512 if (!is_writable (VAR_LINKS
))
513 add_error (t('The link directory is not writable!'), VAR_LINKS
);
515 if (!is_writable (VAR_ASYNC
))
516 add_error (t('The async directory is not writable!'), VAR_ASYNC
);
518 if (!is_writable (VAR_BLOCK
))
519 add_error (t('The block directory is not writable!'), VAR_BLOCK
);
521 /* Check if the install.php script is still in the directory. */
522 if (file_exists (JIRAFEAU_ROOT
. 'install.php'))
523 add_error (t('Installer script still present'),
524 t('Please make sure to delete the installer script ' .
525 '"install.php" before continuing.'));
529 * Read link informations
530 * @return array containing informations.
533 jirafeau_get_link ($hash)
536 $link = VAR_LINKS
. s2p ("$hash") . $hash;
538 if (!file_exists ($link))
542 $out['file_name'] = trim ($c[0]);
543 $out['mime_type'] = trim ($c[1]);
544 $out['file_size'] = trim ($c[2]);
545 $out['key'] = trim ($c[3], NL
);
546 $out['time'] = trim ($c[4]);
547 $out['md5'] = trim ($c[5]);
548 $out['onetime'] = trim ($c[6]);
549 $out['upload_date'] = trim ($c[7]);
550 $out['ip'] = trim ($c[8]);
551 $out['link_code'] = trim ($c[9]);
552 if (trim ($c[10]) == 'C')
553 $out['crypted'] = true;
559 * List files in admin interface.
562 jirafeau_admin_list ($name, $file_hash, $link_hash)
564 echo '<fieldset><legend>';
566 echo t('Filename') . ": $name ";
567 if (!empty ($file_hash))
568 echo t('file') . ": $file_hash ";
569 if (!empty ($link_hash))
570 echo t('link') . ": $link_hash ";
571 if (empty ($name) && empty ($file_hash) && empty ($link_hash))
572 echo t('List all files');
576 echo '<td>' . t('Filename') . '</td>';
577 echo '<td>' . t('Type') . '</td>';
578 echo '<td>' . t('Size') . '</td>';
579 echo '<td>' . t('Expire') . '</td>';
580 echo '<td>' . t('Onetime') . '</td>';
581 echo '<td>' . t('Upload date') . '</td>';
582 echo '<td>' . t('Origin') . '</td>';
583 echo '<td>' . t('Action') . '</td>';
586 /* Get all links files. */
587 $stack = array (VAR_LINKS
);
588 while (($d = array_shift ($stack)) && $d != NULL)
591 foreach ($dir as $node)
593 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
594 preg_match ('/\.tmp/i', "$node"))
596 if (is_dir ($d . $node))
598 /* Push new found directory. */
599 $stack[] = $d . $node . '/';
601 elseif (is_file ($d . $node))
603 /* Read link informations. */
604 $l = jirafeau_get_link ($node);
609 if (!empty ($name) && !preg_match ("/$name/i", $l['file_name']))
611 if (!empty ($file_hash) && $file_hash != $l['md5'])
613 if (!empty ($link_hash) && $link_hash != $node)
615 /* Print link informations. */
618 '<form action = "admin.php" method = "post">' .
619 '<input type = "hidden" name = "action" value = "download"/>' .
620 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
621 '<input type = "submit" value = "' . $l['file_name'] . '" />' .
624 echo '<td>' . $l['mime_type'] . '</td>';
625 echo '<td>' . jirafeau_human_size ($l['file_size']) . '</td>';
626 echo '<td>' . ($l['time'] == -1 ?
'' : strftime ('%c', $l['time'])) .
628 echo '<td>' . $l['onetime'] . '</td>';
629 echo '<td>' . strftime ('%c', $l['upload_date']) . '</td>';
630 echo '<td>' . $l['ip'] . '</td>';
632 '<form action = "admin.php" method = "post">' .
633 '<input type = "hidden" name = "action" value = "delete_link"/>' .
634 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
635 '<input type = "submit" value = "' . t('Del link') . '" />' .
637 '<form action = "admin.php" method = "post">' .
638 '<input type = "hidden" name = "action" value = "delete_file"/>' .
639 '<input type = "hidden" name = "md5" value = "' . $l['md5'] . '"/>' .
640 '<input type = "submit" value = "' . t('Del file and links') . '" />' .
647 echo '</table></fieldset>';
651 * Clean expired files.
652 * @return number of cleaned files.
655 jirafeau_admin_clean ()
658 /* Get all links files. */
659 $stack = array (VAR_LINKS
);
660 while (($d = array_shift ($stack)) && $d != NULL)
664 foreach ($dir as $node)
666 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
667 preg_match ('/\.tmp/i', "$node"))
670 if (is_dir ($d . $node))
672 /* Push new found directory. */
673 $stack[] = $d . $node . '/';
675 elseif (is_file ($d . $node))
677 /* Read link informations. */
678 $l = jirafeau_get_link (basename ($node));
681 $p = s2p ($l['md5']);
682 if ($l['time'] > 0 && $l['time'] < time () ||
// expired
683 !file_exists (VAR_FILES
. $p . $l['md5']) ||
// invalid
684 !file_exists (VAR_FILES
. $p . $l['md5'] . '_count')) // invalid
686 jirafeau_delete_link ($node);
697 * Clean old async transferts.
698 * @return number of cleaned files.
701 jirafeau_admin_clean_async ()
704 /* Get all links files. */
705 $stack = array (VAR_ASYNC
);
706 while (($d = array_shift ($stack)) && $d != NULL)
710 foreach ($dir as $node)
712 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
713 preg_match ('/\.tmp/i', "$node"))
716 if (is_dir ($d . $node))
718 /* Push new found directory. */
719 $stack[] = $d . $node . '/';
721 elseif (is_file ($d . $node))
723 /* Read async informations. */
724 $a = jirafeau_get_async_ref (basename ($node));
727 /* Delete transferts older than 1 hour. */
728 if (date ('U') - $a['last_edited'] > 3600)
730 jirafeau_async_delete (basename ($node));
739 * Read async transfert informations
740 * @return array containing informations.
743 jirafeau_get_async_ref ($ref)
746 $refinfos = VAR_ASYNC
. s2p ("$ref") . "$ref";
748 if (!file_exists ($refinfos))
751 $c = file ($refinfos);
752 $out['file_name'] = trim ($c[0]);
753 $out['mime_type'] = trim ($c[1]);
754 $out['key'] = trim ($c[2], NL
);
755 $out['time'] = trim ($c[3]);
756 $out['onetime'] = trim ($c[4]);
757 $out['ip'] = trim ($c[5]);
758 $out['last_edited'] = trim ($c[6]);
759 $out['next_code'] = trim ($c[7]);
764 * Delete async transfert informations
767 jirafeau_async_delete ($ref)
770 if (file_exists (VAR_ASYNC
. $p . $ref))
771 unlink (VAR_ASYNC
. $p . $ref);
772 if (file_exists (VAR_ASYNC
. $p . $ref . '_data'))
773 unlink (VAR_ASYNC
. $p . $ref . '_data');
774 $parse = VAR_ASYNC
. $p;
776 while (file_exists ($parse)
777 && ($scan = scandir ($parse))
778 && count ($scan) == 2 // '.' and '..' folders => empty.
779 && basename ($parse) != basename (VAR_ASYNC
))
782 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
787 * Init a new asynchronous upload.
788 * @param $finename Name of the file to send
789 * @param $one_time One time upload parameter
790 * @param $key eventual password (or blank)
791 * @param $time time limit
792 * @param $ip ip address of the client
793 * @return a string containing a temporary reference followed by a code or the string "Error"
796 jirafeau_async_init ($filename, $type, $one_time, $key, $time, $ip)
800 /* Create temporary folder. */
803 $code = jirafeau_gen_random (4);
806 $ref = jirafeau_gen_random (32);
807 $p = VAR_ASYNC
. s2p ($ref);
808 } while (file_exists ($p));
809 @mkdir
($p, 0755, true);
810 if (!file_exists ($p))
816 /* md5 password or empty */
819 $password = md5 ($key);
821 /* Store informations. */
823 $handle = fopen ($p, 'w');
825 str_replace (NL
, '', trim ($filename)) . NL
.
826 str_replace (NL
, '', trim ($type)) . NL
. $password . NL
.
827 $time . NL
. ($one_time ?
'O' : 'R') . NL
. $ip . NL
.
828 date ('U') . NL
. $code . NL
);
831 return $ref . NL
. $code ;
835 * Append a piece of file on the asynchronous upload.
836 * @param $ref asynchronous upload reference
837 * @param $file piece of data
838 * @param $code client code for this operation
839 * @return a string containing a next code to use or the string "Error"
842 jirafeau_async_push ($ref, $data, $code)
844 /* Get async infos. */
845 $a = jirafeau_get_async_ref ($ref);
847 /* Check some errors. */
849 ||
$a['next_code'] != "$code"
850 ||
empty ($data['tmp_name'])
851 ||
!is_uploaded_file ($data['tmp_name']))
856 /* Concatenate data. */
857 $r = fopen ($data['tmp_name'], 'r');
858 $w = fopen (VAR_ASYNC
. $p . $ref . '_data', 'a');
861 if (fwrite ($w, fread ($r, 1024)) === false)
865 jirafeau_async_delete ($ref);
871 unlink ($data['tmp_name']);
873 /* Update async file. */
874 $code = jirafeau_gen_random (4);
875 $handle = fopen (VAR_ASYNC
. $p . $ref, 'w');
877 $a['file_name'] . NL
. $a['mime_type'] . NL
. $a['key'] . NL
.
878 $a['time'] . NL
. $a['onetime'] . NL
. $a['ip'] . NL
.
879 date ('U') . NL
. $code . NL
);
885 * Finalyze an asynchronous upload.
886 * @param $ref asynchronous upload reference
887 * @param $code client code for this operation
888 * @param $crypt boolean asking to crypt or not
889 * @param $link_name_length link name lenght
890 * @return a string containing the download reference followed by a delete code or the string "Error"
893 jirafeau_async_end ($ref, $code, $crypt, $link_name_length)
895 if (!is_int ($link_name_length))
896 $link_name_length = 8;
897 /* Get async infos. */
898 $a = jirafeau_get_async_ref ($ref);
900 ||
$a['next_code'] != "$code")
903 /* Generate link infos. */
904 $p = VAR_ASYNC
. s2p ($ref) . $ref . "_data";
905 if (!file_exists($p))
910 if ($crypt == true && extension_loaded('mcrypt'))
912 $cypt_key = jirafeau_encrypt_file ($p, $p);
913 if (strlen($crypt_key) > 0)
917 $md5 = md5_file ($p);
918 $size = filesize($p);
920 $delete_link_code = jirafeau_gen_random (5);
922 /* File already exist ? */
923 if (!file_exists (VAR_FILES
. $np))
924 @mkdir
(VAR_FILES
. $np, 0755, true);
925 if (!file_exists (VAR_FILES
. $np . $md5))
926 rename ($p, VAR_FILES
. $np . $md5);
928 /* Increment or create count file. */
930 if (file_exists (VAR_FILES
. $np . $md5 . '_count'))
932 $content = file (VAR_FILES
. $np . $md5. '_count');
933 $counter = trim ($content[0]);
936 $handle = fopen (VAR_FILES
. $np . $md5. '_count', 'w');
937 fwrite ($handle, $counter);
941 $link_tmp_name = VAR_LINKS
. $md5 . rand (0, 10000) . '.tmp';
942 $handle = fopen ($link_tmp_name, 'w');
944 $a['file_name'] . NL
. $a['mime_type'] . NL
. $size . NL
.
945 $a['key'] . NL
. $a['time'] . NL
. $md5 . NL
. $a['onetime'] . NL
.
946 date ('U') . NL
. $a['ip'] . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
948 $md5_link = substr(base_16_to_64 (md5_file ($link_tmp_name)), 0, $link_name_length);
949 $l = s2p ("$md5_link");
950 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
951 !rename ($link_tmp_name, VAR_LINKS
. $l . $md5_link))
954 /* Clean async upload. */
955 jirafeau_async_delete ($ref);
956 return $md5_link . NL
. $delete_link_code . NL
. urlencode($crypt_key);
961 * @param $id identifier of the block.
964 jirafeau_block_delete_ ($id)
966 $p = VAR_BLOCK
. s2p ($id);
967 if (!file_exists ($p))
970 if (file_exists ($p . $id))
972 if (file_exists ($p . $id . '_infos'))
973 unlink ($p . $id . '_infos');
976 while (file_exists ($parse)
977 && ($scan = scandir ($parse))
978 && count ($scan) == 2 // '.' and '..' folders => empty.
979 && basename ($parse) != basename (VAR_BLOCK
))
982 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
987 * Create a file filled with zeros.
988 * @param $size size of the file.
989 * @return a string corresponding to an id or the string "Error"
992 jirafeau_block_init ($size)
994 if (!ctype_digit ($size) ||
$size <= 0)
1001 $id = jirafeau_gen_random (32);
1002 $p = VAR_BLOCK
. s2p ($id);
1003 } while (file_exists ($p));
1004 @mkdir
($p, 0755, true);
1005 if (!file_exists ($p))
1013 $h = fopen ($p, 'w');
1014 $fill = str_repeat ("\0", 1024);
1015 for ($cnt = 0; $cnt < $size; $cnt +
= 1024)
1017 if ($size - $cnt < 1024)
1018 $fill = str_repeat ("\0", $size - $cnt);
1019 if (fwrite ($h, $fill) === false)
1022 jirafeau_block_delete_ ($id);
1028 /* Generate a write/delete code. */
1029 $code = jirafeau_gen_random (12);
1031 /* Add block infos. */
1032 if (file_put_contents ($p . '_infos', date ('U') . NL
. $size . NL
. $code) === FALSE)
1034 jirafeau_block_delete_ ($id);
1038 return $id . NL
. $code;
1041 /** Get block size in bytes.
1042 * @param $id identifier of the block
1043 * @return block size in bytes
1046 jirafeau_block_get_size ($id)
1048 $p = VAR_BLOCK
. s2p ($id) . $id;
1049 if (!file_exists ($p))
1053 $f = file ($p . '_infos');
1054 $date = trim ($f[0]);
1055 $block_size = trim ($f[1]);
1056 $stored_code = trim ($f[2]);
1058 if (date ('U') - $date > JIRAFEAU_HOUR
1059 && date ('U') - $date < JIRAFEAU_MONTH
)
1061 if (file_put_contents ($p . '_infos', date ('U') . NL
. $block_size . NL
. $stored_code) === FALSE)
1063 jirafeau_block_delete_ ($id);
1068 elseif (date ('U') - $date >= JIRAFEAU_MONTH
)
1070 echo date ('U'). " $date ";
1071 jirafeau_block_delete_ ($id);
1079 * Read some data in a block.
1080 * @param $id identifier of the block
1081 * @param $start where to read data (starting from zero).
1082 * @param $length length to read.
1086 jirafeau_block_read ($id, $start, $length)
1088 if (!ctype_digit ($start) ||
$start < 0
1089 ||
!ctype_digit ($length) ||
$length <= 0)
1095 $p = VAR_BLOCK
. s2p ($id) . $id;
1096 if (!file_exists ($p))
1103 $f = file ($p . '_infos');
1104 $date = trim ($f[0]);
1105 $block_size = trim ($f[1]);
1106 $stored_code = trim ($f[2]);
1108 if (date ('U') - $date > JIRAFEAU_HOUR
1109 && date ('U') - $date < JIRAFEAU_MONTH
)
1111 if (file_put_contents ($p . '_infos', date ('U') . NL
. $block_size . NL
. $stored_code) === FALSE)
1113 jirafeau_block_delete_ ($id);
1119 elseif (date ('U') - $date >= JIRAFEAU_MONTH
)
1121 echo date ('U'). " $date ";
1122 jirafeau_block_delete_ ($id);
1127 if ($start +
$length > $block_size)
1134 header ('Content-Length: ' . $length);
1135 header ('Content-Disposition: attachment');
1137 $r = fopen ($p, 'r');
1138 if (fseek ($r, $start) != 0)
1144 for ($cnt = 0; $cnt < $length && !feof ($r); $cnt +
= 1024)
1146 if ($length - $cnt < 1024)
1147 $c = $length - $cnt;
1148 print fread ($r, $c);
1155 * Write some data in a block.
1156 * @param $id identifier of the block
1157 * @param $start where to writing data (starting from zero).
1158 * @param $data data to write.
1159 * @param $code code to allow writing.
1160 * @return string "Ok" or string "Error".
1163 jirafeau_block_write ($id, $start, $data, $code)
1165 if (!ctype_digit ($start) ||
$start < 0
1166 ||
strlen ($code) == 0)
1169 $p = VAR_BLOCK
. s2p ($id) . $id;
1170 if (!file_exists ($p))
1174 $f = file ($p . '_infos');
1175 $date = trim ($f[0]);
1176 $block_size = trim ($f[1]);
1177 $stored_code = trim ($f[2]);
1179 if (date ('U') - $date > JIRAFEAU_HOUR
1180 && date ('U') - $date < JIRAFEAU_MONTH
)
1182 if (file_put_contents ($p . '_infos', date ('U') . NL
. $block_size . NL
. $stored_code) === FALSE)
1184 jirafeau_block_delete_ ($id);
1189 elseif (date ('U') - $date >= JIRAFEAU_MONTH
)
1191 jirafeau_block_delete_ ($id);
1196 if ($stored_code != $code)
1203 $size = $data['size'];
1206 if ($start +
$size > $block_size)
1210 $r = fopen ($data['tmp_name'], 'r');
1213 $w = fopen ($p, 'r+');
1214 if (fseek ($w, $start) != 0)
1217 /* Write content. */
1219 for ($cnt = 0; $cnt <= $size && !feof ($w); $cnt +
= 1024)
1221 if ($size - $cnt < 1024)
1223 $d = fread ($r, $c);
1228 unlink ($data['tmp_name']);
1234 * @param $id identifier of the block.
1235 * @param $code code to allow writing.
1236 * @return string "Ok" or string "Error".
1239 jirafeau_block_delete ($id, $code)
1241 $p = VAR_BLOCK
. s2p ($id) . $id;
1243 if (!file_exists ($p))
1246 $f = file ($p . '_infos');
1247 $date = trim ($f[0]);
1248 $block_size = trim ($f[1]);
1249 $stored_code = trim ($f[2]);
1251 if ($code != $stored_code)
1254 jirafeau_block_delete_ ($id);
1259 * Clean old unused blocks.
1260 * @return number of cleaned blocks.
1263 jirafeau_admin_clean_block ()
1266 /* Get all blocks. */
1267 $stack = array (VAR_BLOCK
);
1268 while (($d = array_shift ($stack)) && $d != NULL)
1270 $dir = scandir ($d);
1272 foreach ($dir as $node)
1274 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0)
1277 if (is_dir ($d . $node))
1279 /* Push new found directory. */
1280 $stack[] = $d . $node . '/';
1282 elseif (is_file ($d . $node) && preg_match ('/\_infos/i', "$node"))
1284 /* Read block informations. */
1285 $f = file ($d . $node);
1286 $date = trim ($f[0]);
1287 $block_size = trim ($f[1]);
1288 if (date ('U') - $date >= JIRAFEAU_MONTH
)
1290 jirafeau_block_delete_ (substr($node, 0, -6));
1300 jirafeau_crypt_create_iv($base, $size)
1303 while (strlen ($iv) < $size)
1305 $iv = substr($iv, 0, $size);
1310 * Crypt file and returns decrypt key.
1311 * @param $fp_src file path to the file to crypt.
1312 * @param $fp_dst file path to the file to write crypted file (could be the same).
1313 * @return decrypt key composed of the key and the iv separated by a point ('.')
1316 jirafeau_encrypt_file ($fp_src, $fp_dst)
1318 $fs = filesize ($fp_src);
1319 if ($fs === false ||
$fs == 0 ||
!extension_loaded('mcrypt'))
1322 /* Prepare module. */
1323 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1325 $crypt_key = jirafeau_gen_random (10);
1326 $md5_key = md5($crypt_key);
1327 $iv = jirafeau_crypt_create_iv ($md5_key, mcrypt_enc_get_iv_size($m));
1329 mcrypt_generic_init($m, $md5_key, $iv);
1331 $r = fopen ($fp_src, 'r');
1332 $w = fopen ($fp_dst, 'c');
1335 $enc = mcrypt_generic($m, fread ($r, 1024));
1336 if (fwrite ($w, $enc) === false)
1342 mcrypt_generic_deinit($m);
1343 mcrypt_module_close($m);
1349 * @param $fp_src file path to the file to decrypt.
1350 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1351 * @param $k string composed of the key and the iv separated by a point ('.')
1352 * @return key used to decrypt. a string of length 0 is returned if failed.
1355 jirafeau_decrypt_file ($fp_src, $fp_dst, $k)
1357 $fs = filesize ($fp_src);
1358 if ($fs === false ||
$fs == 0 ||
!extension_loaded('mcrypt'))
1362 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1363 /* Extract key and iv. */
1365 $md5_key = md5($crypt_key);
1366 $iv = jirafeau_crypt_create_iv ($md5_key, mcrypt_enc_get_iv_size($m));
1368 $r = fopen ($fp_src, 'r');
1369 $w = fopen ($fp_dst, 'c');
1372 $dec = mdecrypt_generic($m, fread ($r, 1024));
1373 if (fwrite ($w, $dec) === false)
1379 mcrypt_generic_deinit($m);
1380 mcrypt_module_close($m);
patrick-canterino.de