<?php
//defined('ABSPATH') || exit;
// codingStandardsIgnoreStart
// WP sanitize functions are not available at this point in code, as the script will not be executed by WP, it will be placed in uploads/atec-webp and the .htaccess will redirect requests to this script.
$root = filter_var($_SERVER['DOCUMENT_ROOT'], FILTER_SANITIZE_URL);
$uri = filter_var($_SERVER['REQUEST_URI'], FILTER_SANITIZE_URL);
// codingStandardsIgnoreEnd
$path	= $root.'/'.$uri;
if ($uri=== '' || !file_exists($path)) { header('HTTP/1.0 404 Not Found'); exit; }

function atec_wpwp_sendFile($path, $mime, $str): void
{
	$info = getimagesize($path);
	header('X-Cache-Image: atec-WebP | '.$str.'.');
	header('Content-Type: image/' . $mime);
	// codingStandardsIgnoreStart
	readfile($path);
	// codingStandardsIgnoreEnd
	exit;
}

function atec_wpwp_checkFile($path): void
{
	// codingStandardsIgnoreStart
	// This file is executed outside of WP, via .htaccess redirect - so no WP functions available.
	$size = filesize($path);
	if ($size===false || $size==0) { header('X-Cache-Image: atec-WebP | Failed.'); unlink($path); }
	else header('X-Cache-Image: atec-WebP | Created.');
	// codingStandardsIgnoreEnd
}

$ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
$size = filesize($path);
if ($size!==false && $size>6144)
{
	$XwebpPath = $path.'.Xwebp.webp';
	if (class_exists('Imagick') && !empty(Imagick::queryFormats('WEBP')))
	{
		$img = new Imagick($path);
		if ($ext=== 'gif' && $img->getNumberImages()>1) { atec_wpwp_sendFile($path, 'gif', 'SKIP: Animated GIF'); }
		$img->setImageFormat('webp');
		if ($img->writeImage($XwebpPath))
		{
			atec_wpwp_checkFile($XwebpPath);
			header('Content-Type: image/webp');
			// codingStandardsIgnoreStart
			// Can not escape imageObject output as that would corrupt the image.
			//echo $img;
			echo $img->getImagesBlob();
			// codingStandardsIgnoreEnd
			exit;
		}
	}
	else
	{
		switch ($ext)
		{
			case 'bmp':
				$img = imagecreatefrombmp($path);
				// codingStandardsIgnoreStart
				// Can not escape imageObject output as that would corrupt the image.
				if (!$img) $img = imagecreatefromstring(file_get_contents($path));
				// codingStandardsIgnoreEnd
				break;
			case 'gif': $img = imagecreatefromgif($path); break;
			case 'png': $img = imagecreatefrompng($path); break;
			case 'jpg':
			case 'jpeg': $img = imagecreatefromjpeg($path); break;
		}

		if ($img)
		{
			if (in_array($ext,['png', 'gif']))
			{
				// codingStandardsIgnoreStart
				// Can not escape imageObject output as that would corrupt the image.
				if ($ext!== 'gif' || !preg_match('#(\x00\x21\xF9\x04.{4}\x00\x2C.*){2,}#s', file_get_contents($path)))
				{
					$width = imagesx($img);
					$height = imagesy($img);
					$newImg = imagecreatetruecolor($width, $height);
					imagealphablending($newImg, false);
					imagesavealpha($newImg, true);
					imagecopyresampled($newImg, $img, 0, 0, 0, 0, $width, $height, $width, $height);
					$img = $newImg;
					imagedestroy($newImg);
				}
				else $img=false;
				// codingStandardsIgnoreEnd
			}
			if ($img && ($result=imagewebp($img, $XwebpPath, in_array($ext,['jpg', 'jpeg'])?95:-1))) //IMG_WEBP_LOSSLESS
			{
				atec_wpwp_checkFile($XwebpPath);
				header('Content-Type: image/webp');
				imagewebp($img);
				exit;
			}
		}
	}
}
atec_wpwp_sendFile($path, $ext, 'Skip (size)');
?>