<?php
declare(strict_types = 1);

/**
 * Création d'images redimensionnées.
 *
 * @license https://www.gnu.org/licenses/gpl-3.0.html
 * @link https://www.igalerie.org/
 */

$gets = ['file', 'item', 'key', 'orientation', 'quality', 'size'];
require_once(__DIR__ . '/includes/prepend.php');

// Vérification du format des paramètres.
$types = implode('|', array_merge_recursive(Image::EXT_ARRAY));
if (!preg_match('`^[a-z]?\d{1,12}\-[a-f\d]{32}\.(' . $types . ')$`i', $_GET['file'] ?? '', $file)
 || !preg_match('`^(.{1,255})(\.[a-z0-9]{3,4})$`i', $_GET['item'] ?? '')
 || !preg_match('`^[a-f0-9]{32}$`', $_GET['key'] ?? '')
 || !preg_match('`^\d{1,3}$`', $_GET['quality'] ?? '')
 || !preg_match('`^(\d{2,4})x(\d{2,4})$`', $_GET['size'] ?? '', $max_size))
{
	die(App::httpResponse(400));
}

// Vérification de la clé de sécurité.
$key_params = [$_GET['file'], $_GET['item'], $_GET['quality'], $_GET['size']];
if (isset($_GET['orientation']))
{
	if (!preg_match('`^\d$`', $_GET['orientation']))
	{
		die(App::httpResponse(400));
	}
	$key_params[] = $_GET['orientation'];
}
if (!Security::fileKeyVerify($key_params, $_GET['key']))
{
	die(App::httpResponse(403));
}

// On crée l'image redimensionnée si elle n'existe pas.
if (!file_exists($file_resize = GALLERY_ROOT . '/cache/resize/' . $_GET['file']))
{
	if (!file_exists($file_source = CONF_ALBUMS_PATH . '/' . $_GET['item']))
	{
		die('File does not exist.');
	}

	// On vérifie les dimensions.
	if (!$i = Image::getTypeSize($file_source))
	{
		die('Invalid image.');
	}
	if ($i['width'] > $max_size[1] || $i['height'] > $max_size[2])
	{
		// Création de l'image GD.
		$gd_image = GD::createFrom($file_source);
		if (is_string($gd_image))
		{
			die($gd_image);
		}
		if (is_bool($gd_image))
		{
			die(sprintf('Cannot create image (%s).', $i['filetype']));
		}

		// Redimensionnement.
		$dst_size = Image::getResizedSize($i['width'], $i['height'],
			(int) $max_size[1], (int) $max_size[2]);
		GD::resize($gd_image, 0, 0, $i['width'], $i['height'],
			0, 0, $dst_size['w'], $dst_size['h']);

		// Orientation.
		$metadata = new Metadata($file_source);
		$orientation = (int) $metadata->getExifValue('orientation');
		GD::orientation($gd_image, $orientation);

		// Enregistrement de l'image GD.
		GD::file($gd_image, $file_resize, Item::getTypeFile($file[1]), (int) $_GET['quality']);
	}
	else
	{
		$file_resize = $file_source;
	}
}

// Lecture du fichier.
Image::read($file_resize);
?>