<?php
/*Copyright (c) 2009, Dan "Ducky" Little & GeoMOOSE.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/


function normalizePath($my_path_components, $url) {
	if(substr($url, 0, 7) == 'http://' or substr($url, 0, 8) == 'https://') {
		return $url;
	} elseif($url[0] == '/') {
		return 'http://localhost'.$url;
	} else {
		return 'http://localhost'.implode('/',$my_path_components).'/'.$url;
	}
}

$downloadCount = 0;
function getImage($url) {
	global $downloadCount, $CONFIGURATION;
#	$dlFileName = $outputFileName.'2';

	$dlFileName = $CONFIGURATION['temp'].'print_'.time().$downloadCount;
	$downloadCount += 1;

	$ch = curl_init($url);
	

	#print $dlFileName;
	#print "<br/>";

	$outfile = fopen($dlFileName, "w");
	curl_setopt($ch, CURLOPT_FILE, $outfile);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_exec($ch);

	$mimetype = curl_getinfo($ch,CURLINFO_CONTENT_TYPE);
	curl_close($ch);
	fclose($outfile);

	$image = false;

	if(!(strpos($mimetype,'png') === false)) {
		$image = imagecreatefrompng($dlFileName);
	} elseif(!(strpos($mimetype,'gif') === false)) {
		$image = imagecreatefromgif($dlFileName);
	} elseif (!(strpos($mimetype,'jpeg') === false)) {
		$image = imagecreatefromjpeg($dlFileName);
	}

	return $image;
}


function renderImage($mapbook, $layers_json,  $mapImageWidth, $mapImageHeight, $extent, $sketches=array()) { 
	global $CONFIGURATION;

	$mapserverUrl = $CONFIGURATION['mapserver_url'];

#	$server = 'http://'.$_SERVER['HTTP_HOST'];
	$server = 'http://'.$CONFIGURATION['server_name'];
	if((int)$_SERVER['SERVER_PORT'] != 80) {
		$server = $server . ':' . $_SERVER['SERVER_PORT'];
	}

	$path_components = explode('/', $_SERVER['SCRIPT_NAME']);
	array_pop($path_components); # Remove script name
	array_pop($path_components); # Remove the php directory reference
	$serverRoot = implode('/', $path_components).'/';


	$urls = array();
	$opacities = array();
	for($i = 0; $i < sizeof($layers_json['order']); $i++) {
		$source_name = $layers_json['order'][$i];

		$source = getMapSource($mapbook, $source_name);
		$url = '';

		if($source->getAttribute('type') == 'wms') {
			$url = $layers_json[$source_name]['url'];

			if(substr($url, sizeof($url)-2, 1) != '?') {
				$url = $url.'?';
			}

			$url = $url . 'SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&EXCEPTIONS=application%2Fvnd.ogc.se_inimage';

			# See if we specify the format in the params...
			if($layers_json[$source_name]['params']['format']) {
				$format = $layers_json[$source_name]['params']['format'];
				unset($layers_json[$source_name]['params']['format']);
			} else if($layers_json[$source_name]['params']['FORMAT']) {
				$format = $layers_json[$source_name]['params']['FORMAT'];
				unset($layers_json[$source_name]['params']['FORMAT']);
			} else {
				$format = 'image/jpeg';
			}

			# See if we specify the srs in the params...
			if($layers_json[$source_name]['params']['srs']) {
				$srs = $layers_json[$source_name]['params']['srs'];
				unset($layers_json[$source_name]['params']['srs']);
			} else if($layers_json[$source_name]['params']['SRS']) {
				$srs = $layers_json[$source_name]['params']['SRS'];
				unset($layers_json[$source_name]['params']['SRS']);
			} else {
				$srs = $CONFIGURATION['projection'];
			}

			$url = $url . '&SRS='.$srs;
			$url = $url . '&FORMAT='.$format;
			$url = $url . '&WIDTH='.$mapImageWidth;
			$url = $url . '&HEIGHT='.$mapImageHeight;
			$url = $url . '&BBOX='.implode(',', $extent);
			$url = $url . '&LAYERS='.implode(',', $layers_json[$source_name]['layers']);

		} else if($source->getAttribute('type') == 'mapserver') {
			$mapfile = $source->getElementsByTagName('file')->item(0)->nodeValue;	
			if($mapfile[0] == '.') {
				$mapfile = $CONFIGURATION['root'].$mapfile;
			}

			if($layers_json[$source_name]['url']) {
				$url = $layers_json[$source_name]['url'];
			} else {
				$url = $mapserverUrl;
			}

			$url = $url . '?map=' . $mapfile;
			$url = $url . '&mode=map';
			$url = $url . '&mapsize=' . $mapImageWidth . '+' . $mapImageHeight;
			$url = $url . '&mapext=' . implode('+', $extent);
			$url = $url . '&layers=' . implode('+', $layers_json[$source_name]['layers']);
		}

		if(substr($url,0,4)  == 'http') {
			# Do nothing as this url is absolute enough or our purposes.
		} else if($url[0] == '/') {
			$url = $server . $url;
		} else if($url[0] == '.') {
			$url = $server . $serverRoot . substr($url, 1, sizeof($url));
		} else {
			$url = $server . $serverRoot . $url;
		}

		foreach($layers_json[$source_name]['params'] as $k=>$v) {
			$url = $url . '&' . $k . '=' . $v;
		}

		array_push($urls, $url);
		array_push($opacities, $layers_json[$source_name]['opacity']);
	}

	$printImage = imagecreatetruecolor($mapImageWidth, $mapImageHeight);
	$colorWhite =  imagecolorallocate($printImage, 255, 255, 255);
	imagefill($printImage, 0, 0, $colorWhite);

	$urls = array_reverse($urls);
	$opacities = array_reverse($opacities);
	for($i = 0; $i < sizeof($urls); $i++) {
		$image = getImage($urls[$i]);
		#ImageCopyResized($printImage, $image, 0,0,0,0, $mapImageWidth, $mapImageHeight, ImageSX($image), ImageSY($image));
		if($image) {
			ImageCopyMerge($printImage, $image, 0, 0, 0, 0, $mapImageWidth, $mapImageHeight, (float)$opacities[$i]);
		}
	}

	# now add the sketches on top of the map...
	for($i = 0; $i < sizeof($sketches); $i++) {
		#print $sketches[$i]['wkt'];
		$sketch_map = ms_newMapObj('print/print_shape.map',$CONFIGURATION['root']);
		$sketch_map->setExtent($extent[0], $extent[1], $extent[2], $extent[3]);
		$sketch_map->setSize($mapImageWidth, $mapImageHeight);

		$shape = ms_shapeObjFromWKT($sketches[$i]['wkt']);

		#print $sketches[$i]['title'];

		if($shape->{type} == MS_SHAPE_POLYGON) {
			$layer = $sketch_map->getLayerByName('poly-draw');
			$class = $layer->getClass(0);

			if($sketches[$i]['title']) {
				$class->settext($sketches[$i]['title']);
			}

			$st_fill = $class->getStyle(0);
			if($sketches[$i]['fill'] and $sketches[$i]['label_only'] != 'true' and $sketches[$i]['fill'] != 'none') {
				$c = translateColor($sketches[$i]['fill']);
				# if we get "white" turn it slightly grey to prevent it from being made
				# transparent
				if($c[0] == 255 and $c[1] == 255 and $c[2] == 255) {
					$c[2] = 254;
				}
				$st_fill->color->setRGB($c[0], $c[1], $c[2]);
			} else {
				$st_fill->color->setRGB(255,255,255);
			}

			$st_border = $class->getStyle(1);
			if($sketches[$i]['stroke'] and $sketches[$i]['label_only'] != 'true') {
				$c = translateColor($sketches[$i]['stroke']);
				$st_border->outlinecolor->setRGB($c[0], $c[1], $c[2]);
			} else {
				$st_border->outlinecolor->setRGB(255,255,255);
			}

			$layer->addFeature($shape);
		} elseif($shape->{type} == MS_SHAPE_POINT) {
			$layer = $sketch_map->getLayerByName('point-draw');
			$class = $layer->getClass(0);
			$st = $class->getStyle(0);

			if($sketches[$i]['title']) {
				$class->settext($sketches[$i]['title']);
			}
			if($sketches[$i]['fill'] and $sketches[$i]['label_only'] != 'true') {
				$c = translateColor($sketches[$i]['fill']);
				$st->color->setRGB($c[0], $c[1], $c[2]);
			} else {
				$st->color->setRGB(255,255,255);
			}

			if($sketches[$i]['stroke'] and $sketches[$i]['label_only'] != 'true') {
				$c = translateColor($sketches[$i]['stroke']);
				$st->outlinecolor->setRGB($c[0], $c[1], $c[2]);
			} else {
				$st->outlinecolor->setRGB(255,0,0);
			}
			$layer->addFeature($shape);
		} elseif($shape->{type} == MS_SHAPE_LINE) {
			$layer = $sketch_map->getLayerByName('line-draw');
			$class = $layer->getClass(0);
			$st = $class->getStyle(0);

			if($sketches[$i]['title']) {
				$class->settext($sketches[$i]['title']);
			}
			if($sketches[$i]['stroke'] and $sketches[$i]['label_only'] != 'true') {
				$c = translateColor($sketches[$i]['stroke']);
				$st->color->setRGB($c[0], $c[1], $c[2]);
			} else {
				$st->color->setRGB(255,255,255);
			}
			$layer->addFeature($shape);
		}

#		$layer = $sketch_map->getLayer(0);

		$sketches_image = $sketch_map->prepareImage();
		$sketches_image = $sketch_map->draw();

		$uniqueId = 'sketch_'.time().getmypid();
		$tempDir = $CONFIGURATION['temp'];

		$filename = $tempDir.'/'.$uniqueId.'.png';

		$sketches_image->saveImage($filename);
		$image = ImageCreateFromPng($filename);
#		ImageCopyResized($printImage, $image, 0,0,0,0, $mapImageWidth, $mapImageHeight, $mapImageWidth, $mapImageHeight); #ImageSX($image), ImageSX($image));
		ImageCopyMerge($printImage, $image, 0, 0, 0, 0, $mapImageWidth, $mapImageHeight, (float)$sketches[$i]['opacity'] * 100.0);

	}

	return $printImage;
}

# returns a 3 element array containing r,g,b as integers between 0 and 255
function translateColor($color) {
	$basic_colors = array('aqua' => array(0,255,255), 'black' => array(0,0,0), 'blue' => array(0,0,255), 'fuchsia' => array(255,0,255), 'gray' => array(128,128,128), 'grey' => array(128,128,128), 'green' => array(0,128,0), 'lime' => array(0,255,0), 'maroon' => array(128,0,0), 'navy' => array(0,0,128), 'olive' => array(128,128,0), 'purple' => array(128,0,128), 'red' => array(255,0,0), 'silver' => array(192,192,192), 'teal' => array(0,128,128), 'white' => array(255,255,255), 'yellow' => array(255,255,0));
	if($basic_colors[$color]) {
		return $basic_colors[$color];
	}

	# Six character hex code
	if(preg_match('/\#....../', $color)) {
		$r = substr($color, 1,2);
		$g = substr($color, 3,2);
		$b = substr($color, 5,2);
		return array(hexdec($r), hexdec($g), hexdec($b));
	# Three character hex code
	} elseif (preg_match('/\#.../', $color)) {
		$r = substr($color, 1,1);
		$g = substr($color, 2,1);
		$b = substr($color, 3,1);
		$r = $r.$r;
		$g = $g.$g;
		$b = $b.$b;
		return array(hexdec($r), hexdec($g), hexdec($b));
	# CSS RGB
	} elseif (preg_match('/rgb\(.+\)/', $color)) {

	}
}

?>