]>
git.p6c8.net - jirafeau_project.git/blob - lib/functions.php
3 * Jirafeau, your web file repository
4 * Copyright (C) 2008 Julien "axolotl" BERNARD <axolotl@magieeternelle.org>
5 * Copyright (C) 2015 Jerome Jutteau <j.jutteau@gmail.com>
6 * Copyright (C) 2015 Nicola Spanti (RyDroid) <dev@nicola-spanti.info>
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU Affero General Public License as
10 * published by the Free Software Foundation, either version 3 of the
11 * License, or (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Affero General Public License for more details.
18 * You should have received a copy of the GNU Affero General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 * Transform a string in a path by seperating each letters by a '/'.
24 * @return path finishing with a '/'
30 for ($i = 0; $i < strlen ($s); $i++
)
36 * Convert base 16 to base 64
37 * @returns A string based on 64 characters (0-9, a-z, A-Z, "-" and "_")
42 $m = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_';
43 $hex2bin = array ('0000', # 0
62 # Convert long hex string to bin.
63 $size = strlen ($num);
64 for ($i = 0; $i < $size; $i++
)
65 $b .= $hex2bin{hexdec ($num{$i})};
66 # Convert long bin to base 64.
68 for ($i = $size - 6; $i >= 0; $i -= 6)
69 $o = $m{bindec (substr ($b, $i, 6))} . $o;
70 # Some few bits remaining ?
71 if ($i < 0 && $i > -6)
72 $o = $m{bindec (substr ($b, 0, $i +
6))} . $o;
77 * Generate a random code.
78 * @param $l code length
79 * @return random code.
82 jirafeau_gen_random ($l)
88 for ($i = 0; $i < $l; $i++
)
89 $code .= dechex (rand (0, 15));
96 if ( isset($_SERVER['HTTPS']) ) {
97 if ( 'on' == strtolower($_SERVER['HTTPS']) ||
98 '1' == $_SERVER['HTTPS'] )
100 } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
102 } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
103 if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
110 jirafeau_human_size ($octets)
112 $u = array ('B', 'KB', 'MB', 'GB', 'TB');
113 $o = max ($octets, 0);
114 $p = min (floor (($o ?
log ($o) : 0) / log (1024)), count ($u) - 1);
115 $o /= pow (1024, $p);
116 return round ($o, 1) . $u[$p];
120 jirafeau_clean_rm_link ($link)
123 if (file_exists (VAR_LINKS
. $p . $link))
124 unlink (VAR_LINKS
. $p . $link);
125 $parse = VAR_LINKS
. $p;
127 while (file_exists ($parse)
128 && ($scan = scandir ($parse))
129 && count ($scan) == 2 // '.' and '..' folders => empty.
130 && basename ($parse) != basename (VAR_LINKS
))
133 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
138 jirafeau_clean_rm_file ($md5)
141 $f = VAR_FILES
. $p . $md5;
142 if (file_exists ($f) && is_file ($f))
144 if (file_exists ($f . '_count') && is_file ($f . '_count'))
145 unlink ($f . '_count');
146 $parse = VAR_FILES
. $p;
148 while (file_exists ($parse)
149 && ($scan = scandir ($parse))
150 && count ($scan) == 2 // '.' and '..' folders => empty.
151 && basename ($parse) != basename (VAR_FILES
))
154 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
159 * transforms a php.ini string representing a value in an integer
160 * @param $value the value from php.ini
161 * @returns an integer for this value
164 jirafeau_ini_to_bytes ($value)
166 $modifier = substr ($value, -1);
167 $bytes = substr ($value, 0, -1);
168 switch (strtoupper ($modifier))
185 * gets the maximum upload size according to php.ini
186 * @returns the maximum upload size in bytes
189 jirafeau_get_max_upload_size_bytes ()
191 return min (jirafeau_ini_to_bytes (ini_get ('post_max_size')),
192 jirafeau_ini_to_bytes (ini_get ('upload_max_filesize')));
196 * gets the maximum upload size according to php.ini
197 * @returns the maximum upload size string
200 jirafeau_get_max_upload_size ()
202 return jirafeau_human_size(
203 min (jirafeau_ini_to_bytes (ini_get ('post_max_size')),
204 jirafeau_ini_to_bytes (ini_get ('upload_max_filesize'))));
208 * gets a string explaining the error
209 * @param $code the error code
210 * @returns a string explaining the error
213 jirafeau_upload_errstr ($code)
217 case UPLOAD_ERR_INI_SIZE
:
218 case UPLOAD_ERR_FORM_SIZE
:
219 return t('Your file exceeds the maximum authorized file size. ');
221 case UPLOAD_ERR_PARTIAL
:
222 case UPLOAD_ERR_NO_FILE
:
224 t('Your file was not uploaded correctly. You may succeed in retrying. ');
226 case UPLOAD_ERR_NO_TMP_DIR
:
227 case UPLOAD_ERR_CANT_WRITE
:
228 case UPLOAD_ERR_EXTENSION
:
229 return t('Internal error. You may not succeed in retrying. ');
231 return t('Unknown error. ');
234 /** Remove link and it's file
235 * @param $link the link's name (hash)
239 jirafeau_delete_link ($link)
241 $l = jirafeau_get_link ($link);
245 jirafeau_clean_rm_link ($link);
251 if (file_exists (VAR_FILES
. $p . $md5. '_count'))
253 $content = file (VAR_FILES
. $p . $md5. '_count');
254 $counter = trim ($content[0]);
260 $handle = fopen (VAR_FILES
. $p . $md5. '_count', 'w');
261 fwrite ($handle, $counter);
266 jirafeau_clean_rm_file ($md5);
270 * Delete a file and it's links.
273 jirafeau_delete_file ($md5)
276 /* Get all links files. */
277 $stack = array (VAR_LINKS
);
278 while (($d = array_shift ($stack)) && $d != NULL)
282 foreach ($dir as $node)
284 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
285 preg_match ('/\.tmp/i', "$node"))
288 if (is_dir ($d . $node))
290 /* Push new found directory. */
291 $stack[] = $d . $node . '/';
293 elseif (is_file ($d . $node))
295 /* Read link informations. */
296 $l = jirafeau_get_link (basename ($node));
299 if ($l['md5'] == $md5)
302 jirafeau_delete_link ($node);
307 jirafeau_clean_rm_file ($md5);
312 * handles an uploaded file
313 * @param $file the file struct given by $_FILE[]
314 * @param $one_time_download is the file a one time download ?
315 * @param $key if not empty, protect the file with this key
316 * @param $time the time of validity of the file
317 * @param $ip uploader's ip
318 * @param $crypt boolean asking to crypt or not
319 * @param $link_name_length size of the link name
320 * @returns an array containing some information
321 * 'error' => information on possible errors
322 * 'link' => the link name of the uploaded file
323 * 'delete_link' => the link code to delete file
326 jirafeau_upload ($file, $one_time_download, $key, $time, $ip, $crypt, $link_name_length)
328 if (empty ($file['tmp_name']) ||
!is_uploaded_file ($file['tmp_name']))
332 array ('has_error' => true,
333 'why' => jirafeau_upload_errstr ($file['error'])),
335 'delete_link' => ''));
338 /* array representing no error */
339 $noerr = array ('has_error' => false, 'why' => '');
341 /* Crypt file if option is enabled. */
344 if ($crypt == true && !(extension_loaded('mcrypt') == true))
345 error_log ("PHP extension mcrypt not loaded, won't encrypt in Jirafeau");
346 if ($crypt == true && extension_loaded('mcrypt') == true)
348 $crypt_key = jirafeau_encrypt_file ($file['tmp_name'], $file['tmp_name']);
349 if (strlen($crypt_key) > 0)
353 /* file informations */
354 $md5 = md5_file ($file['tmp_name']);
355 $name = str_replace (NL
, '', trim ($file['name']));
356 $mime_type = $file['type'];
357 $size = $file['size'];
359 /* does file already exist ? */
362 if (file_exists (VAR_FILES
. $p . $md5))
364 $rc = unlink ($file['tmp_name']);
366 elseif ((file_exists (VAR_FILES
. $p) || @mkdir
(VAR_FILES
. $p, 0755, true))
367 && move_uploaded_file ($file['tmp_name'], VAR_FILES
. $p . $md5))
375 array ('has_error' => true,
376 'why' => t('Internal error during file creation.')),
378 'delete_link' => ''));
381 /* Increment or create count file. */
383 if (file_exists (VAR_FILES
. $p . $md5 . '_count'))
385 $content = file (VAR_FILES
. $p . $md5. '_count');
386 $counter = trim ($content[0]);
389 $handle = fopen (VAR_FILES
. $p . $md5. '_count', 'w');
390 fwrite ($handle, $counter);
393 /* Create delete code. */
394 $delete_link_code = jirafeau_gen_random (5);
396 /* md5 password or empty. */
399 $password = md5 ($key);
401 /* create link file */
402 $link_tmp_name = VAR_LINKS
. $md5 . rand (0, 10000) . '.tmp';
403 $handle = fopen ($link_tmp_name, 'w');
405 $name . NL
. $mime_type . NL
. $size . NL
. $password . NL
. $time .
406 NL
. $md5. NL
. ($one_time_download ?
'O' : 'R') . NL
. date ('U') .
407 NL
. $ip . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
409 $md5_link = substr(base_16_to_64 (md5_file ($link_tmp_name)), 0, $link_name_length);
410 $l = s2p ("$md5_link");
411 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
412 !rename ($link_tmp_name, VAR_LINKS
. $l . $md5_link))
414 if (file_exists ($link_tmp_name))
415 unlink ($link_tmp_name);
420 $handle = fopen (VAR_FILES
. $p . $md5. '_count', 'w');
421 fwrite ($handle, $counter);
426 jirafeau_clean_rm_file ($md5_link);
430 array ('has_error' => true,
431 'why' => t('Internal error during file creation. ')),
433 'delete_link' => '');
435 return array ( 'error' => $noerr,
437 'delete_link' => $delete_link_code,
438 'crypt_key' => $crypt_key);
442 * Tells if a mime-type is viewable in a browser
443 * @param $mime the mime type
444 * @returns a boolean telling if a mime type is viewable
447 jirafeau_is_viewable ($mime)
451 /* Actually, verify if mime-type is an image or a text. */
452 $viewable = array ('image', 'text', 'video', 'audio');
453 $decomposed = explode ('/', $mime);
454 return in_array ($decomposed[0], $viewable);
459 // Error handling functions.
460 //! Global array that contains all registered errors.
461 $error_list = array ();
464 * Adds an error to the list of errors.
465 * @param $title the error's title
466 * @param $description is a human-friendly description of the problem.
469 add_error ($title, $description)
472 $error_list[] = '<p>' . $title. '<br />' . $description. '</p>';
476 * Informs whether any error has been registered yet.
477 * @return true if there are errors.
483 return !empty ($error_list);
487 * Displays all the errors.
495 echo '<div class="error">';
496 foreach ($error_list as $error)
504 function check_errors ($cfg)
506 if (file_exists (JIRAFEAU_ROOT
. 'install.php')
507 && !($cfg['installation_done'] === true))
509 header('Location: install.php');
513 /* check if the destination dirs are writable */
514 $writable = is_writable (VAR_FILES
) && is_writable (VAR_LINKS
);
516 /* Checking for errors. */
517 if (!is_writable (VAR_FILES
))
518 add_error (t('The file directory is not writable!'), VAR_FILES
);
520 if (!is_writable (VAR_LINKS
))
521 add_error (t('The link directory is not writable!'), VAR_LINKS
);
523 if (!is_writable (VAR_ASYNC
))
524 add_error (t('The async directory is not writable!'), VAR_ASYNC
);
528 * Read link informations
529 * @return array containing informations.
532 jirafeau_get_link ($hash)
535 $link = VAR_LINKS
. s2p ("$hash") . $hash;
537 if (!file_exists ($link))
541 $out['file_name'] = trim ($c[0]);
542 $out['mime_type'] = trim ($c[1]);
543 $out['file_size'] = trim ($c[2]);
544 $out['key'] = trim ($c[3], NL
);
545 $out['time'] = trim ($c[4]);
546 $out['md5'] = trim ($c[5]);
547 $out['onetime'] = trim ($c[6]);
548 $out['upload_date'] = trim ($c[7]);
549 $out['ip'] = trim ($c[8]);
550 $out['link_code'] = trim ($c[9]);
551 $out['crypted'] = trim ($c[10]) == 'C';
557 * List files in admin interface.
560 jirafeau_admin_list ($name, $file_hash, $link_hash)
562 echo '<fieldset><legend>';
564 echo t('Filename') . ": $name ";
565 if (!empty ($file_hash))
566 echo t('file') . ": $file_hash ";
567 if (!empty ($link_hash))
568 echo t('link') . ": $link_hash ";
569 if (empty ($name) && empty ($file_hash) && empty ($link_hash))
570 echo t('List all files');
574 echo '<td>' . t('Filename') . '</td>';
575 echo '<td>' . t('Type') . '</td>';
576 echo '<td>' . t('Size') . '</td>';
577 echo '<td>' . t('Expire') . '</td>';
578 echo '<td>' . t('Onetime') . '</td>';
579 echo '<td>' . t('Upload date') . '</td>';
580 echo '<td>' . t('Origin') . '</td>';
581 echo '<td>' . t('Action') . '</td>';
584 /* Get all links files. */
585 $stack = array (VAR_LINKS
);
586 while (($d = array_shift ($stack)) && $d != NULL)
589 foreach ($dir as $node)
591 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
592 preg_match ('/\.tmp/i', "$node"))
594 if (is_dir ($d . $node))
596 /* Push new found directory. */
597 $stack[] = $d . $node . '/';
599 elseif (is_file ($d . $node))
601 /* Read link informations. */
602 $l = jirafeau_get_link ($node);
607 if (!empty ($name) && !preg_match ("/$name/i", htmlspecialchars($l['file_name'])))
609 if (!empty ($file_hash) && $file_hash != $l['md5'])
611 if (!empty ($link_hash) && $link_hash != $node)
613 /* Print link informations. */
616 '<form action = "admin.php" method = "post">' .
617 '<input type = "hidden" name = "action" value = "download"/>' .
618 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
619 '<input type = "submit" value = "' . htmlspecialchars($l['file_name']) . '" />' .
622 echo '<td>' . $l['mime_type'] . '</td>';
623 echo '<td>' . jirafeau_human_size ($l['file_size']) . '</td>';
624 echo '<td>' . ($l['time'] == -1 ?
'' : strftime ('%c', $l['time'])) .
626 echo '<td>' . $l['onetime'] . '</td>';
627 echo '<td>' . strftime ('%c', $l['upload_date']) . '</td>';
628 echo '<td>' . $l['ip'] . '</td>';
630 '<form action = "admin.php" method = "post">' .
631 '<input type = "hidden" name = "action" value = "delete_link"/>' .
632 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
633 '<input type = "submit" value = "' . t('Del link') . '" />' .
635 '<form action = "admin.php" method = "post">' .
636 '<input type = "hidden" name = "action" value = "delete_file"/>' .
637 '<input type = "hidden" name = "md5" value = "' . $l['md5'] . '"/>' .
638 '<input type = "submit" value = "' . t('Del file and links') . '" />' .
645 echo '</table></fieldset>';
649 * Clean expired files.
650 * @return number of cleaned files.
653 jirafeau_admin_clean ()
656 /* Get all links files. */
657 $stack = array (VAR_LINKS
);
658 while (($d = array_shift ($stack)) && $d != NULL)
662 foreach ($dir as $node)
664 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
665 preg_match ('/\.tmp/i', "$node"))
668 if (is_dir ($d . $node))
670 /* Push new found directory. */
671 $stack[] = $d . $node . '/';
673 elseif (is_file ($d . $node))
675 /* Read link informations. */
676 $l = jirafeau_get_link (basename ($node));
679 $p = s2p ($l['md5']);
680 if ($l['time'] > 0 && $l['time'] < time () ||
// expired
681 !file_exists (VAR_FILES
. $p . $l['md5']) ||
// invalid
682 !file_exists (VAR_FILES
. $p . $l['md5'] . '_count')) // invalid
684 jirafeau_delete_link ($node);
695 * Clean old async transferts.
696 * @return number of cleaned files.
699 jirafeau_admin_clean_async ()
702 /* Get all links files. */
703 $stack = array (VAR_ASYNC
);
704 while (($d = array_shift ($stack)) && $d != NULL)
708 foreach ($dir as $node)
710 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
711 preg_match ('/\.tmp/i', "$node"))
714 if (is_dir ($d . $node))
716 /* Push new found directory. */
717 $stack[] = $d . $node . '/';
719 elseif (is_file ($d . $node))
721 /* Read async informations. */
722 $a = jirafeau_get_async_ref (basename ($node));
725 /* Delete transferts older than 1 hour. */
726 if (date ('U') - $a['last_edited'] > 3600)
728 jirafeau_async_delete (basename ($node));
737 * Read async transfert informations
738 * @return array containing informations.
741 jirafeau_get_async_ref ($ref)
744 $refinfos = VAR_ASYNC
. s2p ("$ref") . "$ref";
746 if (!file_exists ($refinfos))
749 $c = file ($refinfos);
750 $out['file_name'] = trim ($c[0]);
751 $out['mime_type'] = trim ($c[1]);
752 $out['key'] = trim ($c[2], NL
);
753 $out['time'] = trim ($c[3]);
754 $out['onetime'] = trim ($c[4]);
755 $out['ip'] = trim ($c[5]);
756 $out['last_edited'] = trim ($c[6]);
757 $out['next_code'] = trim ($c[7]);
762 * Delete async transfert informations
765 jirafeau_async_delete ($ref)
768 if (file_exists (VAR_ASYNC
. $p . $ref))
769 unlink (VAR_ASYNC
. $p . $ref);
770 if (file_exists (VAR_ASYNC
. $p . $ref . '_data'))
771 unlink (VAR_ASYNC
. $p . $ref . '_data');
772 $parse = VAR_ASYNC
. $p;
774 while (file_exists ($parse)
775 && ($scan = scandir ($parse))
776 && count ($scan) == 2 // '.' and '..' folders => empty.
777 && basename ($parse) != basename (VAR_ASYNC
))
780 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
785 * Init a new asynchronous upload.
786 * @param $finename Name of the file to send
787 * @param $one_time One time upload parameter
788 * @param $key eventual password (or blank)
789 * @param $time time limit
790 * @param $ip ip address of the client
791 * @return a string containing a temporary reference followed by a code or the string 'Error'
794 jirafeau_async_init ($filename, $type, $one_time, $key, $time, $ip)
798 /* Create temporary folder. */
801 $code = jirafeau_gen_random (4);
804 $ref = jirafeau_gen_random (32);
805 $p = VAR_ASYNC
. s2p ($ref);
806 } while (file_exists ($p));
807 @mkdir
($p, 0755, true);
808 if (!file_exists ($p))
814 /* md5 password or empty */
817 $password = md5 ($key);
819 /* Store informations. */
821 $handle = fopen ($p, 'w');
823 str_replace (NL
, '', trim ($filename)) . NL
.
824 str_replace (NL
, '', trim ($type)) . NL
. $password . NL
.
825 $time . NL
. ($one_time ?
'O' : 'R') . NL
. $ip . NL
.
826 date ('U') . NL
. $code . NL
);
829 return $ref . NL
. $code ;
833 * Append a piece of file on the asynchronous upload.
834 * @param $ref asynchronous upload reference
835 * @param $file piece of data
836 * @param $code client code for this operation
837 * @param $max_file_size maximum allowed file size
838 * @return a string containing a next code to use or the string "Error"
841 jirafeau_async_push ($ref, $data, $code, $max_file_size)
843 /* Get async infos. */
844 $a = jirafeau_get_async_ref ($ref);
846 /* Check some errors. */
848 ||
$a['next_code'] != "$code"
849 ||
empty ($data['tmp_name'])
850 ||
!is_uploaded_file ($data['tmp_name']))
856 $r_path = $data['tmp_name'];
857 $w_path = VAR_ASYNC
. $p . $ref . '_data';
859 /* Check that file size is not above upload limit. */
860 if ($max_file_size > 0 &&
861 filesize ($r_path) +
filesize ($w_path) > $max_file_size * 1024 * 1024)
863 jirafeau_async_delete ($ref);
867 /* Concatenate data. */
868 $r = fopen ($r_path, 'r');
869 $w = fopen ($w_path, 'a');
872 if (fwrite ($w, fread ($r, 1024)) === false)
876 jirafeau_async_delete ($ref);
884 /* Update async file. */
885 $code = jirafeau_gen_random (4);
886 $handle = fopen (VAR_ASYNC
. $p . $ref, 'w');
888 $a['file_name'] . NL
. $a['mime_type'] . NL
. $a['key'] . NL
.
889 $a['time'] . NL
. $a['onetime'] . NL
. $a['ip'] . NL
.
890 date ('U') . NL
. $code . NL
);
896 * Finalyze an asynchronous upload.
897 * @param $ref asynchronous upload reference
898 * @param $code client code for this operation
899 * @param $crypt boolean asking to crypt or not
900 * @param $link_name_length link name length
901 * @return a string containing the download reference followed by a delete code or the string 'Error'
904 jirafeau_async_end ($ref, $code, $crypt, $link_name_length)
906 /* Get async infos. */
907 $a = jirafeau_get_async_ref ($ref);
909 ||
$a['next_code'] != "$code")
912 /* Generate link infos. */
913 $p = VAR_ASYNC
. s2p ($ref) . $ref . "_data";
914 if (!file_exists($p))
919 if ($crypt == true && extension_loaded('mcrypt') == true)
921 $crypt_key = jirafeau_encrypt_file ($p, $p);
922 if (strlen($crypt_key) > 0)
926 $md5 = md5_file ($p);
927 $size = filesize($p);
929 $delete_link_code = jirafeau_gen_random (5);
931 /* File already exist ? */
932 if (!file_exists (VAR_FILES
. $np))
933 @mkdir
(VAR_FILES
. $np, 0755, true);
934 if (!file_exists (VAR_FILES
. $np . $md5))
935 rename ($p, VAR_FILES
. $np . $md5);
937 /* Increment or create count file. */
939 if (file_exists (VAR_FILES
. $np . $md5 . '_count'))
941 $content = file (VAR_FILES
. $np . $md5. '_count');
942 $counter = trim ($content[0]);
945 $handle = fopen (VAR_FILES
. $np . $md5. '_count', 'w');
946 fwrite ($handle, $counter);
950 $link_tmp_name = VAR_LINKS
. $md5 . rand (0, 10000) . '.tmp';
951 $handle = fopen ($link_tmp_name, 'w');
953 $a['file_name'] . NL
. $a['mime_type'] . NL
. $size . NL
.
954 $a['key'] . NL
. $a['time'] . NL
. $md5 . NL
. $a['onetime'] . NL
.
955 date ('U') . NL
. $a['ip'] . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
957 $md5_link = substr(base_16_to_64 (md5_file ($link_tmp_name)), 0, $link_name_length);
958 $l = s2p ("$md5_link");
959 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
960 !rename ($link_tmp_name, VAR_LINKS
. $l . $md5_link))
963 /* Clean async upload. */
964 jirafeau_async_delete ($ref);
965 return $md5_link . NL
. $delete_link_code . NL
. urlencode($crypt_key);
969 jirafeau_crypt_create_iv($base, $size)
972 while (strlen ($iv) < $size)
974 $iv = substr($iv, 0, $size);
979 * Crypt file and returns decrypt key.
980 * @param $fp_src file path to the file to crypt.
981 * @param $fp_dst file path to the file to write crypted file (could be the same).
982 * @return decrypt key composed of the key and the iv separated by a point ('.')
985 jirafeau_encrypt_file ($fp_src, $fp_dst)
987 $fs = filesize ($fp_src);
988 if ($fs === false ||
$fs == 0 ||
!(extension_loaded('mcrypt') == true))
991 /* Prepare module. */
992 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
994 $crypt_key = jirafeau_gen_random (10);
995 $md5_key = md5($crypt_key);
996 $iv = jirafeau_crypt_create_iv ($md5_key, mcrypt_enc_get_iv_size($m));
998 mcrypt_generic_init($m, $md5_key, $iv);
1000 $r = fopen ($fp_src, 'r');
1001 $w = fopen ($fp_dst, 'c');
1004 $enc = mcrypt_generic($m, fread ($r, 1024));
1005 if (fwrite ($w, $enc) === false)
1011 mcrypt_generic_deinit($m);
1012 mcrypt_module_close($m);
1018 * @param $fp_src file path to the file to decrypt.
1019 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1020 * @param $k string composed of the key and the iv separated by a point ('.')
1021 * @return key used to decrypt. a string of length 0 is returned if failed.
1024 jirafeau_decrypt_file ($fp_src, $fp_dst, $k)
1026 $fs = filesize ($fp_src);
1027 if ($fs === false ||
$fs == 0 ||
extension_loaded('mcrypt') == false)
1031 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1032 /* Extract key and iv. */
1034 $md5_key = md5($crypt_key);
1035 $iv = jirafeau_crypt_create_iv ($md5_key, mcrypt_enc_get_iv_size($m));
1037 $r = fopen ($fp_src, 'r');
1038 $w = fopen ($fp_dst, 'c');
1041 $dec = mdecrypt_generic($m, fread ($r, 1024));
1042 if (fwrite ($w, $dec) === false)
1048 mcrypt_generic_deinit($m);
1049 mcrypt_module_close($m);
1054 * Check if Jirafeau is password protected for visitors.
1055 * @return true if Jirafeau is password protected, false otherwise.
1058 jirafeau_has_upload_password ($cfg)
1060 return count ($cfg['upload_password']) > 0;
1064 * Challenge password for a visitor.
1065 * @param $password password to be challenged
1066 * @return true if password is valid, false otherwise.
1069 jirafeau_challenge_upload_password ($cfg, $password)
1071 if (!jirafeau_has_upload_password($cfg))
1073 forEach ($cfg['upload_password'] as $p)
1074 if ($password == $p)
1080 * Test if visitor's IP is authorized to upload.
1081 * @param $ip IP to be challenged
1082 * @return true if IP is authorized, false otherwise.
1085 jirafeau_challenge_upload_ip ($cfg, $ip)
1087 if (count ($cfg['upload_ip']) == 0)
1089 forEach ($cfg['upload_ip'] as $i)
1093 // CIDR test for IPv4 only.
1094 if (strpos ($i, '/') !== false)
1096 list ($subnet, $mask) = explode('/', $i);
1097 if ((ip2long ($ip) & ~
((1 << (32 - $mask)) - 1) ) == ip2long ($subnet))
1104 /** Tell if we have some HTTP headers generated by a proxy */
1106 has_http_forwarded()
1109 !empty ($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1110 !empty ($_SERVER['http_X_forwarded_for']);
1114 * Generate IP list from HTTP headers generated by a proxy
1115 * @return array of IP strings
1118 get_ip_list_http_forwarded()
1121 if (!empty ($_SERVER['HTTP_X_FORWARDED_FOR']))
1123 $l = explode (',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1127 array_push ($ip_list, preg_replace ('/\s+/', '', $ip));
1129 if (!empty ($_SERVER['http_X_forwarded_for']))
1131 $l = explode (',', $_SERVER['http_X_forwarded_for']);
1134 // Separate IP from port
1135 $ipa = explode (':', $ip);
1139 array_push ($ip_list, preg_replace ('/\s+/', '', $ip));
1146 * Get the ip address of the client from REMOTE_ADDR
1147 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1148 * @returns the client ip address
1151 get_ip_address($cfg)
1153 $remote = $_SERVER['REMOTE_ADDR'];
1154 if (count ($cfg['proxy_ip']) == 0 ||
!has_http_forwarded ())
1157 $ip_list = get_ip_list_http_forwarded ();
1158 if (count ($ip_list) == 0)
1161 foreach ($cfg['proxy_ip'] as $proxy_ip)
1163 if ($remote != $proxy_ip)
1165 // Take the last IP (the one which has been set by the defined proxy).
1166 return end ($ip_list);
1172 * Convert hexadecimal string to base64
1174 function hex_to_base64($hex)
1177 foreach (str_split ($hex, 2) as $pair)
1178 $b .= chr (hexdec ($pair));
1179 return base64_encode ($b);
1183 * Read alias informations
1184 * @return array containing informations.
1187 jirafeau_get_alias ($hash)
1190 $link = VAR_ALIAS
. s2p ("$hash") . $hash;
1192 if (!file_exists ($link))
1196 $out['md5_password'] = trim ($c[0]);
1197 $out['ip'] = trim ($c[1]);
1198 $out['update_date'] = trim ($c[2]);
1199 $out['destination'] = trim ($c[3], NL
);
1204 /** Create an alias to a jirafeau's link.
1205 * @param $alias alias name
1206 * @param $destination reference of the destination
1207 * @param $password password to protect alias
1208 * @param $ip client's IP
1209 * @return a string containing the edit code of the alias or the string "Error"
1212 jirafeau_alias_create ($alias, $destination, $password, $ip)
1214 /* Check that alias and password are long enough. */
1215 if (strlen ($alias) < 8 ||
1216 strlen ($alias) > 32 ||
1217 strlen ($password) < 8 ||
1218 strlen ($password) > 32)
1221 /* Check that destination exists. */
1222 $l = jirafeau_get_link ($destination);
1226 /* Check that alias does not already exists. */
1227 $alias = md5 ($alias);
1228 $p = VAR_ALIAS
. s2p ($alias);
1229 if (file_exists ($p))
1232 /* Create alias folder. */
1233 @mkdir
($p, 0755, true);
1234 if (!file_exists ($p))
1237 /* Generate password. */
1238 $md5_password = md5 ($password);
1240 /* Store informations. */
1242 $handle = fopen ($p, 'w');
1244 $md5_password . NL
.
1253 /** Update an alias.
1254 * @param $alias alias to update
1255 * @param $destination reference of the new destination
1256 * @param $password password to protect alias
1257 * @param $new_password optional new password to protect alias
1258 * @param $ip client's IP
1259 * @return "Ok" or "Error" string
1262 jirafeau_alias_update ($alias, $destination, $password,
1265 $alias = md5 ($alias);
1266 /* Check that alias exits. */
1267 $a = jirafeau_get_alias ($alias);
1271 /* Check that destination exists. */
1272 $l = jirafeau_get_link ($a["destination"]);
1276 /* Check password. */
1277 if ($a["md5_password"] != md5 ($password))
1280 $p = $a['md5_password'];
1281 if (strlen ($new_password) >= 8 &&
1282 strlen ($new_password) <= 32)
1283 $p = md5 ($new_password);
1284 else if (strlen ($new_password) > 0)
1287 /* Rewrite informations. */
1288 $p = VAR_ALIAS
. s2p ($alias) . $alias;
1289 $handle = fopen ($p, 'w');
1300 * @param $alias alias to get
1301 * @return alias destination or "Error" string
1304 jirafeau_alias_get ($alias)
1306 $alias = md5 ($alias);
1307 /* Check that alias exits. */
1308 $a = jirafeau_get_alias ($alias);
1312 return $a['destination'];
1316 jirafeau_clean_rm_alias ($alias)
1318 $p = s2p ("$alias");
1319 if (file_exists (VAR_ALIAS
. $p . $alias))
1320 unlink (VAR_ALIAS
. $p . $alias);
1321 $parse = VAR_ALIAS
. $p;
1323 while (file_exists ($parse)
1324 && ($scan = scandir ($parse))
1325 && count ($scan) == 2 // '.' and '..' folders => empty.
1326 && basename ($parse) != basename (VAR_ALIAS
))
1329 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
1333 /** Delete an alias.
1334 * @param $alias alias to delete
1335 * @param $password password to protect alias
1336 * @return "Ok" or "Error" string
1339 jirafeau_alias_delete ($alias, $password)
1341 $alias = md5 ($alias);
1342 /* Check that alias exits. */
1343 $a = jirafeau_get_alias ($alias);
1347 /* Check password. */
1348 if ($a["md5_password"] != md5 ($password))
1351 jirafeau_clean_rm_alias ($alias);
patrick-canterino.de