]>
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 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;
131 while (file_exists ($parse)
132 && ($scan = scandir ($parse))
133 && count ($scan) == 2 // '.' and '..' folders => empty.
134 && basename ($parse) != basename (VAR_FILES
))
137 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
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
146 function jirafeau_ini_to_bytes ($value)
148 $modifier = substr ($value, -1);
149 $bytes = substr ($value, 0, -1);
150 switch (strtoupper ($modifier))
169 * gets the maximum upload size according to php.ini
170 * @returns the maximum upload size in bytes
173 jirafeau_get_max_upload_size_bytes ()
175 return min (jirafeau_ini_to_bytes (ini_get ('post_max_size')),
176 jirafeau_ini_to_bytes (ini_get ('upload_max_filesize')));
180 * gets the maximum upload size according to php.ini
181 * @returns the maximum upload size string
184 jirafeau_get_max_upload_size ()
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'))));
192 * gets a string explaining the error
193 * @param $code the error code
194 * @returns a string explaining the error
197 jirafeau_upload_errstr ($code)
201 case UPLOAD_ERR_INI_SIZE
:
202 case UPLOAD_ERR_FORM_SIZE
:
203 return t('Your file exceeds the maximum authorized file size. ');
206 case UPLOAD_ERR_PARTIAL
:
207 case UPLOAD_ERR_NO_FILE
:
210 ('Your file was not uploaded correctly. You may succeed in retrying. ');
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. ');
222 return t('Unknown error. ');
225 /** Remove link and it's file
226 * @param $link the link's name (hash)
230 jirafeau_delete_link ($link)
232 $l = jirafeau_get_link ($link);
236 jirafeau_clean_rm_link ($link);
242 if (file_exists (VAR_FILES
. $p . $md5. '_count'))
244 $content = file (VAR_FILES
. $p . $md5. '_count');
245 $counter = trim ($content[0]);
251 $handle = fopen (VAR_FILES
. $p . $md5. '_count', 'w');
252 fwrite ($handle, $counter);
257 jirafeau_clean_rm_file ($md5);
261 * Delete a file and it's links.
264 jirafeau_delete_file ($md5)
267 /* Get all links files. */
268 $stack = array (VAR_LINKS
);
269 while (($d = array_shift ($stack)) && $d != NULL)
273 foreach ($dir as $node)
275 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
276 preg_match ('/\.tmp/i', "$node"))
279 if (is_dir ($d . $node))
281 /* Push new found directory. */
282 $stack[] = $d . $node . '/';
284 elseif (is_file ($d . $node))
286 /* Read link informations. */
287 $l = jirafeau_get_link (basename ($node));
290 if ($l['md5'] == $md5)
293 jirafeau_delete_link ($node);
298 jirafeau_clean_rm_file ($md5);
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 * @param $crypt boolean asking to crypt or not
310 * @returns an array containing some information
311 * 'error' => information on possible errors
312 * 'link' => the link name of the uploaded file
313 * 'delete_link' => the link code to delete file
316 jirafeau_upload ($file, $one_time_download, $key, $time, $ip, $crypt)
318 if (empty ($file['tmp_name']) ||
!is_uploaded_file ($file['tmp_name']))
322 array ('has_error' => true,
323 'why' => jirafeau_upload_errstr ($file['error'])),
325 'delete_link' => ''));
328 /* array representing no error */
329 $noerr = array ('has_error' => false, 'why' => '');
331 /* Crypt file if option is enabled. */
334 if ($crypt == true && extension_loaded('mcrypt'))
336 $crypt_key = jirafeau_encrypt_file ($file['tmp_name'], $file['tmp_name']);
337 if (strlen($crypt_key) > 0)
341 /* file informations */
342 $md5 = md5_file ($file['tmp_name']);
343 $name = str_replace (NL
, '', trim ($file['name']));
344 $mime_type = $file['type'];
345 $size = $file['size'];
347 /* does file already exist ? */
350 if (file_exists (VAR_FILES
. $p . $md5))
352 $rc = unlink ($file['tmp_name']);
354 elseif ((file_exists (VAR_FILES
. $p) || @mkdir
(VAR_FILES
. $p, 0755, true))
355 && move_uploaded_file ($file['tmp_name'], VAR_FILES
. $p . $md5))
363 array ('has_error' => true,
364 'why' => t('Internal error during file creation.')),
366 'delete_link' => ''));
369 /* Increment or create count file. */
371 if (file_exists (VAR_FILES
. $p . $md5 . '_count'))
373 $content = file (VAR_FILES
. $p . $md5. '_count');
374 $counter = trim ($content[0]);
377 $handle = fopen (VAR_FILES
. $p . $md5. '_count', 'w');
378 fwrite ($handle, $counter);
381 /* Create delete code. */
382 $delete_link_code = jirafeau_gen_random (8);
384 /* md5 password or empty. */
387 $password = md5 ($key);
389 /* create link file */
390 $link_tmp_name = VAR_LINKS
. $md5 . rand (0, 10000) . ' .tmp';
391 $handle = fopen ($link_tmp_name, 'w');
393 $name . NL
. $mime_type . NL
. $size . NL
. $password . NL
. $time .
394 NL
. $md5. NL
. ($one_time_download ?
'O' : 'R') . NL
. date ('U') .
395 NL
. $ip . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
397 $md5_link = base_16_to_64 (md5_file ($link_tmp_name));
398 $l = s2p ("$md5_link");
399 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
400 !rename ($link_tmp_name, VAR_LINKS
. $l . $md5_link))
402 if (file_exists ($link_tmp_name))
403 unlink ($link_tmp_name);
408 $handle = fopen (VAR_FILES
. $p . $md5. '_count', 'w');
409 fwrite ($handle, $counter);
414 jirafeau_clean_rm_file ($md5_link);
418 array ('has_error' => true,
419 'why' => t('Internal error during file creation. ')),
421 'delete_link' => ''));
423 return (array ('error' => $noerr,
425 'delete_link' => $delete_link_code,
426 'crypt_key' => $crypt_key));
430 * tells if a mime-type is viewable in a browser
431 * @param $mime the mime type
432 * @returns a boolean telling if a mime type is viewable
435 jirafeau_is_viewable ($mime)
439 /* Actually, verify if mime-type is an image or a text. */
440 $viewable = array ('image', 'text');
441 $decomposed = explode ('/', $mime);
442 return in_array ($decomposed[0], $viewable);
447 // Error handling functions.
448 //! Global array that contains all registered errors.
449 $error_list = array ();
452 * Adds an error to the list of errors.
453 * @param $title the error's title
454 * @param $description is a human-friendly description of the problem.
457 add_error ($title, $description)
460 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
464 * Informs whether any error has been registered yet.
465 * @return true if there are errors.
471 return !empty ($error_list);
475 * Displays all the errors.
483 echo '<div class="error">';
484 foreach ($error_list as $error)
492 function check_errors ()
494 if (file_exists (JIRAFEAU_ROOT
. 'install.php')
495 && !file_exists (JIRAFEAU_ROOT
. 'lib/config.local.php'))
497 header('Location: install.php');
501 /* check if the destination dirs are writable */
502 $writable = is_writable (VAR_FILES
) && is_writable (VAR_LINKS
);
504 /* Checking for errors. */
505 if (!is_writable (VAR_FILES
))
506 add_error (t('The file directory is not writable!'), VAR_FILES
);
508 if (!is_writable (VAR_LINKS
))
509 add_error (t('The link directory is not writable!'), VAR_LINKS
);
511 if (!is_writable (VAR_ASYNC
))
512 add_error (t('The async directory is not writable!'), VAR_ASYNC
);
514 if (!is_writable (VAR_BLOCK
))
515 add_error (t('The block directory is not writable!'), VAR_BLOCK
);
517 /* Check if the install.php script is still in the directory. */
518 if (file_exists (JIRAFEAU_ROOT
. 'install.php'))
519 add_error (t('Installer script still present'),
520 t('Please make sure to delete the installer script ' .
521 '"install.php" before continuing.'));
525 * Read link informations
526 * @return array containing informations.
529 jirafeau_get_link ($hash)
532 $link = VAR_LINKS
. s2p ("$hash") . $hash;
534 if (!file_exists ($link))
538 $out['file_name'] = trim ($c[0]);
539 $out['mime_type'] = trim ($c[1]);
540 $out['file_size'] = trim ($c[2]);
541 $out['key'] = trim ($c[3], NL
);
542 $out['time'] = trim ($c[4]);
543 $out['md5'] = trim ($c[5]);
544 $out['onetime'] = trim ($c[6]);
545 $out['upload_date'] = trim ($c[7]);
546 $out['ip'] = trim ($c[8]);
547 $out['link_code'] = trim ($c[9]);
548 if (trim ($c[10]) == 'C')
549 $out['crypted'] = true;
555 * List files in admin interface.
558 jirafeau_admin_list ($name, $file_hash, $link_hash)
560 echo '<fieldset><legend>';
562 echo t('Filename') . ": $name ";
563 if (!empty ($file_hash))
564 echo t('file') . ": $file_hash ";
565 if (!empty ($link_hash))
566 echo t('link') . ": $link_hash ";
567 if (empty ($name) && empty ($file_hash) && empty ($link_hash))
568 echo t('List all files');
572 echo '<td>' . t('Filename') . '</td>';
573 echo '<td>' . t('Type') . '</td>';
574 echo '<td>' . t('Size') . '</td>';
575 echo '<td>' . t('Expire') . '</td>';
576 echo '<td>' . t('Onetime') . '</td>';
577 echo '<td>' . t('Upload date') . '</td>';
578 echo '<td>' . t('Origin') . '</td>';
579 echo '<td>' . t('Action') . '</td>';
582 /* Get all links files. */
583 $stack = array (VAR_LINKS
);
584 while (($d = array_shift ($stack)) && $d != NULL)
587 foreach ($dir as $node)
589 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
590 preg_match ('/\.tmp/i', "$node"))
592 if (is_dir ($d . $node))
594 /* Push new found directory. */
595 $stack[] = $d . $node . '/';
597 elseif (is_file ($d . $node))
599 /* Read link informations. */
600 $l = jirafeau_get_link ($node);
605 if (!empty ($name) && !preg_match ("/$name/i", $l['file_name']))
607 if (!empty ($file_hash) && $file_hash != $l['md5'])
609 if (!empty ($link_hash) && $link_hash != $node)
611 /* Print link informations. */
614 '<form action = "admin.php" method = "post">' .
615 '<input type = "hidden" name = "action" value = "download"/>' .
616 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
617 '<input type = "submit" value = "' . $l['file_name'] . '" />' .
620 echo '<td>' . $l['mime_type'] . '</td>';
621 echo '<td>' . jirafeau_human_size ($l['file_size']) . '</td>';
622 echo '<td>' . ($l['time'] == -1 ?
'' : strftime ('%c', $l['time'])) .
624 echo '<td>' . $l['onetime'] . '</td>';
625 echo '<td>' . strftime ('%c', $l['upload_date']) . '</td>';
626 echo '<td>' . $l['ip'] . '</td>';
628 '<form action = "admin.php" method = "post">' .
629 '<input type = "hidden" name = "action" value = "delete_link"/>' .
630 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
631 '<input type = "submit" value = "' . t('Del link') . '" />' .
633 '<form action = "admin.php" method = "post">' .
634 '<input type = "hidden" name = "action" value = "delete_file"/>' .
635 '<input type = "hidden" name = "md5" value = "' . $l['md5'] . '"/>' .
636 '<input type = "submit" value = "' . t('Del file and links') . '" />' .
643 echo '</table></fieldset>';
647 * Clean expired files.
648 * @return number of cleaned files.
651 jirafeau_admin_clean ()
654 /* Get all links files. */
655 $stack = array (VAR_LINKS
);
656 while (($d = array_shift ($stack)) && $d != NULL)
660 foreach ($dir as $node)
662 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
663 preg_match ('/\.tmp/i', "$node"))
666 if (is_dir ($d . $node))
668 /* Push new found directory. */
669 $stack[] = $d . $node . '/';
671 elseif (is_file ($d . $node))
673 /* Read link informations. */
674 $l = jirafeau_get_link (basename ($node));
677 $p = s2p ($l['md5']);
678 if ($l['time'] > 0 && $l['time'] < time () ||
// expired
679 !file_exists (VAR_FILES
. $p . $l['md5']) ||
// invalid
680 !file_exists (VAR_FILES
. $p . $l['md5'] . '_count')) // invalid
682 jirafeau_delete_link ($node);
693 * Clean old async transferts.
694 * @return number of cleaned files.
697 jirafeau_admin_clean_async ()
700 /* Get all links files. */
701 $stack = array (VAR_ASYNC
);
702 while (($d = array_shift ($stack)) && $d != NULL)
706 foreach ($dir as $node)
708 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
709 preg_match ('/\.tmp/i', "$node"))
712 if (is_dir ($d . $node))
714 /* Push new found directory. */
715 $stack[] = $d . $node . '/';
717 elseif (is_file ($d . $node))
719 /* Read async informations. */
720 $a = jirafeau_get_async_ref (basename ($node));
723 /* Delete transferts older than 1 hour. */
724 if (date ('U') - $a['last_edited'] > 3600)
726 jirafeau_async_delete (basename ($node));
735 * Read async transfert informations
736 * @return array containing informations.
739 jirafeau_get_async_ref ($ref)
742 $refinfos = VAR_ASYNC
. s2p ("$ref") . "$ref";
744 if (!file_exists ($refinfos))
747 $c = file ($refinfos);
748 $out['file_name'] = trim ($c[0]);
749 $out['mime_type'] = trim ($c[1]);
750 $out['key'] = trim ($c[2], NL
);
751 $out['time'] = trim ($c[3]);
752 $out['onetime'] = trim ($c[4]);
753 $out['ip'] = trim ($c[5]);
754 $out['last_edited'] = trim ($c[6]);
755 $out['next_code'] = trim ($c[7]);
760 * Delete async transfert informations
763 jirafeau_async_delete ($ref)
766 if (file_exists (VAR_ASYNC
. $p . $ref))
767 unlink (VAR_ASYNC
. $p . $ref);
768 if (file_exists (VAR_ASYNC
. $p . $ref . '_data'))
769 unlink (VAR_ASYNC
. $p . $ref . '_data');
770 $parse = VAR_ASYNC
. $p;
772 while (file_exists ($parse)
773 && ($scan = scandir ($parse))
774 && count ($scan) == 2 // '.' and '..' folders => empty.
775 && basename ($parse) != basename (VAR_ASYNC
))
778 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
783 * Init a new asynchronous upload.
784 * @param $finename Name of the file to send
785 * @param $one_time One time upload parameter
786 * @param $key eventual password (or blank)
787 * @param $time time limit
788 * @param $ip ip address of the client
789 * @return a string containing a temporary reference followed by a code or the string "Error"
792 jirafeau_async_init ($filename, $type, $one_time, $key, $time, $ip)
796 /* Create temporary folder. */
799 $code = jirafeau_gen_random (4);
802 $ref = jirafeau_gen_random (32);
803 $p = VAR_ASYNC
. s2p ($ref);
804 } while (file_exists ($p));
805 @mkdir
($p, 0755, true);
806 if (!file_exists ($p))
812 /* md5 password or empty */
815 $password = md5 ($key);
817 /* Store informations. */
819 $handle = fopen ($p, 'w');
821 str_replace (NL
, '', trim ($filename)) . NL
.
822 str_replace (NL
, '', trim ($type)) . NL
. $password . NL
.
823 $time . NL
. ($one_time ?
'O' : 'R') . NL
. $ip . NL
.
824 date ('U') . NL
. $code . NL
);
827 return $ref . NL
. $code ;
831 * Append a piece of file on the asynchronous upload.
832 * @param $ref asynchronous upload reference
833 * @param $file piece of data
834 * @param $code client code for this operation
835 * @return a string containing a next code to use or the string "Error"
838 jirafeau_async_push ($ref, $data, $code)
840 /* Get async infos. */
841 $a = jirafeau_get_async_ref ($ref);
843 /* Check some errors. */
845 ||
$a['next_code'] != "$code"
846 ||
empty ($data['tmp_name'])
847 ||
!is_uploaded_file ($data['tmp_name']))
852 /* Concatenate data. */
853 $r = fopen ($data['tmp_name'], 'r');
854 $w = fopen (VAR_ASYNC
. $p . $ref . '_data', 'a');
857 if (fwrite ($w, fread ($r, 1024)) === false)
861 jirafeau_async_delete ($ref);
867 unlink ($data['tmp_name']);
869 /* Update async file. */
870 $code = jirafeau_gen_random (4);
871 $handle = fopen (VAR_ASYNC
. $p . $ref, 'w');
873 $a['file_name'] . NL
. $a['mime_type'] . NL
. $a['key'] . NL
.
874 $a['time'] . NL
. $a['onetime'] . NL
. $a['ip'] . NL
.
875 date ('U') . NL
. $code . NL
);
881 * Finalyze an asynchronous upload.
882 * @param $ref asynchronous upload reference
883 * @param $code client code for this operation
884 * @param $crypt boolean asking to crypt or not
885 * @return a string containing the download reference followed by a delete code or the string "Error"
888 jirafeau_async_end ($ref, $code, $crypt)
890 /* Get async infos. */
891 $a = jirafeau_get_async_ref ($ref);
893 ||
$a['next_code'] != "$code")
896 /* Generate link infos. */
897 $p = VAR_ASYNC
. s2p ($ref) . $ref . "_data";
898 if (!file_exists($p))
903 if ($crypt == true && extension_loaded('mcrypt'))
905 $cypt_key = jirafeau_encrypt_file ($p, $p);
906 if (strlen($crypt_key) > 0)
910 $md5 = md5_file ($p);
911 $size = filesize($p);
913 $delete_link_code = jirafeau_gen_random (8);
915 /* File already exist ? */
916 if (!file_exists (VAR_FILES
. $np))
917 @mkdir
(VAR_FILES
. $np, 0755, true);
918 if (!file_exists (VAR_FILES
. $np . $md5))
919 rename ($p, VAR_FILES
. $np . $md5);
921 /* Increment or create count file. */
923 if (file_exists (VAR_FILES
. $np . $md5 . '_count'))
925 $content = file (VAR_FILES
. $np . $md5. '_count');
926 $counter = trim ($content[0]);
929 $handle = fopen (VAR_FILES
. $np . $md5. '_count', 'w');
930 fwrite ($handle, $counter);
934 $link_tmp_name = VAR_LINKS
. $md5 . rand (0, 10000) . ' .tmp';
935 $handle = fopen ($link_tmp_name, 'w');
937 $a['file_name'] . NL
. $a['mime_type'] . NL
. $size . NL
.
938 $a['key'] . NL
. $a['time'] . NL
. $md5 . NL
. $a['onetime'] . NL
.
939 date ('U') . NL
. $a['ip'] . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
941 $md5_link = base_16_to_64 (md5_file ($link_tmp_name));
942 $l = s2p ("$md5_link");
943 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
944 !rename ($link_tmp_name, VAR_LINKS
. $l . $md5_link))
947 /* Clean async upload. */
948 jirafeau_async_delete ($ref);
949 return $md5_link . NL
. $delete_link_code . NL
. urlencode($crypt_key);
954 * @param $id identifier of the block.
957 jirafeau_block_delete_ ($id)
959 $p = VAR_BLOCK
. s2p ($id);
960 if (!file_exists ($p))
963 if (file_exists ($p . $id))
965 if (file_exists ($p . $id . '_infos'))
966 unlink ($p . $id . '_infos');
969 while (file_exists ($parse)
970 && ($scan = scandir ($parse))
971 && count ($scan) == 2 // '.' and '..' folders => empty.
972 && basename ($parse) != basename (VAR_BLOCK
))
975 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
980 * Create a file filled with zeros.
981 * @param $size size of the file.
982 * @return a string corresponding to an id or the string "Error"
985 jirafeau_block_init ($size)
987 if (!ctype_digit ($size) ||
$size <= 0)
994 $id = jirafeau_gen_random (32);
995 $p = VAR_BLOCK
. s2p ($id);
996 } while (file_exists ($p));
997 @mkdir
($p, 0755, true);
998 if (!file_exists ($p))
1006 $h = fopen ($p, 'w');
1007 $fill = str_repeat ("\0", 1024);
1008 for ($cnt = 0; $cnt < $size; $cnt +
= 1024)
1010 if ($size - $cnt < 1024)
1011 $fill = str_repeat ("\0", $size - $cnt);
1012 if (fwrite ($h, $fill) === false)
1015 jirafeau_block_delete_ ($id);
1021 /* Generate a write/delete code. */
1022 $code = jirafeau_gen_random (12);
1024 /* Add block infos. */
1025 if (file_put_contents ($p . '_infos', date ('U') . NL
. $size . NL
. $code) === FALSE)
1027 jirafeau_block_delete_ ($id);
1031 return $id . NL
. $code;
1034 /** Get block size in bytes.
1035 * @param $id identifier of the block
1036 * @return block size in bytes
1039 jirafeau_block_get_size ($id)
1041 $p = VAR_BLOCK
. s2p ($id) . $id;
1042 if (!file_exists ($p))
1046 $f = file ($p . '_infos');
1047 $date = trim ($f[0]);
1048 $block_size = trim ($f[1]);
1049 $stored_code = trim ($f[2]);
1051 if (date ('U') - $date > JIRAFEAU_HOUR
1052 && date ('U') - $date < JIRAFEAU_MONTH
)
1054 if (file_put_contents ($p . '_infos', date ('U') . NL
. $block_size . NL
. $stored_code) === FALSE)
1056 jirafeau_block_delete_ ($id);
1061 elseif (date ('U') - $date >= JIRAFEAU_MONTH
)
1063 echo date ('U'). " $date ";
1064 jirafeau_block_delete_ ($id);
1072 * Read some data in a block.
1073 * @param $id identifier of the block
1074 * @param $start where to read data (starting from zero).
1075 * @param $length length to read.
1079 jirafeau_block_read ($id, $start, $length)
1081 if (!ctype_digit ($start) ||
$start < 0
1082 ||
!ctype_digit ($length) ||
$length <= 0)
1088 $p = VAR_BLOCK
. s2p ($id) . $id;
1089 if (!file_exists ($p))
1096 $f = file ($p . '_infos');
1097 $date = trim ($f[0]);
1098 $block_size = trim ($f[1]);
1099 $stored_code = trim ($f[2]);
1101 if (date ('U') - $date > JIRAFEAU_HOUR
1102 && date ('U') - $date < JIRAFEAU_MONTH
)
1104 if (file_put_contents ($p . '_infos', date ('U') . NL
. $block_size . NL
. $stored_code) === FALSE)
1106 jirafeau_block_delete_ ($id);
1112 elseif (date ('U') - $date >= JIRAFEAU_MONTH
)
1114 echo date ('U'). " $date ";
1115 jirafeau_block_delete_ ($id);
1120 if ($start +
$length > $block_size)
1127 header ('Content-Length: ' . $length);
1128 header ('Content-Disposition: attachment');
1130 $r = fopen ($p, 'r');
1131 if (fseek ($r, $start) != 0)
1137 for ($cnt = 0; $cnt < $length && !feof ($r); $cnt +
= 1024)
1139 if ($length - $cnt < 1024)
1140 $c = $length - $cnt;
1141 print fread ($r, $c);
1148 * Write some data in a block.
1149 * @param $id identifier of the block
1150 * @param $start where to writing data (starting from zero).
1151 * @param $data data to write.
1152 * @param $code code to allow writing.
1153 * @return string "Ok" or string "Error".
1156 jirafeau_block_write ($id, $start, $data, $code)
1158 if (!ctype_digit ($start) ||
$start < 0
1159 ||
strlen ($code) == 0)
1162 $p = VAR_BLOCK
. s2p ($id) . $id;
1163 if (!file_exists ($p))
1167 $f = file ($p . '_infos');
1168 $date = trim ($f[0]);
1169 $block_size = trim ($f[1]);
1170 $stored_code = trim ($f[2]);
1172 if (date ('U') - $date > JIRAFEAU_HOUR
1173 && date ('U') - $date < JIRAFEAU_MONTH
)
1175 if (file_put_contents ($p . '_infos', date ('U') . NL
. $block_size . NL
. $stored_code) === FALSE)
1177 jirafeau_block_delete_ ($id);
1182 elseif (date ('U') - $date >= JIRAFEAU_MONTH
)
1184 jirafeau_block_delete_ ($id);
1189 if ($stored_code != $code)
1196 $size = $data['size'];
1199 if ($start +
$size > $block_size)
1203 $r = fopen ($data['tmp_name'], 'r');
1206 $w = fopen ($p, 'r+');
1207 if (fseek ($w, $start) != 0)
1210 /* Write content. */
1212 for ($cnt = 0; $cnt <= $size && !feof ($w); $cnt +
= 1024)
1214 if ($size - $cnt < 1024)
1216 $d = fread ($r, $c);
1221 unlink ($data['tmp_name']);
1227 * @param $id identifier of the block.
1228 * @param $code code to allow writing.
1229 * @return string "Ok" or string "Error".
1232 jirafeau_block_delete ($id, $code)
1234 $p = VAR_BLOCK
. s2p ($id) . $id;
1236 if (!file_exists ($p))
1239 $f = file ($p . '_infos');
1240 $date = trim ($f[0]);
1241 $block_size = trim ($f[1]);
1242 $stored_code = trim ($f[2]);
1244 if ($code != $stored_code)
1247 jirafeau_block_delete_ ($id);
1252 * Clean old unused blocks.
1253 * @return number of cleaned blocks.
1256 jirafeau_admin_clean_block ()
1259 /* Get all blocks. */
1260 $stack = array (VAR_BLOCK
);
1261 while (($d = array_shift ($stack)) && $d != NULL)
1263 $dir = scandir ($d);
1265 foreach ($dir as $node)
1267 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0)
1270 if (is_dir ($d . $node))
1272 /* Push new found directory. */
1273 $stack[] = $d . $node . '/';
1275 elseif (is_file ($d . $node) && preg_match ('/\_infos/i', "$node"))
1277 /* Read block informations. */
1278 $f = file ($d . $node);
1279 $date = trim ($f[0]);
1280 $block_size = trim ($f[1]);
1281 if (date ('U') - $date >= JIRAFEAU_MONTH
)
1283 jirafeau_block_delete_ (substr($node, 0, -6));
1293 * Crypt file and returns decrypt key.
1294 * @param $fp_src file path to the file to crypt.
1295 * @param $fp_dst file path to the file to write crypted file (could be the same).
1296 * @return decrypt key composed of the key and the iv separated by a point ('.')
1299 jirafeau_encrypt_file ($fp_src, $fp_dst)
1301 $fs = filesize ($fp_src);
1302 if ($fs === false ||
$fs == 0 ||
!extension_loaded('mcrypt'))
1305 /* Prepare module. */
1306 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1307 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($m), MCRYPT_DEV_URANDOM
);
1309 $ks = mcrypt_enc_get_key_size($m);
1310 $key = substr(md5(jirafeau_gen_random(12)), 0, $ks);
1312 mcrypt_generic_init($m, $key, $iv);
1314 $r = fopen ($fp_src, 'r');
1315 $w = fopen ($fp_dst, 'c');
1318 $enc = mcrypt_generic($m, fread ($r, 1024));
1319 if (fwrite ($w, $enc) === false)
1325 mcrypt_generic_deinit($m);
1326 mcrypt_module_close($m);
1327 return $key . "." . base64_encode($iv);
1332 * @param $fp_src file path to the file to decrypt.
1333 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1334 * @param $k string composed of the key and the iv separated by a point ('.')
1335 * @return key used to decrypt. a string of length 0 is returned if failed.
1338 jirafeau_decrypt_file ($fp_src, $fp_dst, $k)
1340 $fs = filesize ($fp_src);
1341 if ($fs === false ||
$fs == 0 ||
!extension_loaded('mcrypt'))
1344 /* Extract key and iv. */
1345 $ex = explode (".", $k);
1347 $iv = base64_decode($ex[1]);
1349 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1350 mcrypt_generic_init($m, $key, $iv);
1352 $r = fopen ($fp_src, 'r');
1353 $w = fopen ($fp_dst, 'c');
1356 $dec = mdecrypt_generic($m, fread ($r, 1024));
1357 if (fwrite ($w, $dec) === false)
1363 mcrypt_generic_deinit($m);
1364 mcrypt_module_close($m);
patrick-canterino.de