<?php
// composer require abeautifulsite/simpleimage
// website: https://github.com/claviska/SimpleImage
include('../vendor/abeautifulsite/simpleimage/src/abeautifulsite/SimpleImage.php');

$bCSSfile = false;
$sFilename = null;

if (isset($_GET['file'])) {
    $sFilename = $_GET['file'];
}

if (isset($_SERVER['HTTP_REFERER'])) {
    $sReferer = $_SERVER['HTTP_REFERER'];
    $bCSSfile = (strpos($sReferer, '.css') !== false);
}

if (empty($sFilename) || !file_exists($sFilename)) {
    http_response_code(404);

    if (!$bCSSfile) {
        $sFilename = 'https://placeholdit.imgix.net/~text?txtsize=20&w=350&h=150&txt='.urlencode('['.$sFilename.']');
        $image = new abeautifulsite\SimpleImage($sFilename);
        $image->output();
    }
}


$last_modified_time = @filemtime($sFilename);
header("Expires: ".gmdate("D, d M Y H:i:s", $last_modified_time+1800)." GMT");

header("Cache-Control: max-age=1800");
header("Vary: Accept-Encoding");

if (array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)) {
    if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time) {
        header("HTTP/1.1 304 Not Modified");
        return;
    }
}

$image = new abeautifulsite\SimpleImage($sFilename);

// Resize image
if (isset($_GET['w'])) {
    $image->fit_to_width($_GET['w']);
}

$image->output();