<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

define('CACHE_TIME', 290304000); 	// 7 days

class Img extends MY_Controller
{
	// We want to inherit MY_Controller to gain access to its functions,
	// but we don't want the overhead its constructor brings for ever image requested.
	public function __construct()
	{
		CI_Controller::__construct();
	}

	public function index($source_file)
	{
		// Apache already confirmed that the file exists and is a JPG, PNG, or GIF.
		$source_file          = "/" . implode("/", func_get_args());
		$original_source_file = $source_file;
		$source_file          = ABSOLUTE_PATH . $source_file;

		$this->sendImage($source_file, $original_source_file);
	}

	public function setDPR($dpr)
	{
		$_SESSION["devicePixelRatio"] = $dpr;
	}

	private function sendImage($source_file, $original_source_file)
	{
		$source_file          = str_replace(array("../", "//"), array("", "/"), urldecode($source_file));
		$original_source_file = str_replace(array("../", "//"), array("", "/"), urldecode($original_source_file));

		// Ensure that the image requested is in the web root.
		if(stripos($source_file, ABSOLUTE_PATH) !== 0) {
			$this->http404();
			exit();
		}

		// Check if the image to send exists
		if(!file_exists($source_file))
		{
			$this->http404();
			exit();
		}

		$retina_file = preg_replace('/\.(jpe?g|png|gif|webp)$/i', '@2x.$1', $source_file);
		$source_ext  = strtolower(pathinfo($source_file, PATHINFO_EXTENSION));

		if($source_ext == "jpg")
		{
			$source_ext = "jpeg";
		}

		// Check if a cookie is set
	    $cookie_value = false;
	    if(isset($_SESSION["devicePixelRatio"]))
	    {
	        $cookie_value = intval($_SESSION["devicePixelRatio"]);
	    }
	    else
	    {
	    	$cookie_value = 1;
	    }

        // Force revalidation of cache on next request
        $cache_directive = 'no-cache';

	    // Check if DPR is high enough to warrant retina image
	    if($cookie_value !== false && $cookie_value > 1 && file_exists($retina_file))
	    {
	        $source_file = $retina_file;
	    }

	    if(isset($_SERVER['MOD_XSENDFILE_ENABLED']) && $_SERVER['MOD_XSENDFILE_ENABLED'])
    	{
	    	header("X-SendFile: $source_file", true);
	    	header("Content-Type: image/" . $source_ext, true);
	    	header("Content-Disposition: inline; filename=\"" . addslashes(basename($original_source_file)) . "\"", true);
	    	exit;
	    }

	    // Send cache headers
	    $mtime 	= filemtime($source_file);
	    $size 	= filesize($source_file);
	    $etag 	= '"'.$mtime.$size.'"';
	    header("Cache-Control: private, {$cache_directive}, max-age=".CACHE_TIME, true);
	    date_default_timezone_set('GMT');
	    header('Expires: '.gmdate('D, d M Y H:i:s', time()+CACHE_TIME).' GMT', true);
	    header("ETag: $etag", true);

	    if(isset($_SERVER['HTTP_IF_NONE_MATCH']) && ($_SERVER['HTTP_IF_NONE_MATCH']) === $etag)
	    {
	        // File in cache hasn't change
	        header('Last-Modified: '.gmdate('D, d M Y H:i:s', $mtime).' GMT', true, 304);
	        exit();
	    }

	    if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && (strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) === $mtime))
	    {
	        // File in cache hasn't change
	        header('Last-Modified: '.gmdate('D, d M Y H:i:s', $mtime).' GMT', true, 304);
	        exit();
	    }

	    // Send image headers
	    header("Content-Type: image/".$source_ext, true);
	    header('Content-Length: '.$size, true);
	    readfile($source_file);
	    exit();
	}

	public function thumb($w, $h, $crop)
	{
		Mainframe::init();

		if((string)$crop === "0")
		{
			$crop = false;
		}

		$source_file          = "/" . urldecode($this->input->get("src"));
		$original_source_file = $source_file;
		$source_file          = ABSOLUTE_PATH . str_replace("//", "/", $source_file);
		$resized              = ABSOLUTE_PATH . Mainframe::thumbnail($source_file, $w, $h, $crop, Mainframe::site()->webp ? IMAGETYPE_WEBP : null);
		$source_file          = $resized;

		$this->sendImage($source_file, $original_source_file);
	}
}
