]>
git.p6c8.net - jirafeau_mojo42.git/blob - lib/functions.php
d70a17c77826715cfcc846e6e96f113c419d38bc
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 * @returns an array containing some information
310 * 'error' => information on possible errors
311 * 'link' => the link name of the uploaded file
312 * 'delete_link' => the link code to delete file
315 jirafeau_upload ($file, $one_time_download, $key, $time, $ip)
317 if (empty ($file['tmp_name']) ||
!is_uploaded_file ($file['tmp_name']))
321 array ('has_error' => true,
322 'why' => jirafeau_upload_errstr ($file['error'])),
324 'delete_link' => ''));
327 /* array representing no error */
328 $noerr = array ('has_error' => false, 'why' => '');
330 /* file informations */
331 $md5 = md5_file ($file['tmp_name']);
332 $name = str_replace (NL
, '', trim ($file['name']));
333 $mime_type = $file['type'];
334 $size = $file['size'];
336 /* does file already exist ? */
339 if (file_exists (VAR_FILES
. $p . $md5))
341 $rc = unlink ($file['tmp_name']);
343 elseif ((file_exists (VAR_FILES
. $p) || @mkdir
(VAR_FILES
. $p, 0755, true))
344 && move_uploaded_file ($file['tmp_name'], VAR_FILES
. $p . $md5))
352 array ('has_error' => true,
353 'why' => t('Internal error during file creation.')),
355 'delete_link' => ''));
358 /* Increment or create count file. */
360 if (file_exists (VAR_FILES
. $p . $md5 . '_count'))
362 $content = file (VAR_FILES
. $p . $md5. '_count');
363 $counter = trim ($content[0]);
366 $handle = fopen (VAR_FILES
. $p . $md5. '_count', 'w');
367 fwrite ($handle, $counter);
370 /* Create delete code. */
371 $delete_link_code = jirafeau_gen_random (8);
373 /* md5 password or empty */
376 $password = md5 ($key);
378 /* create link file */
379 $link_tmp_name = VAR_LINKS
. $md5 . rand (0, 10000) . ' .tmp';
380 $handle = fopen ($link_tmp_name, 'w');
382 $name . NL
. $mime_type . NL
. $size . NL
. $password . NL
. $time .
383 NL
. $md5. NL
. ($one_time_download ?
'O' : 'R') . NL
. date ('U') .
384 NL
. $ip . NL
. $delete_link_code . NL
);
386 $md5_link = base_16_to_64 (md5_file ($link_tmp_name));
387 $l = s2p ("$md5_link");
388 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
389 !rename ($link_tmp_name, VAR_LINKS
. $l . $md5_link))
391 if (file_exists ($link_tmp_name))
392 unlink ($link_tmp_name);
397 $handle = fopen (VAR_FILES
. $p . $md5. '_count', 'w');
398 fwrite ($handle, $counter);
403 jirafeau_clean_rm_file ($md5_link);
407 array ('has_error' => true,
408 'why' => t('Internal error during file creation. ')),
410 'delete_link' => ''));
412 return (array ('error' => $noerr,
414 'delete_link' => $delete_link_code));
418 * tells if a mime-type is viewable in a browser
419 * @param $mime the mime type
420 * @returns a boolean telling if a mime type is viewable
423 jirafeau_is_viewable ($mime)
427 /* Actually, verify if mime-type is an image or a text. */
428 $viewable = array ('image', 'text');
429 $decomposed = explode ('/', $mime);
430 return in_array ($decomposed[0], $viewable);
435 // Error handling functions.
436 //! Global array that contains all registered errors.
437 $error_list = array ();
440 * Adds an error to the list of errors.
441 * @param $title the error's title
442 * @param $description is a human-friendly description of the problem.
445 add_error ($title, $description)
448 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
452 * Informs whether any error has been registered yet.
453 * @return true if there are errors.
459 return !empty ($error_list);
463 * Displays all the errors.
471 echo '<div class="error">';
472 foreach ($error_list as $error)
480 function check_errors ()
482 if (file_exists (JIRAFEAU_ROOT
. 'install.php')
483 && !file_exists (JIRAFEAU_ROOT
. 'lib/config.local.php'))
485 header('Location: install.php');
489 /* check if the destination dirs are writable */
490 $writable = is_writable (VAR_FILES
) && is_writable (VAR_LINKS
);
492 /* Checking for errors. */
493 if (!is_writable (VAR_FILES
))
494 add_error (t('The file directory is not writable!'), VAR_FILES
);
496 if (!is_writable (VAR_LINKS
))
497 add_error (t('The link directory is not writable!'), VAR_LINKS
);
499 if (!is_writable (VAR_ASYNC
))
500 add_error (t('The async directory is not writable!'), VAR_ASYNC
);
502 /* Check if the install.php script is still in the directory. */
503 if (file_exists (JIRAFEAU_ROOT
. 'install.php'))
504 add_error (t('Installer script still present'),
505 t('Please make sure to delete the installer script ' .
506 '"install.php" before continuing.'));
510 * Read link informations
511 * @return array containing informations.
514 jirafeau_get_link ($hash)
517 $link = VAR_LINKS
. s2p ("$hash") . $hash;
519 if (!file_exists ($link))
523 $out['file_name'] = trim ($c[0]);
524 $out['mime_type'] = trim ($c[1]);
525 $out['file_size'] = trim ($c[2]);
526 $out['key'] = trim ($c[3], NL
);
527 $out['time'] = trim ($c[4]);
528 $out['md5'] = trim ($c[5]);
529 $out['onetime'] = trim ($c[6]);
530 $out['upload_date'] = trim ($c[7]);
531 $out['ip'] = trim ($c[8]);
532 $out['link_code'] = trim ($c[9]);
538 * List files in admin interface.
541 jirafeau_admin_list ($name, $file_hash, $link_hash)
543 echo '<fieldset><legend>';
545 echo t('Filename') . ": $name ";
546 if (!empty ($file_hash))
547 echo t('file') . ": $file_hash ";
548 if (!empty ($link_hash))
549 echo t('link') . ": $link_hash ";
550 if (empty ($name) && empty ($file_hash) && empty ($link_hash))
551 echo t('List all files');
555 echo '<td>' . t('Filename') . '</td>';
556 echo '<td>' . t('Type') . '</td>';
557 echo '<td>' . t('Size') . '</td>';
558 echo '<td>' . t('Expire') . '</td>';
559 echo '<td>' . t('Onetime') . '</td>';
560 echo '<td>' . t('Upload date') . '</td>';
561 echo '<td>' . t('Origin') . '</td>';
562 echo '<td>' . t('Action') . '</td>';
565 /* Get all links files. */
566 $stack = array (VAR_LINKS
);
567 while (($d = array_shift ($stack)) && $d != NULL)
570 foreach ($dir as $node)
572 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
573 preg_match ('/\.tmp/i', "$node"))
575 if (is_dir ($d . $node))
577 /* Push new found directory. */
578 $stack[] = $d . $node . '/';
580 elseif (is_file ($d . $node))
582 /* Read link informations. */
583 $l = jirafeau_get_link ($node);
588 if (!empty ($name) && !preg_match ("/$name/i", $l['file_name']))
590 if (!empty ($file_hash) && $file_hash != $l['md5'])
592 if (!empty ($link_hash) && $link_hash != $node)
594 /* Print link informations. */
597 '<form action = "admin.php" method = "post">' .
598 '<input type = "hidden" name = "action" value = "download"/>' .
599 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
600 '<input type = "submit" value = "' . $l['file_name'] . '" />' .
603 echo '<td>' . $l['mime_type'] . '</td>';
604 echo '<td>' . jirafeau_human_size ($l['file_size']) . '</td>';
605 echo '<td>' . ($l['time'] == -1 ?
'' : strftime ('%c', $l['time'])) .
607 echo '<td>' . $l['onetime'] . '</td>';
608 echo '<td>' . strftime ('%c', $l['upload_date']) . '</td>';
609 echo '<td>' . $l['ip'] . '</td>';
611 '<form action = "admin.php" method = "post">' .
612 '<input type = "hidden" name = "action" value = "delete_link"/>' .
613 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
614 '<input type = "submit" value = "' . t('Del link') . '" />' .
616 '<form action = "admin.php" method = "post">' .
617 '<input type = "hidden" name = "action" value = "delete_file"/>' .
618 '<input type = "hidden" name = "md5" value = "' . $l['md5'] . '"/>' .
619 '<input type = "submit" value = "' . t('Del file and links') . '" />' .
626 echo '</table></fieldset>';
630 * Clean expired files.
631 * @return number of cleaned files.
634 jirafeau_admin_clean ()
637 /* Get all links files. */
638 $stack = array (VAR_LINKS
);
639 while (($d = array_shift ($stack)) && $d != NULL)
643 foreach ($dir as $node)
645 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
646 preg_match ('/\.tmp/i', "$node"))
649 if (is_dir ($d . $node))
651 /* Push new found directory. */
652 $stack[] = $d . $node . '/';
654 elseif (is_file ($d . $node))
656 /* Read link informations. */
657 $l = jirafeau_get_link (basename ($node));
660 $p = s2p ($l['md5']);
661 if ($l['time'] > 0 && $l['time'] < time () ||
// expired
662 !file_exists (VAR_FILES
. $p . $l['md5']) ||
// invalid
663 !file_exists (VAR_FILES
. $p . $l['md5'] . '_count')) // invalid
665 jirafeau_delete_link ($node);
676 * Clean old async transferts.
677 * @return number of cleaned files.
680 jirafeau_admin_clean_async ()
683 /* Get all links files. */
684 $stack = array (VAR_ASYNC
);
685 while (($d = array_shift ($stack)) && $d != NULL)
689 foreach ($dir as $node)
691 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
692 preg_match ('/\.tmp/i', "$node"))
695 if (is_dir ($d . $node))
697 /* Push new found directory. */
698 $stack[] = $d . $node . '/';
700 elseif (is_file ($d . $node))
702 /* Read async informations. */
703 $a = jirafeau_get_async_ref (basename ($node));
706 /* Delete transferts older than 1 hour. */
707 if (date ('U') - $a['last_edited'] > 3600)
709 jirafeau_async_delete (basename ($node));
718 * Read async transfert informations
719 * @return array containing informations.
722 jirafeau_get_async_ref ($ref)
725 $refinfos = VAR_ASYNC
. s2p ("$ref") . "$ref";
727 if (!file_exists ($refinfos))
730 $c = file ($refinfos);
731 $out['file_name'] = trim ($c[0]);
732 $out['mime_type'] = trim ($c[1]);
733 $out['key'] = trim ($c[2], NL
);
734 $out['time'] = trim ($c[3]);
735 $out['onetime'] = trim ($c[4]);
736 $out['ip'] = trim ($c[5]);
737 $out['last_edited'] = trim ($c[6]);
738 $out['next_code'] = trim ($c[7]);
743 * Delete async transfert informations
746 jirafeau_async_delete ($ref)
749 if (file_exists (VAR_ASYNC
. $p . $ref))
750 unlink (VAR_ASYNC
. $p . $ref);
751 if (file_exists (VAR_ASYNC
. $p . $ref . '_data'))
752 unlink (VAR_ASYNC
. $p . $ref . '_data');
753 $parse = VAR_ASYNC
. $p;
755 while (file_exists ($parse)
756 && ($scan = scandir ($parse))
757 && count ($scan) == 2 // '.' and '..' folders => empty.
758 && basename ($parse) != basename (VAR_ASYNC
))
761 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
766 * Init a new asynchronous upload.
767 * @param $finename Name of the file to send
768 * @param $one_time One time upload parameter
769 * @param $key eventual password (or blank)
770 * @param $time time limit
771 * @param $ip ip address of the client
772 * @return a string containing a temporary reference followed by a code or the string "Error"
775 jirafeau_async_init ($filename, $type, $one_time, $key, $time, $ip)
779 /* Create temporary folder. */
782 $code = jirafeau_gen_random (4);
785 $ref = jirafeau_gen_random (32);
786 $p = VAR_ASYNC
. s2p ($ref);
787 } while (file_exists ($p));
788 @mkdir
($p, 0755, true);
789 if (!file_exists ($p))
795 /* md5 password or empty */
798 $password = md5 ($key);
800 /* Store informations. */
802 $handle = fopen ($p, 'w');
804 str_replace (NL
, '', trim ($filename)) . NL
. trim ($type) . NL
. $password . NL
. $time . NL
.
805 ($one_time ?
'O' : 'R') . NL
. $ip . NL
. date ('U') . NL
.
809 return $ref . NL
. $code ;
813 * Append a piece of file on the asynchronous upload.
814 * @param $ref asynchronous upload reference
815 * @param $file piece of data
816 * @param $code client code for this operation
817 * @return a string containing a next code to use or the string "Error"
820 jirafeau_async_push ($ref, $data, $code)
822 /* Get async infos. */
823 $a = jirafeau_get_async_ref ($ref);
825 /* Check some errors. */
827 ||
$a['next_code'] != "$code"
828 ||
empty ($data['tmp_name'])
829 ||
!is_uploaded_file ($data['tmp_name']))
834 /* Concatenate data. */
835 $r = fopen ($data['tmp_name'], 'r');
836 $w = fopen (VAR_ASYNC
. $p . $ref . '_data', 'a');
839 if (fwrite ($w, fread ($r, 1024)) === false)
843 jirafeau_async_delete ($ref);
849 unlink ($data['tmp_name']);
851 /* Update async file. */
852 $code = jirafeau_gen_random (4);
853 $handle = fopen (VAR_ASYNC
. $p . $ref, 'w');
855 $a['file_name'] . NL
. $a['mime_type'] . NL
. $a['key'] . NL
.
856 $a['time'] . NL
. $a['onetime'] . NL
. $a['ip'] . NL
.
857 date ('U') . NL
. $code . NL
);
863 * Finalyze an asynchronous upload.
864 * @param $ref asynchronous upload reference
865 * @param $code client code for this operation
866 * @return a string containing the download reference followed by a delete code or the string "Error"
869 jirafeau_async_end ($ref, $code)
871 /* Get async infos. */
872 $a = jirafeau_get_async_ref ($ref);
874 ||
$a['next_code'] != "$code")
877 /* Generate link infos. */
878 $p = VAR_ASYNC
. s2p ($ref) . $ref . "_data";
879 if (!file_exists($p))
881 $md5 = md5_file ($p);
882 $size = filesize($p);
884 $delete_link_code = jirafeau_gen_random (8);
886 /* File already exist ? */
887 if (!file_exists (VAR_FILES
. $np))
888 @mkdir
(VAR_FILES
. $np, 0755, true);
889 if (!file_exists (VAR_FILES
. $np . $md5))
890 rename ($p, VAR_FILES
. $np . $md5);
892 /* Increment or create count file. */
894 if (file_exists (VAR_FILES
. $np . $md5 . '_count'))
896 $content = file (VAR_FILES
. $np . $md5. '_count');
897 $counter = trim ($content[0]);
900 $handle = fopen (VAR_FILES
. $np . $md5. '_count', 'w');
901 fwrite ($handle, $counter);
905 $link_tmp_name = VAR_LINKS
. $md5 . rand (0, 10000) . ' .tmp';
906 $handle = fopen ($link_tmp_name, 'w');
908 $a['file_name'] . NL
. $a['mime_type'] . NL
. $size . NL
.
909 $a['key'] . NL
. $a['time'] . NL
. $md5 . NL
. $a['onetime'] . NL
.
910 date ('U') . NL
. $a['ip'] . NL
. $delete_link_code . NL
);
912 $md5_link = base_16_to_64 (md5_file ($link_tmp_name));
913 $l = s2p ("$md5_link");
914 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
915 !rename ($link_tmp_name, VAR_LINKS
. $l . $md5_link))
918 /* Clean async upload. */
919 jirafeau_async_delete ($ref);
920 return $md5_link . NL
. $delete_link_code;
patrick-canterino.de