<?php

class FastDeliver {
    ## class-config:
    private static $extCacheTime = 84600;
    private static $allowedFiles='
        css.css
        buttons.js
        sitemap.txt
        htmlClasses.js
        bilder/download.svg
        bilder/enlargeBox.svg
        bilder/resizeBox.svg
        font/Oxygen Mono Source-Code-Pro Ubuntu Mono.css
    ';

    public function __construct ( ) {
    }


    public function deliver( $file, $type ) {
        $type = str_replace(' ', '+', $type);
        if ( false === strpos( self::$allowedFiles, $file ) ) {
             http_response_code(403);
             error_log( "FastDeliver.php: (Fatal) File '$file' not allowed in class-config" );
             exit;
        }

        $zippedFile = $file . '.gz';

        if ( is_file( $file ) && is_readable( $file ) ) {

            if ( is_file( $zippedFile ) && is_readable( $zippedFile ) ) {
                if ( filemtime( $file ) > filemtime( $zippedFile ) ) {
                    $this -> createZippedFile( $file, $zippedFile );
                }
            } elseif ( ! is_file( $zippedFile ) )  {
                $this -> createZippedFile( $file, $zippedFile );
            }

            header( "Content-Type:$type; charset=UTF-8" );
            header( "X-Sender:FastDeliver.php" );

            if ( self::$extCacheTime ) {
                header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + self::$extCacheTime ) . " GMT" );
                header(" Cache-Control: public, max-age=" . self::$extCacheTime );
            }
            if ( false === strpos( $_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip' ) ) {
                header('Content-Length: ' . filesize($file));
                readfile( $file );
                exit;
            } else {
                header( 'Vary: Accept-Encoding' );
                header( 'Content-Encoding: gzip' );
                if (! is_file( $zippedFile ) ) {
                    error_log( "$zippedFile not found" );
                }
                header('Content-Length: ' . filesize($zippedFile));
                readfile( $zippedFile );
                exit;
            }

        } else {
            error_log( "FastDeliver.php: (Fatal) File '$file' not exists or not readable" );
        }
    }

    function createZippedFile( $file, $zippedFile ) {
        $error = intval( trim( `gzip -9 -c < '$file' > '$zippedFile' 2> /dev/null; echo $?` ) );
        if ( $error != 0 ) {
            error_log( "FastDeliver.php: error by trying gzip -c < '$file' > '$zippedFile' 2> /dev/null; echo \$?; in a shell" );
            $_SERVER['HTTP_ACCEPT_ENCODING'] = '';
        } else {
            error_log( "FastDeliver.php: File '$zippedFile' created." );
        }
        return $error;
    }
}
$o = new FastDeliver();
$o -> deliver( $_GET['file'],$_GET['type'] ) ;
