/ // cache directory must be writable by apache: // mkdir /var/www/html/ULF/data_plot/thumbcache // chown apache:apache /var/www/html/ULF/data_plot/thumbcache // note: JPG and PNG files are served directly by ulf_dbstatus-hover.php // and do not go through this script $datapath_plot = "/var/www/html/ULF/data_plot/"; $thumbcache = "/var/www/html/ULF/data_plot/thumbcache/"; $path = isset($_GET['path']) ? $_GET['path'] : ''; // security check - only allow paths within the expected data directory $allowed_base = realpath($datapath_plot); $realpath = realpath($path); if (empty($path) || $realpath === false || strpos($realpath, $allowed_base) !== 0 || !file_exists($realpath)) { http_response_code(404); exit; } $ext = strtolower(pathinfo($realpath, PATHINFO_EXTENSION)); // this script only handles PDFs - JPGs and PNGs are served directly if ($ext !== 'pdf') { http_response_code(404); exit; } // derive station code from path - expected structure is data_plot//filename $relative = substr($realpath, strlen($allowed_base) + 1); $parts = explode("/", $relative); $station = $parts[0]; $basename = pathinfo($realpath, PATHINFO_FILENAME); // build cache path $cache_dir = $thumbcache . $station . "/"; $cache_file = $cache_dir . $basename . ".jpg"; // check if we need to generate or regenerate the thumbnail $needs_gen = false; if (!file_exists($cache_file)) { $needs_gen = true; } else if (filemtime($realpath) > filemtime($cache_file)) { // source PDF is newer than cached thumbnail - regenerate $needs_gen = true; } if ($needs_gen) { // create cache directory for this station if it doesn't exist if (!is_dir($cache_dir)) { mkdir($cache_dir, 0755, true); } $source = escapeshellarg($realpath . '[0]'); $dest = escapeshellarg($cache_file); // convert first page of PDF to jpg with white background $cmd = "convert -density 72 -resize 400x -background white -flatten $source $dest"; exec($cmd, $output, $returncode); if ($returncode !== 0 || !file_exists($cache_file)) { http_response_code(500); exit; } } // serve the cached thumbnail header('Content-Type: image/jpeg'); header('Cache-Control: max-age=3600'); readfile($cache_file); ?>