<?php
////////////////////////////////////////////////////////////////////////
// Breeze Website Builder
// Copyright Silver Dolphin Solutions, LLC, Edward Lemmers, P.E.
// For licensing, see license.txt.
// Created:	3/10/2013	ELL
// Revised: 6/11/2015	ELL
// Added ability to handle GIF and PNG images is additon to JPG images.
// Revised: 8/3/2016	ELL
// Fixed bugs when no dimensions specified for image.

	include ("check_session.php");
	include ("lib/image_processing.php");
	
	$action = $_POST['action'];
	$sValue = stripslashes( $_POST['sValue'] ) ;
	$userfiles = $_REQUEST['userfiles'];
	
	////////////////////////////////////////////////////////////
	if ($action == "optimize")	// Parse sValue for images.
		$num_of_images_optimized = OptimizeImages($sValue, $userfiles, BWB_IMAGE_DIR);
	
	if ($action == "reset")	// Replace modified images with original images.
		$num_of_images_reset = ResetImages($sValue, $userfiles, BWB_IMAGE_DIR);
	////////////////////////////////////////////////////////////

	function OptimizeImages($sValue, $userfiles, $image_folder)
	{
		$result = 0;
		$doc_root = getenv('DOCUMENT_ROOT');
		$orig_image_path = $doc_root . $userfiles . "/" . $image_folder . "/orig";
			
		if (!file_exists($orig_image_path))
			mkdir($orig_image_path, 0755);
		
		$bad_chars = array("\"", "px", "%");
		$img_ext = array("jpg", "jpeg", "png", "gif");
		$last_img_tag_pos = 0;
		while ((strpos($sValue, "<img ", $last_img_tag_pos)) > 1)
		{
			$img_tag_pos = strpos($sValue, "<img ", $last_img_tag_pos);
			$last_img_tag_pos = $img_tag_pos + strlen("<img ");
			$next_img_tag_pos = strpos($sValue, "<img ", $last_img_tag_pos);
			if ($next_img_tag_pos === false)
				$next_img_tag_pos = strlen($sValue);
			
			$src_att_pos = strpos($sValue, "src=", $img_tag_pos);
			$end_src_pos = strpos($sValue, "\"", $src_att_pos + strlen("src=") + 2);
			$start_src_pos = $src_att_pos + strlen("src=") + 1;
			$src = substr($sValue, $start_src_pos, $end_src_pos - $start_src_pos);
			$src_parts = explode(".", $src);
			$tmp = strtolower($src_parts[count($src_parts) - 1]);
			if (!in_array($tmp, $img_ext))
				continue;			//jpeg, gif or png not found, can't process
				
			$src = str_replace("%20", " ", $src);	// The %20 substitution for spaces break it.
			if (substr($src, 0, 1) != "/")
				$src = "/" . $src;
			$image_path = $doc_root . $src;
			$image_file = basename($src);
			$orig_image_path_file = $orig_image_path . "/" . $image_file;
			list($width_orig, $height_orig) = getimagesize($image_path);
			
			$height_att_pos = strpos($sValue, "height", $img_tag_pos);
			if (($height_att_pos < $img_tag_pos) || ($height_att_pos > $next_img_tag_pos))	{
				// Height attribute not found, use actual image height.
				$height = $height_orig;
			}
			else	{
				$end_height_pos_1 = strpos($sValue, "\"", $height_att_pos + strlen("height") + 2);
				$end_height_pos_2 = strpos($sValue, ";", $height_att_pos + strlen("height") + 2);
				if (($end_height_pos_1 === false))
					$end_height_pos = $end_height_pos_2;
				elseif (($end_height_pos_2 === false))
					$end_height_pos = $end_height_pos_1;
				elseif ($end_height_pos_1 <  $end_height_pos_2)
						$end_height_pos = $end_height_pos_1;
				else
					$end_height_pos = $end_height_pos_2;
				
				$start_height_pos = $height_att_pos + strlen("height") + 1;
				$height = substr($sValue, $start_height_pos, $end_height_pos - $start_height_pos);
				$height = str_replace($bad_chars, "", $height);
			}
			
			$width_att_pos = strpos($sValue, "width", $img_tag_pos);
			if (($width_att_pos < $img_tag_pos) || ($width_att_pos > $next_img_tag_pos))	{
				// width attribute not found, use actual image width.
				$width = $width_orig;
			}
			else	{
				$end_width_pos_1 = strpos($sValue, "\"", $width_att_pos + strlen("width") + 2);
				$end_width_pos_2 = strpos($sValue, ";", $width_att_pos + strlen("width") + 2);
				if (($end_width_pos_1 === false))
					$end_width_pos = $end_width_pos_2;
				elseif (($end_width_pos_2 === false))
					$end_width_pos = $end_width_pos_1;
				elseif ($end_width_pos_1 <  $end_width_pos_2)
						$end_width_pos = $end_width_pos_1;
				else
					$end_width_pos = $end_width_pos_2;
					
				$start_width_pos = $width_att_pos + strlen("width") + 1;
				$width = substr($sValue, $start_width_pos, $end_width_pos - $start_width_pos);
				$width = str_replace($bad_chars, "", $width);
			}
			
			if (!file_exists($orig_image_path_file))
			{
				if (!copy($image_path, $orig_image_path_file))
				{
					echo "Failed to backup original image $image_path.  Skipping resize.<br>\n";
					contitue;
				}
			}
			
			if (resize_image($image_path, $width, $height, $image_path, 1))
			{
				echo "Resized $image_file from $width_orig wide by $height_orig tall to $width wide by $height tall.<br>\n";
				$result++;
			}
			else
				echo "Failed to resize image $image_file.<br>\n";
		}
		if ($result == 0)
			echo "No resizable images found.";
		return($result);
	}
	
	function ResetImages($sValue, $userfiles, $image_folder)
	{
		$doc_root = getenv('DOCUMENT_ROOT');
		$orig_image_path = $doc_root . $userfiles . "/" . $image_folder . "/orig";
		if (!file_exists($orig_image_path))
		{
			echo "Original images do not exist.  Most likely they were never optimized.  Click <a href='main.php>here</a> to return the the main menu.";
			return -1;
			exit;
		}
		
		$success = 0;
		$fail = 0;
		$last_img_tag_pos = 0;
		$img_ext = array("jpg", "jpeg", "png", "gif");
		while ((strpos($sValue, "<img ", $last_img_tag_pos)) > 1)
		{
			$img_tag_pos = strpos($sValue, "<img ", $last_img_tag_pos);
			$last_img_tag_pos = $img_tag_pos + strlen("<img ");
			
			$src_att_pos = strpos($sValue, "src=", $img_tag_pos);
			$end_src_pos = strpos($sValue, "\"", $src_att_pos + strlen("src=") + 2);
			$start_src_pos = $src_att_pos + strlen("src=") + 1;
			$src = substr($sValue, $start_src_pos, $end_src_pos - $start_src_pos);
			$src_parts = explode(".", $src);
			$tmp = strtolower($src_parts[count($src_parts) - 1]);
			if (!in_array($tmp, $img_ext))
				continue;			//jpeg, gif or png not found, image was never optimized.
			
			$src = str_replace("%20", " ", $src);	// The %20 substitution for spaces break it.
			if (substr($src, 0, 1) != "/")
				$src = "/" . $src;
			$image_path = $doc_root . $src;
			$image_file = basename($src);
			$orig_image_path_file = $orig_image_path . "/" . $image_file;
			
			if (file_exists($orig_image_path_file))
			{
				if (!copy($orig_image_path_file, $image_path))
				{
					echo "Failed to restore original image $orig_image_path_file.";
					$fail++;
				}
				else
					$success++;
			}
		}
		if (($fail == 0) && ($success > 0))
			echo "All of the images have been restored to their original resolution, but they will appear unchanged.  To enlarge the images, right click on them and select 'Image Properties'.  Then click on the 'Reset Size' button.<br>\n";
		elseif(($fail > 0) && ($success == 0))
			echo "WARNING: None of the images have been restored to their original resolution.<br>\n";
		elseif(($fail > 0) && ($success> 0))
			echo "Some of the images have been restored to their original resolution, but they will appear unchanged.  To enlarge the images, right click on them and select 'Image Properties'.  Then click on the 'Reset Size' button.<br>\n";
		elseif (($fail == 0) && ($success == 0))
			echo "No resizable images found.";
			
		return ($success);
	}
?>