]>
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 <jerome@jutteau.fr>
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 separating each letters by a '/'.
24 * @return path finishing with a '/'
30 for ( $i = 0 ; $i < strlen ( $s ); $i ++
) {
32 if (( $i +
1 ) %
$block_size == 0 ) {
36 if ( strlen ( $s ) %
$block_size != 0 ) {
43 * Convert base 16 to base 64
44 * @returns A string based on 64 characters (0-9, a-z, A-Z, "-" and "_")
46 function base_16_to_64 ( $num )
48 $m = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_' ;
49 $hex2bin = array ( '0000' , # 0
68 # Convert long hex string to bin.
70 for ( $i = 0 ; $i < $size ; $i ++
) {
71 $b .= $hex2bin [ hexdec ( $num [ $i ])];
73 # Convert long bin to base 64.
75 for ( $i = $size - 6 ; $i >= 0 ; $i -= 6 ) {
76 $o = $m [ bindec ( substr ( $b , $i , 6 ))] . $o ;
78 # Some few bits remaining ?
79 if ( $i < 0 && $i > - 6 ) {
80 $o = $m [ bindec ( substr ( $b , 0 , $i +
6 ))] . $o ;
86 * Generate a random code.
87 * @param $l code length
88 * @return random code.
90 function jirafeau_gen_random ( $l )
97 for ( $i = 0 ; $i < $l ; $i ++
) {
98 $code .= dechex ( rand ( 0 , 15 ));
106 if ( isset ( $_SERVER [ 'HTTPS' ])) {
107 if ( 'on' == strtolower ( $_SERVER [ 'HTTPS' ]) ||
108 '1' == $_SERVER [ 'HTTPS' ]) {
111 } elseif ( isset ( $_SERVER [ 'SERVER_PORT' ]) && ( '443' == $_SERVER [ 'SERVER_PORT' ])) {
113 } elseif ( isset ( $_SERVER [ 'HTTP_X_FORWARDED_PROTO' ])) {
114 if ( $_SERVER [ 'HTTP_X_FORWARDED_PROTO' ] == 'https' ) {
121 function jirafeau_human_size ( $octets )
123 $u = array ( 'B' , 'KB' , 'MB' , 'GB' , 'TB' );
124 $o = max ( $octets , 0 );
125 $p = min ( floor (( $o ?
log ( $o ) : 0 ) / log ( 1024 )), count ( $u ) - 1 );
127 return round ( $o , 1 ) . $u [ $p ];
130 // Convert UTC timestamp to a datetime field
131 function jirafeau_get_datetimefield ( $timestamp )
133 $content = '<span class="datetime" data-datetime="' . strftime ( ' %Y - %m - %d %H : %M ' , $timestamp ) . '">'
134 . strftime ( ' %Y - %m - %d %H : %M ' , $timestamp ) . ' (GMT)</span>' ;
138 function jirafeau_fatal_error ( $errorText , $cfg = array ())
140 echo '<div class="error"><h2>Error</h2><p>' . $errorText . '</p></div>' ;
141 require ( JIRAFEAU_ROOT
. 'lib/template/footer.php' );
145 function jirafeau_clean_rm_link ( $link )
148 if ( file_exists ( VAR_LINKS
. $p . $link )) {
149 unlink ( VAR_LINKS
. $p . $link );
151 $parse = VAR_LINKS
. $p ;
153 while ( file_exists ( $parse )
154 && ( $scan = scandir ( $parse ))
155 && count ( $scan ) == 2 // '.' and '..' folders => empty.
156 && basename ( $parse ) != basename ( VAR_LINKS
)) {
158 $parse = substr ( $parse , 0 , strlen ( $parse ) - strlen ( basename ( $parse )) - 1 );
162 function jirafeau_clean_rm_file ( $hash )
165 $f = VAR_FILES
. $p . $hash ;
166 if ( file_exists ( $f ) && is_file ( $f )) {
169 if ( file_exists ( $f . '_count' ) && is_file ( $f . '_count' )) {
170 unlink ( $f . '_count' );
172 $parse = VAR_FILES
. $p ;
174 while ( file_exists ( $parse )
175 && ( $scan = scandir ( $parse ))
176 && count ( $scan ) == 2 // '.' and '..' folders => empty.
177 && basename ( $parse ) != basename ( VAR_FILES
)) {
179 $parse = substr ( $parse , 0 , strlen ( $parse ) - strlen ( basename ( $parse )) - 1 );
184 * transforms a php.ini string representing a value in an integer
185 * @param $value the value from php.ini
186 * @returns an integer for this value
188 function jirafeau_ini_to_bytes ( $value )
190 $modifier = substr ( $value , - 1 );
191 $bytes = substr ( $value , 0 , - 1 );
192 switch ( strtoupper ( $modifier )) {
212 * gets the maximum upload size according to php.ini
213 * @returns the maximum upload size in bytes
215 function jirafeau_get_max_upload_size_bytes ()
218 jirafeau_ini_to_bytes ( ini_get ( 'post_max_size' )),
219 jirafeau_ini_to_bytes ( ini_get ( 'upload_max_filesize' ))
224 * gets the maximum upload size according to php.ini
225 * @returns the maximum upload size string
227 function jirafeau_get_max_upload_size ()
229 return jirafeau_human_size ( jirafeau_get_max_upload_size_bytes ());
233 * get the maximal upload size for a data chunk in async uploads
234 * @param max_upload_chunk_size_bytes
236 function jirafeau_get_max_upload_chunk_size_bytes ( $max_upload_chunk_size_bytes = 0 )
238 if ( $max_upload_chunk_size_bytes > 0 ) {
240 jirafeau_get_max_upload_size_bytes (),
241 $max_upload_chunk_size_bytes
244 return jirafeau_get_max_upload_size_bytes ();
248 * gets a string explaining the error
249 * @param $code the error code
250 * @returns a string explaining the error
252 function jirafeau_upload_errstr ( $code )
255 case UPLOAD_ERR_INI_SIZE
:
256 case UPLOAD_ERR_FORM_SIZE
:
257 return t ( 'Your file exceeds the maximum authorized file size. ' );
259 case UPLOAD_ERR_PARTIAL
:
260 case UPLOAD_ERR_NO_FILE
:
262 t ( 'Your file was not uploaded correctly. You may succeed in retrying. ' );
264 case UPLOAD_ERR_NO_TMP_DIR
:
265 case UPLOAD_ERR_CANT_WRITE
:
266 case UPLOAD_ERR_EXTENSION
:
267 return t ( 'Internal error. You may not succeed in retrying. ' );
269 return t ( 'Unknown error. ' );
272 /** Remove link and it's file
273 * @param $link the link's name (hash)
276 function jirafeau_delete_link ( $link )
278 $l = jirafeau_get_link ( $link );
283 jirafeau_clean_rm_link ( $link );
289 if ( file_exists ( VAR_FILES
. $p . $hash . '_count' )) {
290 $content = file ( VAR_FILES
. $p . $hash . '_count' );
291 $counter = trim ( $content [ 0 ]);
296 $handle = fopen ( VAR_FILES
. $p . $hash . '_count' , 'w' );
297 fwrite ( $handle , $counter );
302 jirafeau_clean_rm_file ( $hash );
307 * Delete a file and it's links.
309 function jirafeau_delete_file ( $hash )
312 /* Get all links files. */
313 $stack = array ( VAR_LINKS
);
314 while (( $d = array_shift ( $stack )) && $d != null ) {
317 foreach ( $dir as $node ) {
318 if ( strcmp ( $node , '.' ) == 0 ||
strcmp ( $node , '..' ) == 0 ||
319 preg_match ( '/\.tmp/i' , " $node " )) {
323 if ( is_dir ( $d . $node )) {
324 /* Push new found directory. */
325 $stack [] = $d . $node . '/' ;
326 } elseif ( is_file ( $d . $node )) {
327 /* Read link informations. */
328 $l = jirafeau_get_link ( basename ( $node ));
332 if ( $l [ 'hash' ] == $hash ) {
334 jirafeau_delete_link ( $node );
339 jirafeau_clean_rm_file ( $hash );
344 /** hash file's content
345 * @param $method hash method, see 'file_hash' option. Valid methods are 'md5', 'md5_outside' or 'random'
346 * @param $file_path file to hash
347 * @returns hash string
349 function jirafeau_hash_file ( $method , $file_path )
353 return jirafeau_md5_outside ( $file_path );
355 return md5_file ( $file_path );
357 return jirafeau_gen_random ( 32 );
359 return md5_file ( $file_path );
362 /** hash part of file: start, end and size.
363 * This is a partial file hash, faster but weaker.
364 * @param $file_path file to hash
365 * @returns hash string
367 function jirafeau_md5_outside ( $file_path )
370 $handle = fopen ( $file_path , "r" );
371 if ( $handle === false ) {
374 $size = filesize ( $file_path );
375 if ( $size === false ) {
378 $first = fread ( $handle , 64 );
379 if ( $first === false ) {
382 if ( fseek ( $handle , $size < 64 ?
0 : $size - 64 ) == - 1 ) {
385 $last = fread ( $handle , 64 );
386 if ( $last === false ) {
389 $out = md5 ( $first . $last . $size );
396 * handles an uploaded file
397 * @param $file the file struct given by $_FILE[]
398 * @param $one_time_download is the file a one time download ?
399 * @param $key if not empty, protect the file with this key
400 * @param $time the time of validity of the file
401 * @param $ip uploader's ip
402 * @param $crypt boolean asking to crypt or not
403 * @param $link_name_length size of the link name
404 * @returns an array containing some information
405 * 'error' => information on possible errors
406 * 'link' => the link name of the uploaded file
407 * 'delete_link' => the link code to delete file
409 function jirafeau_upload ( $file , $one_time_download , $key , $time , $ip , $crypt , $link_name_length , $file_hash_method )
411 if ( empty ( $file [ 'tmp_name' ]) ||
! is_uploaded_file ( $file [ 'tmp_name' ])) {
414 array ( 'has_error' => true ,
415 'why' => jirafeau_upload_errstr ( $file [ 'error' ])),
417 'delete_link' => '' ));
420 /* array representing no error */
421 $noerr = array ( 'has_error' => false , 'why' => '' );
423 /* Crypt file if option is enabled. */
426 if ( $crypt == true && !( extension_loaded ( 'mcrypt' ) == true )) {
427 error_log ( "PHP extension mcrypt not loaded, won't encrypt in Jirafeau" );
429 if ( $crypt == true && extension_loaded ( 'mcrypt' ) == true ) {
430 $crypt_key = jirafeau_encrypt_file ( $file [ 'tmp_name' ], $file [ 'tmp_name' ]);
431 if ( strlen ( $crypt_key ) > 0 ) {
436 /* file information */
437 $hash = jirafeau_hash_file ( $file_hash_method , $file [ 'tmp_name' ]);
438 $name = str_replace ( NL
, '' , trim ( $file [ 'name' ]));
439 $mime_type = $file [ 'type' ];
440 $size = $file [ 'size' ];
442 /* does file already exist ? */
445 if ( file_exists ( VAR_FILES
. $p . $hash )) {
446 $rc = unlink ( $file [ 'tmp_name' ]);
447 } elseif (( file_exists ( VAR_FILES
. $p ) || @mkdir
( VAR_FILES
. $p , 0755 , true ))
448 && move_uploaded_file ( $file [ 'tmp_name' ], VAR_FILES
. $p . $hash )) {
454 array ( 'has_error' => true ,
455 'why' => t ( 'INTERNAL_ERROR_DEL' )),
457 'delete_link' => '' ));
460 /* Increment or create count file. */
462 if ( file_exists ( VAR_FILES
. $p . $hash . '_count' )) {
463 $content = file ( VAR_FILES
. $p . $hash . '_count' );
464 $counter = trim ( $content [ 0 ]);
467 $handle = fopen ( VAR_FILES
. $p . $hash . '_count' , 'w' );
468 fwrite ( $handle , $counter );
471 /* Create delete code. */
472 $delete_link_code = jirafeau_gen_random ( 5 );
474 /* hash password or empty. */
477 $password = md5 ( $key );
480 /* create link file */
481 $link_tmp_name = VAR_LINKS
. $hash . rand ( 0 , 10000 ) . '.tmp' ;
482 $handle = fopen ( $link_tmp_name , 'w' );
485 $name . NL
. $mime_type . NL
. $size . NL
. $password . NL
. $time .
486 NL
. $hash . NL
. ( $one_time_download ?
'O' : 'R' ) . NL
. time () .
487 NL
. $ip . NL
. $delete_link_code . NL
. ( $crypted ?
'C' : 'O' )
490 $hash_link = substr ( base_16_to_64 ( md5_file ( $link_tmp_name )), 0 , $link_name_length );
491 $l = s2p ( " $hash_link " );
492 if (! @mkdir
( VAR_LINKS
. $l , 0755 , true ) ||
493 ! rename ( $link_tmp_name , VAR_LINKS
. $l . $hash_link )) {
494 if ( file_exists ( $link_tmp_name )) {
495 unlink ( $link_tmp_name );
500 $handle = fopen ( VAR_FILES
. $p . $hash . '_count' , 'w' );
501 fwrite ( $handle , $counter );
504 jirafeau_clean_rm_file ( $hash_link );
508 array ( 'has_error' => true ,
509 'why' => t ( 'Internal error during file creation. ' )),
511 'delete_link' => '' );
513 return array ( 'error' => $noerr ,
514 'link' => $hash_link ,
515 'delete_link' => $delete_link_code ,
516 'crypt_key' => $crypt_key );
520 * Tells if a mime-type is viewable in a browser
521 * @param $mime the mime type
522 * @returns a boolean telling if a mime type is viewable
524 function jirafeau_is_viewable ( $mime )
527 $viewable = array ( 'image' , 'video' , 'audio' );
528 $decomposed = explode ( '/' , $mime );
529 if ( in_array ( $decomposed [ 0 ], $viewable ) && strpos ( $mime , 'image/svg+xml' ) === false ) {
532 $viewable = array ( 'text/plain' );
533 if ( in_array ( $mime , $viewable )) {
540 // Error handling functions.
541 //! Global array that contains all registered errors.
542 $error_list = array ();
545 * Adds an error to the list of errors.
546 * @param $title the error's title
547 * @param $description is a human-friendly description of the problem.
549 function add_error ( $title , $description )
552 $error_list [] = '<p>' . $title . '<br />' . $description . '</p>' ;
556 * Informs whether any error has been registered yet.
557 * @return true if there are errors.
562 return ! empty ( $error_list );
566 * Displays all the errors.
568 function show_errors ()
572 echo '<div class="error">' ;
573 foreach ( $error_list as $error ) {
580 function check_errors ( $cfg )
582 if ( file_exists ( JIRAFEAU_ROOT
. 'install.php' )
583 && !( $cfg [ 'installation_done' ] === true )) {
584 header ( 'Location: install.php' );
588 /* Checking for errors. */
589 if (! is_writable ( VAR_FILES
)) {
590 add_error ( t ( 'FILE_DIR_W' ), VAR_FILES
);
593 if (! is_writable ( VAR_LINKS
)) {
594 add_error ( t ( 'LINK_DIR_W' ), VAR_LINKS
);
597 if (! is_writable ( VAR_ASYNC
)) {
598 add_error ( t ( 'ASYNC_DIR_W' ), VAR_ASYNC
);
601 if ( $cfg [ 'enable_crypt' ] && $cfg [ 'litespeed_workaround' ]) {
602 add_error ( t ( 'INCOMPATIBLE_OPTIONS_W' ), 'enable_crypt=true<br>litespeed_workaround=true' );
605 if ( $cfg [ 'one_time_download' ] && $cfg [ 'litespeed_workaround' ]) {
606 add_error ( t ( 'INCOMPATIBLE_OPTIONS_W' ), 'one_time_download=true<br>litespeed_workaround=true' );
611 * Read link information
612 * @return array containing information.
614 function jirafeau_get_link ( $hash )
617 $link = VAR_LINKS
. s2p ( " $hash " ) . $hash ;
619 if (! file_exists ( $link )) {
624 $out [ 'file_name' ] = trim ( $c [ 0 ]);
625 $out [ 'mime_type' ] = trim ( $c [ 1 ]);
626 $out [ 'file_size' ] = trim ( $c [ 2 ]);
627 $out [ 'key' ] = trim ( $c [ 3 ], NL
);
628 $out [ 'time' ] = trim ( $c [ 4 ]);
629 $out [ 'hash' ] = trim ( $c [ 5 ]);
630 $out [ 'onetime' ] = trim ( $c [ 6 ]);
631 $out [ 'upload_date' ] = trim ( $c [ 7 ]);
632 $out [ 'ip' ] = trim ( $c [ 8 ]);
633 $out [ 'link_code' ] = trim ( $c [ 9 ]);
634 $out [ 'crypted' ] = trim ( $c [ 10 ]) == 'C' ;
640 * List files in admin interface.
642 function jirafeau_admin_list ( $name , $file_hash , $link_hash )
644 echo '<fieldset><legend>' ;
646 echo t ( 'FILENAME' ) . ": " . jirafeau_escape ( $name );
648 if (! empty ( $file_hash )) {
649 echo t ( 'FILE' ) . ": " . jirafeau_escape ( $file_hash );
651 if (! empty ( $link_hash )) {
652 echo t ( 'LINK' ) . ": " . jirafeau_escape ( $link_hash );
654 if ( empty ( $name ) && empty ( $file_hash ) && empty ( $link_hash )) {
661 echo '<th>' . t ( 'ACTION' ) . '</th>' ;
664 /* Get all links files. */
665 $stack = array ( VAR_LINKS
);
666 while (( $d = array_shift ( $stack )) && $d != null ) {
668 foreach ( $dir as $node ) {
669 if ( strcmp ( $node , '.' ) == 0 ||
strcmp ( $node , '..' ) == 0 ||
670 preg_match ( '/\.tmp/i' , " $node " )) {
673 if ( is_dir ( $d . $node )) {
674 /* Push new found directory. */
675 $stack [] = $d . $node . '/' ;
676 } elseif ( is_file ( $d . $node )) {
677 /* Read link information. */
678 $l = jirafeau_get_link ( $node );
684 if (! empty ( $name ) && ! @preg_match
( "/ $name /i" , jirafeau_escape ( $l [ 'file_name' ]))) {
687 if (! empty ( $file_hash ) && $file_hash != $l [ 'hash' ]) {
690 if (! empty ( $link_hash ) && $link_hash != $node ) {
693 /* Print link information. */
696 '<strong><a id="upload_link" href="f.php?h=' . jirafeau_escape ( $node ) . '" title="' .
697 t ( 'DL_PAGE' ) . '">' . jirafeau_escape ( $l [ 'file_name' ]) . '</a></strong><br/>' ;
698 echo t ( 'TYPE' ) . ': ' . jirafeau_escape ( $l [ 'mime_type' ]) . '<br/>' ;
699 echo t ( 'SIZE' ) . ': ' . jirafeau_human_size ( $l [ 'file_size' ]) . '<br>' ;
700 echo t ( 'EXPIRE' ) . ': ' . ( $l [ 'time' ] == - 1 ?
'∞' : jirafeau_get_datetimefield ( $l [ 'time' ])) . '<br/>' ;
701 echo t ( 'ONETIME' ) . ': ' . ( $l [ 'onetime' ] == 'O' ?
'Yes' : 'No' ) . '<br/>' ;
702 echo t ( 'UPLOAD_DATE' ) . ': ' . jirafeau_get_datetimefield ( $l [ 'upload_date' ]) . '<br/>' ;
703 if ( strlen ( $l [ 'ip' ]) > 0 ) {
704 echo t ( 'ORIGIN' ) . ': ' . $l [ 'ip' ] . '<br/>' ;
707 echo '<form method="post">' .
708 '<input type = "hidden" name = "action" value = "download"/>' .
709 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
710 jirafeau_admin_csrf_field () .
711 '<input type = "submit" value = "' . t ( 'DL' ) . '" />' .
713 '<form method="post">' .
714 '<input type = "hidden" name = "action" value = "delete_link"/>' .
715 '<input type = "hidden" name = "link" value = "' . $node . '"/>' .
716 jirafeau_admin_csrf_field () .
717 '<input type = "submit" value = "' . t ( 'DEL_LINK' ) . '" />' .
719 '<form method="post">' .
720 '<input type = "hidden" name = "action" value = "delete_file"/>' .
721 '<input type = "hidden" name = "hash" value = "' . $l [ 'hash' ] . '"/>' .
722 jirafeau_admin_csrf_field () .
723 '<input type = "submit" value = "' . t ( 'DEL_FILE_LINKS' ) . '" />' .
730 echo '</table></fieldset>' ;
734 * Clean expired files.
735 * @return number of cleaned files.
737 function jirafeau_admin_clean ()
740 /* Get all links files. */
741 $stack = array ( VAR_LINKS
);
742 while (( $d = array_shift ( $stack )) && $d != null ) {
745 foreach ( $dir as $node ) {
746 if ( strcmp ( $node , '.' ) == 0 ||
strcmp ( $node , '..' ) == 0 ||
747 preg_match ( '/\.tmp/i' , " $node " )) {
751 if ( is_dir ( $d . $node )) {
752 /* Push new found directory. */
753 $stack [] = $d . $node . '/' ;
754 } elseif ( is_file ( $d . $node )) {
755 /* Read link information. */
756 $l = jirafeau_get_link ( basename ( $node ));
760 $p = s2p ( $l [ 'hash' ]);
761 if ( $l [ 'time' ] > 0 && $l [ 'time' ] < time () ||
// expired
762 ! file_exists ( VAR_FILES
. $p . $l [ 'hash' ]) ||
// invalid
763 ! file_exists ( VAR_FILES
. $p . $l [ 'hash' ] . '_count' )) { // invalid
764 jirafeau_delete_link ( $node );
775 * Clean old async transfers.
776 * @return number of cleaned files.
778 function jirafeau_admin_clean_async ()
781 /* Get all links files. */
782 $stack = array ( VAR_ASYNC
);
783 while (( $d = array_shift ( $stack )) && $d != null ) {
786 foreach ( $dir as $node ) {
787 if ( strcmp ( $node , '.' ) == 0 ||
strcmp ( $node , '..' ) == 0 ||
788 preg_match ( '/\.tmp/i' , " $node " )) {
792 if ( is_dir ( $d . $node )) {
793 /* Push new found directory. */
794 $stack [] = $d . $node . '/' ;
795 } elseif ( is_file ( $d . $node )) {
796 /* Read async information. */
797 $a = jirafeau_get_async_ref ( basename ( $node ));
801 /* Delete transfers older than 1 hour. */
802 if ( time () - $a [ 'last_edited' ] > 3600 ) {
803 jirafeau_async_delete ( basename ( $node ));
813 * Better strval function for debug purposes
815 function jirafeau_strval ( $value )
817 if ( gettype ( $value ) == "boolean" ) {
818 return $value ?
'true' : 'false' ;
820 return strval ( $value );
824 * Show file/folder permissions
826 function jirafeau_fileperms ( $path )
828 $out = substr ( sprintf ( " %o " , @fileperms
( $path )), - 4 ) . ", " ;
829 $out .= "read " . ( is_readable ( $path ) ?
"OK" : "KO" ) . ", " ;
830 $out .= "write " . ( is_writable ( $path ) ?
"OK" : "KO" );
835 * Show some useful informations for bug reporting.
837 function jirafeau_admin_bug_report ( $cfg )
839 $out = "<fieldset><legend>" . t ( 'REPORTING_AN_ISSUE' ) . "</legend>" ;
840 $out .= "If you have a problem related to Jirafeau, please <a href='https://gitlab.com/mojo42/Jirafeau/-/issues'>open an issue</a>, explain your problem in english and copy-paste the following content:<br/><br/><code>" ;
842 $out .= "# Jirafeau<br/>" ;
843 $out .= "- version: " . JIRAFEAU_VERSION
. "<br/>" ;
844 $jirafeau_options = [
847 'litespeed_workaround' ,
852 'maximal_upload_size' ,
854 'max_upload_chunk_size_bytes'
856 foreach ( $jirafeau_options as & $o ) {
858 $out .= "- $o : " . jirafeau_strval ( $v ) . " (" . gettype ( $v ) . ")<br/>" ;
862 $out .= "# PHP options<br/>" ;
863 $out .= "- php version: " . phpversion () . "<br/>" ;
864 $out .= "- mcrypt version: " . phpversion ( 'mcrypt' ) . "<br/>" ;
867 'upload_max_filesize' ,
869 'max_execution_time' ,
872 foreach ( $php_options as & $o ) {
874 $out .= "- $o : " . jirafeau_strval ( $v ) . " (" . gettype ( $v ). ")<br/>" ;
876 $out .= "- can set_time_limit: " . ( set_time_limit ( 0 ) ?
"yes" : "no" ) . "<br/>" ;
879 $out .= "# File permissions<br/>" ;
880 $out .= "- 'var' folder permissions: " . jirafeau_fileperms ( $cfg [ 'var_root' ]) . "<br/>" ;
881 $out .= "- 'file' folder permissions: " . jirafeau_fileperms ( VAR_FILES
) . "<br/>" ;
882 $out .= "- 'links' folder permissions: " . jirafeau_fileperms ( VAR_LINKS
) . "<br/>" ;
883 $out .= "- 'async' folder permissions: " . jirafeau_fileperms ( VAR_ASYNC
) . "<br/>" ;
886 $out .= "# Server details<br/>" ;
887 $out .= "- server software: " . $_SERVER [ "SERVER_SOFTWARE" ] . "<br/>" ;
890 $out .= "# OS details<br/>" ;
891 $out .= "- OS: " . php_uname () . "<br/>" ;
894 $out .= "# Browser details<br/>" ;
895 $out .= "<script type='text/javascript' lang='Javascript'>
896 // @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-v3-or-Later
897 document.write('- html5 support: ' + (check_html5_file_api() ? 'yes' : 'no') + '<br/>');
898 document.write('- user agent: ' + navigator.userAgent + '<br/>');
903 $out .= "# Memory<br/>" ;
904 $out .= "- memory_get_peak_usage: " . jirafeau_human_size ( memory_get_peak_usage ()) . "<br/>" ;
906 $out .= "</code></fieldset>" ;
911 * Read async transfer information
912 * @return array containing information.
914 function jirafeau_get_async_ref ( $ref )
917 $refinfos = VAR_ASYNC
. s2p ( " $ref " ) . " $ref " ;
919 if (! file_exists ( $refinfos )) {
923 $c = file ( $refinfos );
924 $out [ 'file_name' ] = trim ( $c [ 0 ]);
925 $out [ 'mime_type' ] = trim ( $c [ 1 ]);
926 $out [ 'key' ] = trim ( $c [ 2 ], NL
);
927 $out [ 'time' ] = trim ( $c [ 3 ]);
928 $out [ 'onetime' ] = trim ( $c [ 4 ]);
929 $out [ 'ip' ] = trim ( $c [ 5 ]);
930 $out [ 'last_edited' ] = trim ( $c [ 6 ]);
931 $out [ 'next_code' ] = trim ( $c [ 7 ]);
936 * Delete async transfer information
938 function jirafeau_async_delete ( $ref )
941 if ( file_exists ( VAR_ASYNC
. $p . $ref )) {
942 unlink ( VAR_ASYNC
. $p . $ref );
944 if ( file_exists ( VAR_ASYNC
. $p . $ref . '_data' )) {
945 unlink ( VAR_ASYNC
. $p . $ref . '_data' );
947 $parse = VAR_ASYNC
. $p ;
949 while ( file_exists ( $parse )
950 && ( $scan = scandir ( $parse ))
951 && count ( $scan ) == 2 // '.' and '..' folders => empty.
952 && basename ( $parse ) != basename ( VAR_ASYNC
)) {
954 $parse = substr ( $parse , 0 , strlen ( $parse ) - strlen ( basename ( $parse )) - 1 );
959 * Init a new asynchronous upload.
960 * @param $filename Name of the file to send
961 * @param $one_time One time upload parameter
962 * @param $key eventual password (or blank)
963 * @param $time time limit
964 * @param $ip ip address of the client
965 * @return a string containing a temporary reference followed by a code or a string starting with 'Error'
967 function jirafeau_async_init ( $filename , $type , $one_time , $key , $time , $ip )
969 /* Create temporary folder. */
972 $code = jirafeau_gen_random ( 4 );
974 $ref = jirafeau_gen_random ( 32 );
975 $p = VAR_ASYNC
. s2p ( $ref );
976 } while ( file_exists ( $p ));
977 @mkdir
( $p , 0755 , true );
978 if (! file_exists ( $p )) {
979 return 'Error: cannot create async folder.' ;
982 /* touch empty data file */
983 $w_path = $p . $ref . '_data' ;
986 /* md5 password or empty */
989 $password = md5 ( $key );
992 /* Store information. */
994 $handle = fopen ( $p , 'w' );
997 str_replace ( NL
, '' , trim ( $filename )) . NL
.
998 str_replace ( NL
, '' , trim ( $type )) . NL
. $password . NL
.
999 $time . NL
. ( $one_time ?
'O' : 'R' ) . NL
. $ip . NL
.
1000 time () . NL
. $code . NL
1004 return $ref . NL
. $code ;
1008 * Append a piece of file on the asynchronous upload.
1009 * @param $ref asynchronous upload reference
1010 * @param $file piece of data
1011 * @param $code client code for this operation
1012 * @param $max_file_size maximum allowed file size
1013 * @return a string containing a next code to use or a string starting with 'Error'
1015 function jirafeau_async_push ( $ref , $data , $code , $max_file_size )
1017 /* Get async infos. */
1018 $a = jirafeau_get_async_ref ( $ref );
1020 /* Check some errors. */
1021 if ( count ( $a ) == 0 ) {
1022 return "Error: cannot find transfer" ;
1024 if ( $a [ 'next_code' ] != " $code " ) {
1025 return "Error: bad transfer code" ;
1027 if ( $data [ 'error' ] != UPLOAD_ERR_OK
) {
1028 // Check error code in https://www.php.net/manual/en/features.file-upload.errors.php
1029 $data_details = print_r ( $data , true );
1030 return "Error: upload error: { $data_details }" ;
1032 if ( empty ( $data [ 'tmp_name' ])) {
1033 return "Error: missing tmp_name" ;
1035 if (! is_uploaded_file ( $data [ 'tmp_name' ])) {
1036 return "Error: tmp_name may not be uploaded" ;
1042 $r_path = $data [ 'tmp_name' ];
1043 $w_path = VAR_ASYNC
. $p . $ref . '_data' ;
1045 /* Check that file size is not above upload limit. */
1046 if ( $max_file_size > 0 &&
1047 filesize ( $r_path ) +
filesize ( $w_path ) > $max_file_size * 1024 * 1024 ) {
1048 jirafeau_async_delete ( $ref );
1049 return "Error: file size is above upload limit" ;
1052 /* Concatenate data. */
1053 $r = fopen ( $r_path , 'r' );
1054 $w = fopen ( $w_path , 'a' );
1056 if ( fwrite ( $w , fread ( $r , 1024 )) === false ) {
1059 jirafeau_async_delete ( $ref );
1060 return "Error: cannot write file" ;
1067 /* Update async file. */
1068 $code = jirafeau_gen_random ( 4 );
1069 $handle = fopen ( VAR_ASYNC
. $p . $ref , 'w' );
1072 $a [ 'file_name' ] . NL
. $a [ 'mime_type' ] . NL
. $a [ 'key' ] . NL
.
1073 $a [ 'time' ] . NL
. $a [ 'onetime' ] . NL
. $a [ 'ip' ] . NL
.
1074 time () . NL
. $code . NL
1081 * Finalize an asynchronous upload.
1082 * @param $ref asynchronous upload reference
1083 * @param $code client code for this operation
1084 * @param $crypt boolean asking to crypt or not
1085 * @param $link_name_length link name length
1086 * @return a string containing the download reference followed by a delete code or a string starting with 'Error'
1088 function jirafeau_async_end ( $ref , $code , $crypt , $link_name_length , $file_hash_method )
1090 /* Get async infos. */
1091 $a = jirafeau_get_async_ref ( $ref );
1093 ||
$a [ 'next_code' ] != " $code " ) {
1094 return "Error: bad code for ending transfer" ;
1097 /* Generate link infos. */
1098 $p = VAR_ASYNC
. s2p ( $ref ) . $ref . "_data" ;
1099 if (! file_exists ( $p )) {
1100 return "Error: referenced file does not exist" ;
1105 if ( $crypt == true && extension_loaded ( 'mcrypt' ) == true ) {
1106 $crypt_key = jirafeau_encrypt_file ( $p , $p );
1107 if ( strlen ( $crypt_key ) > 0 ) {
1112 $hash = jirafeau_hash_file ( $file_hash_method , $p );
1113 $size = filesize ( $p );
1115 $delete_link_code = jirafeau_gen_random ( 5 );
1117 /* File already exist ? */
1118 if (! file_exists ( VAR_FILES
. $np )) {
1119 @mkdir
( VAR_FILES
. $np , 0755 , true );
1121 if (! file_exists ( VAR_FILES
. $np . $hash )) {
1122 rename ( $p , VAR_FILES
. $np . $hash );
1125 /* Increment or create count file. */
1127 if ( file_exists ( VAR_FILES
. $np . $hash . '_count' )) {
1128 $content = file ( VAR_FILES
. $np . $hash . '_count' );
1129 $counter = trim ( $content [ 0 ]);
1132 $handle = fopen ( VAR_FILES
. $np . $hash . '_count' , 'w' );
1133 fwrite ( $handle , $counter );
1137 $link_tmp_name = VAR_LINKS
. $hash . rand ( 0 , 10000 ) . '.tmp' ;
1138 $handle = fopen ( $link_tmp_name , 'w' );
1141 $a [ 'file_name' ] . NL
. $a [ 'mime_type' ] . NL
. $size . NL
.
1142 $a [ 'key' ] . NL
. $a [ 'time' ] . NL
. $hash . NL
. $a [ 'onetime' ] . NL
.
1143 time () . NL
. $a [ 'ip' ] . NL
. $delete_link_code . NL
. ( $crypted ?
'C' : 'O' )
1146 $hash_link = substr ( base_16_to_64 ( md5_file ( $link_tmp_name )), 0 , $link_name_length );
1147 $l = s2p ( " $hash_link " );
1148 if (! @mkdir
( VAR_LINKS
. $l , 0755 , true )) {
1149 return "Error: cannot create folder in LINKS" ;
1151 if (! rename ( $link_tmp_name , VAR_LINKS
. $l . $hash_link )) {
1152 return "Error: cannot rename file in LINKS" ;
1155 /* Clean async upload. */
1156 jirafeau_async_delete ( $ref );
1157 return $hash_link . NL
. $delete_link_code . NL
. urlencode ( $crypt_key );
1160 function jirafeau_crypt_create_iv ( $base , $size )
1163 while ( strlen ( $iv ) < $size ) {
1166 $iv = substr ( $iv , 0 , $size );
1171 * Crypt file and returns decrypt key.
1172 * @param $fp_src file path to the file to crypt.
1173 * @param $fp_dst file path to the file to write crypted file (could be the same).
1174 * @return decrypt key composed of the key and the iv separated by a point ('.')
1176 function jirafeau_encrypt_file ( $fp_src , $fp_dst )
1178 $fs = filesize ( $fp_src );
1179 if ( $fs === false ||
$fs == 0 ||
!( extension_loaded ( 'mcrypt' ) == true )) {
1183 /* Prepare module. */
1184 $m = mcrypt_module_open ( 'rijndael-256' , '' , 'ofb' , '' );
1186 $crypt_key = jirafeau_gen_random ( 10 );
1187 $hash_key = md5 ( $crypt_key );
1188 $iv = jirafeau_crypt_create_iv ( $hash_key , mcrypt_enc_get_iv_size ( $m ));
1190 mcrypt_generic_init ( $m , $hash_key , $iv );
1192 $r = fopen ( $fp_src , 'r' );
1193 $w = fopen ( $fp_dst , 'c' );
1195 $enc = mcrypt_generic ( $m , fread ( $r , 1024 ));
1196 if ( fwrite ( $w , $enc ) === false ) {
1203 mcrypt_generic_deinit ( $m );
1204 mcrypt_module_close ( $m );
1210 * @param $fp_src file path to the file to decrypt.
1211 * @param $fp_dst file path to the file to write decrypted file (could be the same).
1212 * @param $k string composed of the key and the iv separated by a point ('.')
1213 * @return key used to decrypt. a string of length 0 is returned if failed.
1215 function jirafeau_decrypt_file ( $fp_src , $fp_dst , $k )
1217 $fs = filesize ( $fp_src );
1218 if ( $fs === false ||
$fs == 0 ||
extension_loaded ( 'mcrypt' ) == false ) {
1223 $m = mcrypt_module_open ( 'rijndael-256' , '' , 'ofb' , '' );
1224 /* Extract key and iv. */
1226 $hash_key = md5 ( $crypt_key );
1227 $iv = jirafeau_crypt_create_iv ( $hash_key , mcrypt_enc_get_iv_size ( $m ));
1229 $r = fopen ( $fp_src , 'r' );
1230 $w = fopen ( $fp_dst , 'c' );
1232 $dec = mdecrypt_generic ( $m , fread ( $r , 1024 ));
1233 if ( fwrite ( $w , $dec ) === false ) {
1240 mcrypt_generic_deinit ( $m );
1241 mcrypt_module_close ( $m );
1246 * Check if Jirafeau is password protected for visitors.
1247 * @return true if Jirafeau is password protected, false otherwise.
1249 function jirafeau_has_upload_password ( $cfg )
1251 return count ( $cfg [ 'upload_password' ]) > 0 ;
1255 * Challenge password for a visitor.
1256 * @param $password password to be challenged
1257 * @return true if password is valid, false otherwise.
1259 function jirafeau_challenge_upload_password ( $cfg , $password )
1261 if (! jirafeau_has_upload_password ( $cfg )) {
1264 foreach ( $cfg [ 'upload_password' ] as $p ) {
1265 if ( $password == $p ) {
1273 * Test if the given IP is whitelisted by the given list.
1275 * @param $allowedIpList array of allowed IPs
1276 * @param $challengedIp IP to be challenged
1277 * @return true if IP is authorized, false otherwise.
1279 function jirafeau_challenge_ip ( $allowedIpList , $challengedIp )
1281 foreach ( $allowedIpList as $i ) {
1282 if ( $i == $challengedIp ) {
1285 // CIDR test for IPv4 only.
1286 if ( strpos ( $i , '/' ) !== false ) {
1287 list ( $subnet , $mask ) = explode ( '/' , $i );
1288 if (( ip2long ( $challengedIp ) & ~
(( 1 << ( 32 - $mask )) - 1 )) == ip2long ( $subnet )) {
1297 * Check if Jirafeau has a restriction on the IP address for uploading.
1298 * @return true if uploading is IP restricted, false otherwise.
1300 function jirafeau_upload_has_ip_restriction ( $cfg )
1302 return count ( $cfg [ 'upload_ip' ]) > 0 ;
1306 * Test if visitor's IP is authorized to upload at all.
1308 * @param $cfg configuration
1309 * @param $challengedIp IP to be challenged
1310 * @return true if IP is authorized, false otherwise.
1312 function jirafeau_challenge_upload_ip ( $cfg , $challengedIp )
1314 // If no IP address have been listed, allow upload from any IP
1315 if (! jirafeau_upload_has_ip_restriction ( $cfg )) {
1318 return jirafeau_challenge_ip ( $cfg [ 'upload_ip' ], $challengedIp );
1322 * Test if visitor's IP is authorized to upload without a password.
1324 * @param $cfg configuration
1325 * @param $challengedIp IP to be challenged
1326 * @return true if IP is authorized, false otherwise.
1328 function jirafeau_challenge_upload_ip_without_password ( $cfg , $challengedIp )
1330 return jirafeau_challenge_ip ( $cfg [ 'upload_ip_nopassword' ], $challengedIp );
1334 * Test if visitor's IP is authorized or password is supplied and authorized
1335 * @param $ip IP to be challenged
1336 * @param $password password to be challenged
1337 * @return true if access is valid, false otherwise.
1339 function jirafeau_challenge_upload ( $cfg , $ip , $password )
1341 return jirafeau_challenge_upload_ip_without_password ( $cfg , $ip ) ||
1342 (! jirafeau_has_upload_password ( $cfg ) && ! jirafeau_upload_has_ip_restriction ( $cfg )) ||
1343 ( jirafeau_challenge_upload_password ( $cfg , $password ) && jirafeau_challenge_upload_ip ( $cfg , $ip ));
1346 /** Tell if we have some HTTP headers generated by a proxy */
1347 function has_http_forwarded ()
1350 ! empty ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ]) ||
1351 ! empty ( $_SERVER [ 'http_X_forwarded_for' ]);
1355 * Generate IP list from HTTP headers generated by a proxy
1356 * @return array of IP strings
1358 function get_ip_list_http_forwarded ()
1361 if (! empty ( $_SERVER [ 'HTTP_X_FORWARDED_FOR' ])) {
1362 $l = explode ( ',' , $_SERVER [ 'HTTP_X_FORWARDED_FOR' ]);
1366 foreach ( $l as $ip ) {
1367 array_push ( $ip_list , preg_replace ( '/\s+/' , '' , $ip ));
1370 if (! empty ( $_SERVER [ 'http_X_forwarded_for' ])) {
1371 $l = explode ( ',' , $_SERVER [ 'http_X_forwarded_for' ]);
1372 foreach ( $l as $ip ) {
1373 // Separate IP from port
1374 $ipa = explode ( ':' , $ip );
1375 if ( $ipa === false ) {
1379 array_push ( $ip_list , preg_replace ( '/\s+/' , '' , $ip ));
1386 * Get the ip address of the client from REMOTE_ADDR
1387 * or from HTTP_X_FORWARDED_FOR if behind a proxy
1388 * @returns the client ip address
1390 function get_ip_address ( $cfg )
1392 $remote = $_SERVER [ 'REMOTE_ADDR' ];
1393 if ( count ( $cfg [ 'proxy_ip' ]) == 0 ||
! has_http_forwarded ()) {
1397 $ip_list = get_ip_list_http_forwarded ();
1398 if ( count ( $ip_list ) == 0 ) {
1402 foreach ( $cfg [ 'proxy_ip' ] as $proxy_ip ) {
1403 if ( $remote != $proxy_ip ) {
1406 // Take the last IP (the one which has been set by the defined proxy).
1407 return end ( $ip_list );
1413 * Convert hexadecimal string to base64
1415 function hex_to_base64 ( $hex )
1418 foreach ( str_split ( $hex , 2 ) as $pair ) {
1419 $b .= chr ( hexdec ( $pair ));
1421 return base64_encode ( $b );
1425 * Replace markers in templates.
1427 * Available markers have the scheme "###MARKERNAME###".
1429 * @param $content string Template text with markers
1430 * @param $htmllinebreaks boolean Convert linebreaks to BR-Tags
1431 * @return Template with replaced markers
1433 function jirafeau_replace_markers ( $content , $htmllinebreaks = false )
1436 '/###ORGANISATION###/' ,
1437 '/###CONTACTPERSON###/' ,
1440 $replacements = array (
1441 $GLOBALS [ 'cfg' ][ 'organisation' ],
1442 $GLOBALS [ 'cfg' ][ 'contactperson' ],
1443 $GLOBALS [ 'cfg' ][ 'web_root' ]
1445 $content = preg_replace ( $patterns , $replacements , $content );
1447 if ( true === $htmllinebreaks ) {
1448 $content = nl2br ( $content );
1454 function jirafeau_escape ( $string )
1456 return htmlspecialchars ( $string , ENT_QUOTES
);
1459 function jirafeau_admin_session_start ()
1461 $_SESSION [ 'admin_auth' ] = true ;
1462 $_SESSION [ 'admin_csrf' ] = md5 ( uniqid ( mt_rand (), true ));
1465 function jirafeau_admin_session_end ()
1467 $_SESSION = array ();
1471 function jirafeau_admin_session_logged ()
1473 return isset ( $_SESSION [ 'admin_auth' ]) &&
1474 isset ( $_SESSION [ 'admin_csrf' ]) &&
1475 isset ( $_POST [ 'admin_csrf' ]) &&
1476 $_SESSION [ 'admin_auth' ] === true &&
1477 $_SESSION [ 'admin_csrf' ] === $_POST [ 'admin_csrf' ];
1480 function jirafeau_admin_csrf_field ()
1482 return "<input type='hidden' name='admin_csrf' value='" . $_SESSION [ 'admin_csrf' ] . "'/>" ;
1485 function jirafeau_dir_size ( $dir )
1488 foreach ( glob ( rtrim ( $dir , '/' ). '/*' , GLOB_NOSORT
) as $entry ) {
1489 $size +
= is_file ( $entry ) ?
filesize ( $entry ) : jirafeau_dir_size ( $entry );
1494 function jirafeau_export_cfg ( $cfg )
1496 $content = '<?php' . NL
;
1497 $content .= '/* This file was generated by the install process. ' .
1498 'You can edit it. Please see config.original.php to understand the ' .
1499 'configuration items. */' . NL
;
1500 $content .= ' $cfg = ' . var_export ( $cfg , true ) . ';' ;
1502 $fileWrite = file_put_contents ( JIRAFEAU_CFG
, $content );
1504 if ( false === $fileWrite ) {
1505 jirafeau_fatal_error ( t ( 'Can not write local configuration file' ));
1509 function jirafeau_mkdir ( $path )
1511 return !(! file_exists ( $path ) && ! @mkdir
( $path , 0755 ));
1515 * Returns true whether the path is writable or we manage to make it
1516 * so, which essentially is the same thing.
1517 * @param $path is the file or directory to be tested.
1518 * @return true if $path is writable.
1520 function jirafeau_is_writable ( $path )
1522 /* "@" gets rid of error messages. */
1523 return is_writable ( $path ) || @chmod
( $path , 0777 );
1526 function jirafeau_check_var_dir ( $path )
1528 $mkdir_str1 = t ( 'CANNOT_CREATE_DIR' ) . ':' ;
1529 $mkdir_str2 = t ( 'MANUAL_CREATE' );
1530 $write_str1 = t ( 'DIR_NOT_W' ) . ':' ;
1531 $write_str2 = t ( 'You should give the write permission to the web server on ' .
1533 $solution_str = t ( 'HERE_SOLUTION' ) . ':' ;
1535 if (! jirafeau_mkdir ( $path ) ||
! jirafeau_is_writable ( $path )) {
1536 return array ( 'has_error' => true ,
1537 'why' => $mkdir_str1 . '<br /><code>' .
1538 $path . '</code><br />' . $solution_str .
1539 '<br />' . $mkdir_str2 );
1542 foreach ( array ( 'files' , 'links' , 'async' ) as $subdir ) {
1543 $subpath = $path . $subdir ;
1545 if (! jirafeau_mkdir ( $subpath ) ||
! jirafeau_is_writable ( $subpath )) {
1546 return array ( 'has_error' => true ,
1547 'why' => $mkdir_str1 . '<br /><code>' .
1548 $subpath . '</code><br />' . $solution_str .
1549 '<br />' . $mkdir_str2 );
1553 return array ( 'has_error' => false , 'why' => '' );
1556 function jirafeau_add_ending_slash ( $path )
1558 return $path . (( substr ( $path , - 1 ) == '/' ) ?
'' : '/' );
1561 function jirafeau_default_web_root ()
1563 return $_SERVER [ 'HTTP_HOST' ] . str_replace ( basename ( __FILE__
), '' , $_SERVER [ 'REQUEST_URI' ]);
patrick-canterino.de