<?php
/*
 * PHP Printing Service for GeoMOOSE
 * (c) 2008 Dan "Ducky" Little
 * written for the OpenMNND Project
 */
# Include GeoMOOSE PHP Utility Function Library
include('geomoose_php_util.php');
include('Configuration.php');

# Make the PHP Script Shut Up, but still give something useful if there
# is a legit error or parsing bug.
#error_reporting(E_ERROR | E_PARSE);

# These are "auto-detected" if these function have renderHTML or renderPDF
include('printHTML.php');
include('printPDF.php');

# Read in the XML String
#$xmlString = file_get_contents('print_test4.xml');
$xmlString = $GLOBALS['HTTP_RAW_POST_DATA']; 

# Parse the XML String into the DOM
$document = new DOMDocument();
$document->loadXML($xmlString);

# Get a list of maps
$input = $document->getElementsByTagName('input')->item(0);

$extent = split(' ',$input->getAttribute('mapext'));
$imagesize = array($input->getAttribute('width'), $input->getAttribute('height'));

$UniqueHandle = 'print_output_'.time();


# Takes in the XML document and writes the appropriate image to the disk
print "<html><body>";
print "<b>Available Printing Formats:</b><br/>";

# These can be used to diagnose function availability
#checkFunction('Render Image', 'renderImage');
#checkFunction('Render HTML', 'renderHTML');
#checkFunction('Render PDF', 'renderPDF');

# This gets used by both pure image output and the HTML output
$ImageHandle = $UniqueHandle.'.jpg';
$TempImage = $TEMP_DIRECTORY.$ImageHandle;
if(!function_exists('renderImage')) {
	appError('The "renderImage" function is undefined.  No other printing options will function without it!');
} else {
	# Basic Printing Option
	renderImage($document, $TempImage, $imagesize[0], $imagesize[1], $extent[0], $extent[1], $extent[2], $extent[3]);
	if($PRINT_SHOW_IMAGE_LINK) {
		print "<a target='_blank' href='".$TEMP_WEB.$ImageHandle."'>Open Printable Image in New Window</a>";
	}
}

if(function_exists('printHTML')) {
	$HTMLHandle = $UniqueHandle.'.html';
	printHTML($document, $TEMP_DIRECTORY.$HTMLHandle, $TEMP_WEB.$ImageHandle);
	print "<br/><br/><a target='_blank' href='".$TEMP_WEB.$HTMLHandle."'>Open Printable HTML Page in New Window</a>";
}

if(function_exists('printPDF')) {
	$PDFHandle = $UniqueHandle;
	printPDF($document, $TEMP_DIRECTORY.$PDFHandle);	
	print "<br/><br/><a target='_blank' href='".$TEMP_WEB.$PDFHandle.".pdf'>Open Printable PDF Page in New Window</a>";
}
print "</body></html>";



function checkFunction($title, $fname) {
	print $title.": ";
	if(function_exists($fname)) {
		print "ON";
	} else {
		print "OFF";
	}
	print "<br/>";
}



#
# Generates an image based on an XML post request and writes it to the
# the file specified in outputFileName
#
function renderImage($xml, $outputFileName, $width, $height, $minx, $miny, $maxx, $maxy, $quality=1) {
	global $TEMP_DIRECTORY;

	# This creates a temporary image for building and output.	
	$printImage = imagecreatetruecolor($width, $height);
	$colorWhite =  imagecolorallocate($printImage, 255, 255, 255);
	imagefill($printImage, 0, 0, $colorWhite);

	$maps = $xml->getElementsByTagName('map');

	$majorKeys = array();
	$majorKeys['WIDTH'] = $width;
	$majorKeys['HEIGHT'] = $height;
	$majorKeys['MINX'] = $minx;
	$majorKeys['MINY'] = $miny;
	$majorKeys['MAXX'] = $maxx;
	$majorKeys['MAXY'] = $maxy;

	for($i = $maps->length - 1; $i >= 0; $i--) {
		$map = $maps->item($i);
		# If it doesn't have a title, don't bother printing it
		if($map->hasAttribute('title')) {
			$file = $map->getElementsByTagName('file')->item(0)->nodeValue;

			# This accounts for the random different possible settings
			# Relative URL
			if(!(strpos($file, 'relative://') === false)) {
			# Absolute URL
			} elseif (!(strpos($file, 'http://') === false)) {
				$urlInfo = parse_url($file);
				if(!(strpos($urlInfo['query'], "WMS") === false)) {
					$params = array();
					$urlSplit = split('\?', $file);
					parse_str($urlSplit[1], $params);

					$mapfile = ms_newMapObj('resources/printWMS.map');
					$mapfile->selectOutputFormat("JPEG");
					$mapfile->web->set("imagepath", $TEMP_DIRECTORY);
					$mapfile->setSize($width,$height);
					$mapfile->setExtent($minx, $miny, $maxx, $maxy);

					$wmsLayer = $mapfile->getLayerByName('wms_temp');
					$wmsLayer->set("connection", $urlSplit[0].'?');
					$wmsLayer->setMetaData('wms_srs', $params['SRS']);
					$wmsLayer->setMetaData('wms_name', $params['LAYERS']);
					$wmsLayer->setMetaData('wms_server_version', $params['VERSION']);

					$image = $mapfile->prepareImage();
					$image = $mapfile->draw();
					$image->saveImage($outputFileName);

					$image = imagecreatefromjpeg($outputFileName);
					ImageCopyResized($printImage, $image, 0,0,0,0, $width, $height, ImageSX($image), ImageSY($image));
				} else {
					foreach($majorKeys as $key=>$value) {
						$file = str_replace('%'.$key.'%', $value, $file);
					}
					$ch = curl_init($file);
					$outfile = fopen($outputFileName, "w");
					curl_setopt($ch, CURLOPT_FILE, $outfile);
					curl_setopt($ch, CURLOPT_HEADER, 0);
					curl_exec($ch);
					fclose($outfile);
					$mimetype = curl_getinfo($ch,CURLINFO_CONTENT_TYPE);

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

					ImageCopyResized($printImage, $image, 0,0,0,0, $width, $height, ImageSX($image), ImageSY($image));
				}

			# This *should* be a reference to a mapfile
			} else {
				$mapfile = ms_newMapObj(getPath($file));
				$mapfile->setSize($width, $height);
				$mapfile->setExtent($minx, $miny, $maxx, $maxy);

				# G'head and figure out any of the "special" parameters
				$params = $map->getElementsByTagName('param');

				$drawQueryMap = false;
				$queryShape = false;
				foreach($params as $param) {
					$pName = $param->getAttribute('name'); 
					if($pName == 'mapshape') {
						# Create the shape and query the image.
						$points = rtrim($param->getAttribute('value'));
						$points = split(' ', $points);
						$shapeLine = ms_newLineObj();
						for($p = 0; $p < count($points); $p+=2) {
							$point = ms_newPointObj();
							$point->setXY($points[$p], $points[$p+1]);
							$shapeLine->add($point);
						}
						$shape = ms_newShapeObj(MS_SHAPE_POLYGON);
						$shape->add($shapeLine);
						$queryShape = $shape;
					}
					# These are the three mapserver directives for enabling layers
					if($pName == 'layer' or $pName == 'qlayer' or $pName == 'layers') {
						$layerNames = split(' ', $param->getAttribute('value'));
						# Occasionally "layers=" will be set to null
						# this checks to make sure that the value is an actual list.
						if(count($layerNames) > 0 and $layerNames[0] != "") {
							for($l = 0; $l < $mapfile->numlayers; $l++) {
								$layer = $mapfile->getLayer($l);
								$layerName = $layer->name;
								$layerOn = false;
								foreach($layerNames as $testName) {
									if($testName == $layerName or $layer->group == $layerName) {
										$layerOn = true;
									}
								}
								if($layerOn) {
									$layer->set("status", MS_DEFAULT);
								} else {
									$layer->set("status", MS_OFF);
								}
							}
						}
					}
				}

				if($quality > 1) {
					for($l = 0; $l < $mapfile->numlayers; $l++) {
						$layer = $mapfile->getLayer($l);
						for($c = 0; $c < $layer->numclasses; $c++) {
							$class = $layer->getClass($c);
							if($class->label->size > MS_GIANT) {
								$class->label->set("maxsize", $class->label->maxsize * $quality);
								$class->label->set("size", $class->label->size * $quality);
							} elseif($class->label->size > 0) {
								$class->label->set("size", $class->label->size + $quality);
							}

							for($s = 0; $s < $class->numstyles; $s++) {
								$style = $class->getStyle($s);
								if($style->size > 0) {
								#	$style->set("maxsize", $style->maxsize * $quality);
								#	$style->set("size", $style->size * $quality);
								}
							}
						}
					}
				}

				$image = $mapfile->prepareImage();
				# Draw the query map as required.
				if($queryShape) {
					$mapfile->queryByShape($queryShape);
					$image = $mapfile->drawQuery();
				} else {
					$image = $mapfile->draw();
				}
				$mimetype = $mapfile->outputformat->mimetype;
				$image->saveImage($outputFileName);
				if(!(strpos($mimetype,'png') === false)) {
					$image = imagecreatefrompng($outputFileName);
				} elseif(!(strpos($mimetype,'gif') === false)) {
					$image = imagecreatefromgif($outputFileName);
				} elseif (!(strpos($mimetype,'jpeg') === false)) {
					$image = imagecreatefromjpeg($outputFileName);
				} else {
					# Generate an error
				}
				$opacity = 100;
				if($map->hasAttribute('opacity')) {
					$opacity = $map->getAttribute('opacity');
				}
				imagecopymerge($printImage, $image, 0, 0, 0, 0, ImageSX($image), ImageSY($image), $opacity);
			}
		}
	}
	imagejpeg($printImage, $outputFileName);
}

?>
