<?php

ob_start("ob_gzhandler");
define('CACHE_DIR', dirname(__FILE__).'/cache/');
$nocache = true;
$cache_life = 300; // Tiempo de vida de la caché en segundos
$cache_file = CACHE_DIR.md5($_SERVER['REQUEST_URI']);

if (!function_exists('file_put_contents')) {
    function file_put_contents($filename, $content) {
        if ($fhandler = fopen($filename, 'w')) {
            $result = fwrite($fhandler, $content);
            fclose($fhandler);
            return $result;
        }
        return false;
    }
}

function update() {
    $content = ob_get_contents();

    if ($GLOBALS['nocache'] !== true) {
        file_put_contents($GLOBALS['cache_file'], $content);
    }

    return $content; // Mostrar en la primera llamada
}

function autoclean($age) {
    if (is_dir(CACHE_DIR)) {
        if ($dh = opendir(CACHE_DIR)) {
            while (($file = readdir($dh)) !== false) {
                if (is_file(CACHE_DIR . $file) && (time() - filemtime(CACHE_DIR.$file)) >= $age) {
                    unlink(CACHE_DIR . $file);
                }
            }
            closedir($dh);
        }
    }
}

if (isset($_REQUEST['flushcache'])) {
    if (is_dir(CACHE_DIR)) {
        if ($dh = opendir(CACHE_DIR)) {
            if (!empty($_REQUEST['olderthan']) && is_numeric($_REQUEST['olderthan'])) {
                $tcache = floor($_REQUEST['olderthan']);
                while (($file = readdir($dh)) !== false) {
                    if (is_file(CACHE_DIR . $file) && (time() - filemtime(CACHE_DIR.$file)) >= $tcache) {
                        unlink(CACHE_DIR . $file);
                    }
                }
            }
            else {
                while (($file = readdir($dh)) !== false) {
                    if (is_file(CACHE_DIR . $file)) {
                        unlink(CACHE_DIR . $file);
                    }
                }
            }
            closedir($dh);
        }
    }
}

if (file_exists($cache_file) && (time() - filemtime($cache_file)) < $cache_life) {
    $content = file_get_contents($cache_file);
    echo $content;
    exit;
}

ob_start('update');

?>
