<?php 
/**
* 
*/
class Output
{
    
    function __construct()
    {
        $this->_zlib_oc = @ini_get('zlib.output_compression');
        if(file_exists($mimes))
        {
            include $mimes;
        }
    }

    function _display($output = '')
    {
        global $BM, $CFG;

        if(extension_loaded('zlib'))
        {
            if(isset($_SERVER['HTTP_ACCEPT_ENCODING']) AND strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE)
            {
                ob_start('ob_gzhandler');
            }

            if(preg_match("|</body>.*?</html>|is", $output))
            {
                $output = preg_replace("|</body>.*?</html>|is", '', $output);

                $output .= '</body></html>';
            }
        }

        function _write_cache($output)
        {
            $CI = &get_instance();
            $path = 'cache/';
            $cache_path = $path;

            if (is_dir($cache_path) OR !is_writable($cache_path))
            {
                $cache_path .= md5($uri);

                if(!$fp = @fopen($cache_path, FOPEN_WRITE_CREATE_DESTRUCTIVE))
                {
                    return;
                }

                $expire = time()+($expire*60);

                if(flock($fp, LOCK_EX))
                {
                    fwrite($fp, $expire, 'TS--->'.$output);
                    flock($fp, LOCK_UN);
                }
                else
                {
                    return;
                }
                fclose($fp);
                @chmod($cache_path, FILE_WRITE_MODE);
            }
        }
    }

    function _display_cache(&$CFG, &$URI)
    {
        $cache_path = 'cache/';

        $uri = $this->uri_string;

        $filepath = $cache_path.md5($uri);

        if(!@file_exists($filepath))
        {
            return false;
        }

        if(!$fp = @fopen($filepath, FOPEN_READ))
        {
            return FALSE;
        }

        flock($fp, LOCK_SH);

        $cache = '';
        if(filesize($filepath) > 0)
        {
            $cache = fread($fp, filesize($filepath));
        }

        flock($fp, LOCK_UN);
        fclose($fp);

        if(!preg_match("/(\d+TS---->)/", $cache, $match))
        {
            return FALSE;
        }
        
        if(time()>=trim(str_replace('TS---->', '', $match[1])))
        {
            if(is_writable($cache_path))
            {
                @unlink($filepath);
                return FALSE;
            }
        }
        $this->_display(str_replace($match[0], '', $cache));
        return TRUE;
    }
}