<?php

	if(false) {
		error_reporting(E_ALL);
		ini_set('display_errors', true);
		ini_set('display_startuo_errors', true);
	}

	ob_start();

	try {

		define('TRIES', 3);
		define('ROOT', dirname(dirname(dirname(dirname(__DIR__)))) . '/app/');
		define('WEBROOT', ROOT . '/webroot/');
		define('FULL_BASE_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/');

		# If there is no source and thumb
		if(empty($_GET['thumb']) || empty($_GET['source'])) {
			$imageContent = file_get_contents('http://' . $_SERVER['HTTP_HOST'] . '/thumbs/no-image.90z75.png');

			header('Content-type: image/png');
			echo $imageContent;
			exit(0);
		}

		# Extract basic params
		$source = str_replace('..', '', $_GET['source']);
		$thumb = WEBROOT . str_replace('..', '', $_GET['thumb']);
		$type = lastFromDot($thumb);

		# Get the username and password
		include(ROOT . 'Config/config.php');
		$config = new MANICURE_CONFIG;
		$username = $config->default['username'];
		$passcode = $config->default['passcode'];

		# Create url to access manicure
		$url = $_SERVER['REMOTE_ADDR'] != '127.0.0.1' ? "http://{$username}.manicure.io/{$passcode}/" : "http://{$username}.manicure/{$passcode}/";

		$mode = @$_GET['mode'] ? $_GET['mode'] : 'crop';
		$modeParts = explode(':', $mode);
		$mode = $modeParts[0];

		# Get the mode
		switch($mode) {
			case 'wrap':
				$mode = 'scale';
				break;

			case 'clip':
				$mode = 'center';
				break;

			case 'match':
			default:
				$mode = 'crop';
		}

		if(isset($modeParts[1])) {
			$mode = $mode . ':' . $modeParts[1];
		}
		# Add mandatory params: src, domain & size
		$url .= $mode;
		$url .= '/';
		$url .= (empty($_GET['w']) ? '' : $_GET['w']) . 'x' . (empty($_GET['h']) ? '' : $_GET['h']);
		$url .= '/';
		$url .= FULL_BASE_URL . $source;

		$tries = TRIES;
		while($tries-- && (!file_exists($thumb) || !@getimagesize($thumb))) {
			if(file_exists($thumb)) unlink($thumb);

			# Get image content from url
			list($responseCode, $imageContent, $headers) = curl($url);

			# Throw exception
			if($responseCode < 200 || $responseCode >= 300 || !empty($headers['X-Manicure-Error'])) {
				throw new Exception("Manicure response code: {$responseCode}" . (!empty($headers['X-Manicure-Error']) ? ", {$headers['X-Manicure-Error']}" : null));
			}

			# Cache the result
			if(strlen($imageContent)) {

				# Set permissions and save to cache
				$umask = umask(0);
				@mkdir(dirname($thumb), 0755, true);
				file_put_contents($thumb, $imageContent);
				umask($umask);

				# If all is well skip the wait
				if(@getimagesize($thumb)) {
					break;
				}
			}

			usleep(100000);
		}

	} catch(Exception $ex) {
		echo $ex->getMessage();
	}

	# Handle errors
	$output = ob_get_clean();
	if($output) {
		file_put_contents(ROOT . 'tmp/logs/error.log', "\n" . date('Y-m-d H:i:s') . " Error: Thumb generation error: \n{$output}", FILE_APPEND);
	}

	# Return image to src element.
	if($type == 'jpeg') $type = 'jpg';
	header("Content-type: image/{$type}");
	echo !empty($imageContent) ? $imageContent : file_get_contents($thumb);



# ~ cURL wrapper - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	function curl($url) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, str_replace(' ', '%20', $url));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
		curl_setopt($ch, CURLOPT_TIMEOUT, 5);
		curl_setopt($ch, CURLOPT_HEADER, 1);
		curl_setopt($ch, CURLOPT_USERAGENT, 'VectorCMS thumbnail generator');

		# Get the response
		$response = curl_exec($ch);

		# Get the meta
		$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
		$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

		# Get the content intself
		$headers = substr($response, 0, $headerSize);
		$body = substr($response, $headerSize);

		# Parse headers
		$head = array();
		$headers = preg_split('~\r?\n~', $headers);
		foreach($headers as $i => $header) {
			@list($key, $value) = explode(':', $header);
			$head[trim($key)] = trim($value);
		}

		# Close the connection
		curl_close($ch);

		return array($code, $body, $head);
	}
