<?php
	include('smart_resize_image.function.php');
	libxml_use_internal_errors(true);
	error_reporting(E_ALL);
	
	//date_default_timezone_set('America/Chicago'); // Seems to be too forward, this script attempts to update the page before the update is available
	date_default_timezone_set('America/Los_Angeles');
	$url = ""; // Image URL
	$format = "gif"; // Image format
	$date = date("Y-m-d"); // Current date, YYYY-MM-DD
	
	// This hurts so much
	if(date('N') == 7)
	{
		// IT'S SUNDAY. THIS MEANS "FUCK YOU PHAZE, FIX YOUR SCRIPT"
		// mime_content_type(filename) doesn't exist either and I simply can't be bothered troubleshooting that one.
		// So have this bandaid fix:
		$format = "jpeg";
	}
	
	$filenameBase = "dilbert_" . $date;
	$filename = $filenameBase . "." . $format;
	$filenameShrunk = $filenameBase . "_shrunk" . "." . $format;
	$dilbertFile = $filename; // Output image URL, can be regular or shrunk
	
	/*
		Daily Dilbert strip image retriever & generator, created by Phaze (phazepages.net).
		Do what you want with it (editing, redistribution etc.), but not misrepresenting who made it would be much appreciated.
	*/
	
	// I dunno if anyone will ever know this is a thing but I imagine it might be handy for some folk.
	if(isset($_GET['src']))
	{
		$source_code = file_get_contents(__FILE__);
		die("<!DOCTYPE HTML>\n".
		    "<html>\n".
		    "	<head>\n".
		    "		<link rel=\"stylesheet\" type=\"text/css\" href=\"dilbert.css\" />\n".
		    "		<title>Dilbert comic image server source code</title>\n".
		    "	</head>\n".
		    "	<body>\n".
		    "		<pre>\n".
		      htmlentities($source_code)."\n".
		    "		</pre>\n".
		    "	</body>\n".
		    "</html>");
	}
		
	// Provide the smaller image if requested
	if(isset($_GET['shrunk']))
	{
		$dilbertFile = $filenameShrunk;
	}
	
	//Consult the 'cache' to see if the current strip has already been downloaded.
	if(!file_exists($dilbertFile))
	{
		$dilbert = file_get_contents("http://dilbert.com"); // I'm going to delete myself on friday #wow #whoa
		$doc = new DOMDocument();
		$doc->loadHTML($dilbert);
		$xpath = new DOMXpath($doc);
		
		// Hopefully THIS will work and CONTINUE to work. Older xpath queries broke constantly.
		$elements = $xpath->query("//img[contains(@class, 'img-responsive img-comic')]");
		
		// Only interested in the first (most recent) image's URL
		if (!is_null($elements))
		{
			$url = $elements->item(0)->getAttribute("src");
		}
		
		// Enumerate the directory to delete any leftover files that are the same format as the requested image.
		// I really don't want to end up with > 1,000 Dilbert comics on my webserver since my host might complain.
		if ($handle = opendir('.'))
		{
			while (false !== ($entry = readdir($handle)))
			{
				// Get the file extension. Is the format of the file GIF? Delete any GIF files. Ditto for JPG if selecting JPG.
				if (substr($entry, strlen($entry) - 3, 3) === substr($format, strlen($format) - 3, 3))
				{
					unlink($entry);
				}
			}
			closedir($handle);
		}
		
		copy($url, $filename);
		
		list($width, $height) = getimagesize($filename);
		$newWidth = $width * 0.7;
		$newHeight = $height * 0.7;
		
		// https://github.com/Nimrod007/PHP_image_resize
		smart_resize_image($filename, null, $newWidth, $newHeight, true, $filenameShrunk, false, false, 100);
	}
	
	// Use a nice filename that isn't "dilbert.php" if someone tries to save this image!
	header('Content-Disposition: inline; filename="'.$dilbertFile.'"');
	
	// http://php.net/manual/en/function.header.php#61903
	// Getting headers sent by the client.
	$headers = apache_request_headers();
	
	// Checking if the client is validating their cache and if it is current.
	if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == filemtime($filename)))
	{
		// Client's cache is current, respond '304 Not Modified'.
		header('Last-Modified: '.gmdate("D, d M Y H:i:s", filemtime($filename)).' GMT', true, 304);
	}
	else
	{
		// Image not cached or cache outdated, respond '200 OK' and output the image.
		header('Last-Modified: '.gmdate("D, d M Y H:i:s", filemtime($filename)).' GMT', true, 200);
		header('Content-Length: '.filesize($filename));
		header('Content-Type: image/'.$format);
		
		// Render the image, based on format
		if($format == "jpeg")
		{
			//header('Content-Type: image/jpeg');
			$img = imagecreatefromjpeg($dilbertFile);
			imagejpeg($img);
			imagedestroy($img);
		}
		elseif($format == "png")
		{
			//header('Content-Type: image/png');
			$img = imagecreatefrompng($dilbertFile);
			imagepng($img);
			imagedestroy($img);
		}
		elseif($format == "gif")
		{
			//header('Content-Type: image/gif');
			$img = imagecreatefromgif($dilbertFile);
			imagegif($img);
			imagedestroy($img);
		}
	}
?>