]>
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
. time () .
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 '<strong><a id="upload_link" href="/f.php?h='. htmlspecialchars($node) .'" title="' .
617 t('Download page') . '">' . htmlspecialchars($l['file_name']) . '</a></strong>';
619 echo '<td>' . $l['mime_type'] . '</td>';
620 echo '<td>' . jirafeau_human_size ($l['file_size']) . '</td>';
621 echo '<td>' . ($l['time'] == -1 ?
'' : strftime ('%c', $l['time'])) .
624 if ($l['onetime'] == 'O')
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 = "download"/>' .
634 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
635 '<input type = "submit" value = "' . t('Download') . '" />' .
637 '<form action = "admin.php" method = "post">' .
638 '<input type = "hidden" name = "action" value = "delete_link"/>' .
639 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
640 '<input type = "submit" value = "' . t('Del link') . '" />' .
642 '<form action = "admin.php" method = "post">' .
643 '<input type = "hidden" name = "action" value = "delete_file"/>' .
644 '<input type = "hidden" name = "md5" value = "' . $l['md5'] . '"/>' .
645 '<input type = "submit" value = "' . t('Del file and links') . '" />' .
652 echo '</table></fieldset>';
656 * Clean expired files.
657 * @return number of cleaned files.
660 jirafeau_admin_clean ()
663 /* Get all links files. */
664 $stack = array (VAR_LINKS
);
665 while (($d = array_shift ($stack)) && $d != NULL)
669 foreach ($dir as $node)
671 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
672 preg_match ('/\.tmp/i', "$node"))
675 if (is_dir ($d . $node))
677 /* Push new found directory. */
678 $stack[] = $d . $node . '/';
680 elseif (is_file ($d . $node))
682 /* Read link informations. */
683 $l = jirafeau_get_link (basename ($node));
686 $p = s2p ($l['md5']);
687 if ($l['time'] > 0 && $l['time'] < time () ||
// expired
688 !file_exists (VAR_FILES
. $p . $l['md5']) ||
// invalid
689 !file_exists (VAR_FILES
. $p . $l['md5'] . '_count')) // invalid
691 jirafeau_delete_link ($node);
702 * Clean old async transferts.
703 * @return number of cleaned files.
706 jirafeau_admin_clean_async ()
709 /* Get all links files. */
710 $stack = array (VAR_ASYNC
);
711 while (($d = array_shift ($stack)) && $d != NULL)
715 foreach ($dir as $node)
717 if (strcmp ($node, '.') == 0 ||
strcmp ($node, '..') == 0 ||
718 preg_match ('/\.tmp/i', "$node"))
721 if (is_dir ($d . $node))
723 /* Push new found directory. */
724 $stack[] = $d . $node . '/';
726 elseif (is_file ($d . $node))
728 /* Read async informations. */
729 $a = jirafeau_get_async_ref (basename ($node));
732 /* Delete transferts older than 1 hour. */
733 if (time () - $a['last_edited'] > 3600)
735 jirafeau_async_delete (basename ($node));
744 * Read async transfert informations
745 * @return array containing informations.
748 jirafeau_get_async_ref ($ref)
751 $refinfos = VAR_ASYNC
. s2p ("$ref") . "$ref";
753 if (!file_exists ($refinfos))
756 $c = file ($refinfos);
757 $out['file_name'] = trim ($c[0]);
758 $out['mime_type'] = trim ($c[1]);
759 $out['key'] = trim ($c[2], NL
);
760 $out['time'] = trim ($c[3]);
761 $out['onetime'] = trim ($c[4]);
762 $out['ip'] = trim ($c[5]);
763 $out['last_edited'] = trim ($c[6]);
764 $out['next_code'] = trim ($c[7]);
769 * Delete async transfert informations
772 jirafeau_async_delete ($ref)
775 if (file_exists (VAR_ASYNC
. $p . $ref))
776 unlink (VAR_ASYNC
. $p . $ref);
777 if (file_exists (VAR_ASYNC
. $p . $ref . '_data'))
778 unlink (VAR_ASYNC
. $p . $ref . '_data');
779 $parse = VAR_ASYNC
. $p;
781 while (file_exists ($parse)
782 && ($scan = scandir ($parse))
783 && count ($scan) == 2 // '.' and '..' folders => empty.
784 && basename ($parse) != basename (VAR_ASYNC
))
787 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
792 * Init a new asynchronous upload.
793 * @param $finename Name of the file to send
794 * @param $one_time One time upload parameter
795 * @param $key eventual password (or blank)
796 * @param $time time limit
797 * @param $ip ip address of the client
798 * @return a string containing a temporary reference followed by a code or the string 'Error'
801 jirafeau_async_init ($filename, $type, $one_time, $key, $time, $ip)
805 /* Create temporary folder. */
808 $code = jirafeau_gen_random (4);
811 $ref = jirafeau_gen_random (32);
812 $p = VAR_ASYNC
. s2p ($ref);
813 } while (file_exists ($p));
814 @mkdir
($p, 0755, true);
815 if (!file_exists ($p))
821 /* md5 password or empty */
824 $password = md5 ($key);
826 /* Store informations. */
828 $handle = fopen ($p, 'w');
830 str_replace (NL
, '', trim ($filename)) . NL
.
831 str_replace (NL
, '', trim ($type)) . NL
. $password . NL
.
832 $time . NL
. ($one_time ?
'O' : 'R') . NL
. $ip . NL
.
833 time () . NL
. $code . NL
);
836 return $ref . NL
. $code ;
840 * Append a piece of file on the asynchronous upload.
841 * @param $ref asynchronous upload reference
842 * @param $file piece of data
843 * @param $code client code for this operation
844 * @param $max_file_size maximum allowed file size
845 * @return a string containing a next code to use or the string "Error"
848 jirafeau_async_push ($ref, $data, $code, $max_file_size)
850 /* Get async infos. */
851 $a = jirafeau_get_async_ref ($ref);
853 /* Check some errors. */
855 ||
$a['next_code'] != "$code"
856 ||
empty ($data['tmp_name'])
857 ||
!is_uploaded_file ($data['tmp_name']))
863 $r_path = $data['tmp_name'];
864 $w_path = VAR_ASYNC
. $p . $ref . '_data';
866 /* Check that file size is not above upload limit. */
867 if ($max_file_size > 0 &&
868 filesize ($r_path) +
filesize ($w_path) > $max_file_size * 1024 * 1024)
870 jirafeau_async_delete ($ref);
874 /* Concatenate data. */
875 $r = fopen ($r_path, 'r');
876 $w = fopen ($w_path, 'a');
879 if (fwrite ($w, fread ($r, 1024)) === false)
883 jirafeau_async_delete ($ref);
891 /* Update async file. */
892 $code = jirafeau_gen_random (4);
893 $handle = fopen (VAR_ASYNC
. $p . $ref, 'w');
895 $a['file_name'] . NL
. $a['mime_type'] . NL
. $a['key'] . NL
.
896 $a['time'] . NL
. $a['onetime'] . NL
. $a['ip'] . NL
.
897 time () . NL
. $code . NL
);
903 * Finalyze an asynchronous upload.
904 * @param $ref asynchronous upload reference
905 * @param $code client code for this operation
906 * @param $crypt boolean asking to crypt or not
907 * @param $link_name_length link name length
908 * @return a string containing the download reference followed by a delete code or the string 'Error'
911 jirafeau_async_end ($ref, $code, $crypt, $link_name_length)
913 /* Get async infos. */
914 $a = jirafeau_get_async_ref ($ref);
916 ||
$a['next_code'] != "$code")
919 /* Generate link infos. */
920 $p = VAR_ASYNC
. s2p ($ref) . $ref . "_data";
921 if (!file_exists($p))
926 if ($crypt == true && extension_loaded('mcrypt') == true)
928 $crypt_key = jirafeau_encrypt_file ($p, $p);
929 if (strlen($crypt_key) > 0)
933 $md5 = md5_file ($p);
934 $size = filesize($p);
936 $delete_link_code = jirafeau_gen_random (5);
938 /* File already exist ? */
939 if (!file_exists (VAR_FILES
. $np))
940 @mkdir
(VAR_FILES
. $np, 0755, true);
941 if (!file_exists (VAR_FILES
. $np . $md5))
942 rename ($p, VAR_FILES
. $np . $md5);
944 /* Increment or create count file. */
946 if (file_exists (VAR_FILES
. $np . $md5 . '_count'))
948 $content = file (VAR_FILES
. $np . $md5. '_count');
949 $counter = trim ($content[0]);
952 $handle = fopen (VAR_FILES
. $np . $md5. '_count', 'w');
953 fwrite ($handle, $counter);
957 $link_tmp_name = VAR_LINKS
. $md5 . rand (0, 10000) . '.tmp';
958 $handle = fopen ($link_tmp_name, 'w');
960 $a['file_name'] . NL
. $a['mime_type'] . NL
. $size . NL
.
961 $a['key'] . NL
. $a['time'] . NL
. $md5 . NL
. $a['onetime'] . NL
.
962 time () . NL
. $a['ip'] . NL
. $delete_link_code . NL
. ($crypted ?
'C' : 'O'));
964 $md5_link = substr(base_16_to_64 (md5_file ($link_tmp_name)), 0, $link_name_length);
965 $l = s2p ("$md5_link");
966 if (!@mkdir
(VAR_LINKS
. $l, 0755, true) ||
967 !rename ($link_tmp_name, VAR_LINKS
. $l . $md5_link))
970 /* Clean async upload. */
971 jirafeau_async_delete ($ref);
972 return $md5_link . NL
. $delete_link_code . NL
. urlencode($crypt_key);
976 jirafeau_crypt_create_iv($base, $size)
979 while (strlen ($iv) < $size)
981 $iv = substr($iv, 0, $size);
986 * Crypt file and returns decrypt key.
987 * @param $fp_src file path to the file to crypt.
988 * @param $fp_dst file path to the file to write crypted file (could be the same).
989 * @return decrypt key composed of the key and the iv separated by a point ('.')
992 jirafeau_encrypt_file ($fp_src, $fp_dst)
994 $fs = filesize ($fp_src);
995 if ($fs === false ||
$fs == 0 ||
!(extension_loaded('mcrypt') == true))
998 /* Prepare module. */
999 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1001 $crypt_key = jirafeau_gen_random (10);
1002 $md5_key = md5($crypt_key);
1003 $iv = jirafeau_crypt_create_iv ($md5_key, mcrypt_enc_get_iv_size($m));
1005 mcrypt_generic_init($m, $md5_key, $iv);
1007 $r = fopen ($fp_src, 'r');
1008 $w = fopen ($fp_dst, 'c');
1011 $enc = mcrypt_generic($m, fread ($r, 1024));
1012 if (fwrite ($w, $enc) === false)
1018 mcrypt_generic_deinit($m);
1019 mcrypt_module_close($m);
1025 * @param $fp_src file path to the file to decrypt.
1026 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1027 * @param $k string composed of the key and the iv separated by a point ('.')
1028 * @return key used to decrypt. a string of length 0 is returned if failed.
1031 jirafeau_decrypt_file ($fp_src, $fp_dst, $k)
1033 $fs = filesize ($fp_src);
1034 if ($fs === false ||
$fs == 0 ||
extension_loaded('mcrypt') == false)
1038 $m = mcrypt_module_open('rijndael-256', '', 'ofb', '');
1039 /* Extract key and iv. */
1041 $md5_key = md5($crypt_key);
1042 $iv = jirafeau_crypt_create_iv ($md5_key, mcrypt_enc_get_iv_size($m));
1044 $r = fopen ($fp_src, 'r');
1045 $w = fopen ($fp_dst, 'c');
1048 $dec = mdecrypt_generic($m, fread ($r, 1024));
1049 if (fwrite ($w, $dec) === false)
1055 mcrypt_generic_deinit($m);
1056 mcrypt_module_close($m);
1061 * Check if Jirafeau is password protected for visitors.
1062 * @return true if Jirafeau is password protected, false otherwise.
1065 jirafeau_has_upload_password ($cfg)
1067 return count ($cfg['upload_password']) > 0;
1071 * Challenge password for a visitor.
1072 * @param $password password to be challenged
1073 * @return true if password is valid, false otherwise.
1076 jirafeau_challenge_upload_password ($cfg, $password)
1078 if (!jirafeau_has_upload_password($cfg))
1080 forEach ($cfg['upload_password'] as $p)
1081 if ($password == $p)
1087 * Test if visitor's IP is authorized to upload.
1088 * @param $ip IP to be challenged
1089 * @return true if IP is authorized, false otherwise.
1092 jirafeau_challenge_upload_ip ($cfg, $ip)
1094 if (count ($cfg['upload_ip']) == 0)
1096 forEach ($cfg['upload_ip'] as $i)
1100 // CIDR test for IPv4 only.
1101 if (strpos ($i, '/') !== false)
1103 list ($subnet, $mask) = explode('/', $i);
1104 if ((ip2long ($ip) & ~
((1 << (32 - $mask)) - 1) ) == ip2long ($subnet))
1111 /** Tell if we have some HTTP headers generated by a proxy */
1113 has_http_forwarded()
1116 !empty ($_SERVER['HTTP_X_FORWARDED_FOR']) ||
1117 !empty ($_SERVER['http_X_forwarded_for']);
1121 * Generate IP list from HTTP headers generated by a proxy
1122 * @return array of IP strings
1125 get_ip_list_http_forwarded()
1128 if (!empty ($_SERVER['HTTP_X_FORWARDED_FOR']))
1130 $l = explode (',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1134 array_push ($ip_list, preg_replace ('/\s+/', '', $ip));
1136 if (!empty ($_SERVER['http_X_forwarded_for']))
1138 $l = explode (',', $_SERVER['http_X_forwarded_for']);
1141 // Separate IP from port
1142 $ipa = explode (':', $ip);
1146 array_push ($ip_list, preg_replace ('/\s+/', '', $ip));
1153 * Get the ip address of the client from REMOTE_ADDR
1154 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1155 * @returns the client ip address
1158 get_ip_address($cfg)
1160 $remote = $_SERVER['REMOTE_ADDR'];
1161 if (count ($cfg['proxy_ip']) == 0 ||
!has_http_forwarded ())
1164 $ip_list = get_ip_list_http_forwarded ();
1165 if (count ($ip_list) == 0)
1168 foreach ($cfg['proxy_ip'] as $proxy_ip)
1170 if ($remote != $proxy_ip)
1172 // Take the last IP (the one which has been set by the defined proxy).
1173 return end ($ip_list);
1179 * Convert hexadecimal string to base64
1181 function hex_to_base64($hex)
1184 foreach (str_split ($hex, 2) as $pair)
1185 $b .= chr (hexdec ($pair));
1186 return base64_encode ($b);
1190 * Read alias informations
1191 * @return array containing informations.
1194 jirafeau_get_alias ($hash)
1197 $link = VAR_ALIAS
. s2p ("$hash") . $hash;
1199 if (!file_exists ($link))
1203 $out['md5_password'] = trim ($c[0]);
1204 $out['ip'] = trim ($c[1]);
1205 $out['update_date'] = trim ($c[2]);
1206 $out['destination'] = trim ($c[3], NL
);
1211 /** Create an alias to a jirafeau's link.
1212 * @param $alias alias name
1213 * @param $destination reference of the destination
1214 * @param $password password to protect alias
1215 * @param $ip client's IP
1216 * @return a string containing the edit code of the alias or the string "Error"
1219 jirafeau_alias_create ($alias, $destination, $password, $ip)
1221 /* Check that alias and password are long enough. */
1222 if (strlen ($alias) < 8 ||
1223 strlen ($alias) > 32 ||
1224 strlen ($password) < 8 ||
1225 strlen ($password) > 32)
1228 /* Check that destination exists. */
1229 $l = jirafeau_get_link ($destination);
1233 /* Check that alias does not already exists. */
1234 $alias = md5 ($alias);
1235 $p = VAR_ALIAS
. s2p ($alias);
1236 if (file_exists ($p))
1239 /* Create alias folder. */
1240 @mkdir
($p, 0755, true);
1241 if (!file_exists ($p))
1244 /* Generate password. */
1245 $md5_password = md5 ($password);
1247 /* Store informations. */
1249 $handle = fopen ($p, 'w');
1251 $md5_password . NL
.
1260 /** Update an alias.
1261 * @param $alias alias to update
1262 * @param $destination reference of the new destination
1263 * @param $password password to protect alias
1264 * @param $new_password optional new password to protect alias
1265 * @param $ip client's IP
1266 * @return "Ok" or "Error" string
1269 jirafeau_alias_update ($alias, $destination, $password,
1272 $alias = md5 ($alias);
1273 /* Check that alias exits. */
1274 $a = jirafeau_get_alias ($alias);
1278 /* Check that destination exists. */
1279 $l = jirafeau_get_link ($a["destination"]);
1283 /* Check password. */
1284 if ($a["md5_password"] != md5 ($password))
1287 $p = $a['md5_password'];
1288 if (strlen ($new_password) >= 8 &&
1289 strlen ($new_password) <= 32)
1290 $p = md5 ($new_password);
1291 else if (strlen ($new_password) > 0)
1294 /* Rewrite informations. */
1295 $p = VAR_ALIAS
. s2p ($alias) . $alias;
1296 $handle = fopen ($p, 'w');
1307 * @param $alias alias to get
1308 * @return alias destination or "Error" string
1311 jirafeau_alias_get ($alias)
1313 $alias = md5 ($alias);
1314 /* Check that alias exits. */
1315 $a = jirafeau_get_alias ($alias);
1319 return $a['destination'];
1323 jirafeau_clean_rm_alias ($alias)
1325 $p = s2p ("$alias");
1326 if (file_exists (VAR_ALIAS
. $p . $alias))
1327 unlink (VAR_ALIAS
. $p . $alias);
1328 $parse = VAR_ALIAS
. $p;
1330 while (file_exists ($parse)
1331 && ($scan = scandir ($parse))
1332 && count ($scan) == 2 // '.' and '..' folders => empty.
1333 && basename ($parse) != basename (VAR_ALIAS
))
1336 $parse = substr ($parse, 0, strlen($parse) - strlen(basename ($parse)) - 1);
1340 /** Delete an alias.
1341 * @param $alias alias to delete
1342 * @param $password password to protect alias
1343 * @return "Ok" or "Error" string
1346 jirafeau_alias_delete ($alias, $password)
1348 $alias = md5 ($alias);
1349 /* Check that alias exits. */
1350 $a = jirafeau_get_alias ($alias);
1354 /* Check password. */
1355 if ($a["md5_password"] != md5 ($password))
1358 jirafeau_clean_rm_alias ($alias);
1363 * Replace markers in templates.
1365 * Available markers have the scheme "###MARKERNAME###".
1367 * @param $content string Template text with markers
1368 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1369 * @return Template with replaced markers
1372 jirafeau_replace_markers ($content, $htmllinebreaks = false)
1375 '/###ORGANISATION###/',
1376 '/###CONTACTPERSON###/'
1378 $replacements = array(
1379 '[ORGANISATION PROVIDING THIS WEBSITE]',
1380 'contact@[THIS WEBSITE]'
1382 $content = preg_replace($patterns, $replacements, $content);
1384 if (true === $htmllinebreaks) {
1385 $content = nl2br($content);
patrick-canterino.de