<?php

# These are some global configuration details.
$MAPBOOK = '../rock.xml';
$SELECT_MAPFILE = '/ms4w/apps/GeoMOOSE/rock/maps_rock/select.map';

# 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);

# Include the PDF printing utility
include('pdfprint2.php');


$layers = $_REQUEST['layers'];		# Comma Separated List of Mapbook Layers
$extent = $_REQUEST['extent'];		# Space Separated Coordinate List
$title = $_REQUEST['title'];		# Title for the report
$buffer = $_REQUEST['buffer'];		# Amount to buffer around the selected feature

if(!isset($buffer)) { $buffer = 0; }

$query_layer = $_REQUEST['qlayer'];
$query_item = $_REQUEST['qitem'];
$query_string = $_REQUEST['qstring'];


# Parse the XML String into the DOM
$mapbook= new DOMDocument();
$mapbook->loadXML(file_get_contents($MAPBOOK));

$printBook = new DOMDocument();

$canvas = $printBook->createElement('canvas');
$printBook->appendChild($canvas);

$layersElm = $printBook->createElement('layers');
$canvas->appendChild($layersElm);

$titleParam = $printBook->createElement('param');
$titleParam->setAttribute('name', 'title');
$titleParam->setAttribute('value', $title);
$canvas->appendChild($titleParam);

# Setup the selection layer
$highlightLayer = $printBook->createElement('map');
$highlightLayer->setAttribute('title','Highlight');
# Setup the parameters for the layer
$highlightFile = $printBook->createElement('file');
$highlightFile->appendChild($printBook->createTextNode($SELECT_MAPFILE));
$highlightLayer->appendChild($highlightFile);
$highlightAttributes = array('qitem' => $query_item, 'qstring' => $query_string, 'qlayer' => $query_layer);
foreach($highlightAttributes as $n => $v) {
	$param = $printBook->createElement('param');
	$param->setAttribute('name', $n);
	$param->setAttribute('value', $v);
	$highlightLayer->appendChild($param);
}
$layersElm->appendChild($highlightLayer);

#
# Get the extent of the object
#
$selectfile = ms_newMapObj($SELECT_MAPFILE);
$selectlayer = $selectfile->getLayerByName($query_layer);

#error_reporting(E_PARSE);
$results = $selectlayer->queryByAttributes($query_item, $query_string, MS_SINGLE);
$numResults = $selectlayer->getNumResults();
$bounds = false;
if ($numResults == 1) {
	$selectlayer->open();
	for ($iRes=0; $iRes < $numResults; $iRes++)	{
		$oRes = $selectlayer->getResult($iRes);
		$oShape = $selectlayer->getShape($oRes->tileindex,$oRes->shapeindex);
		$bounds = $oShape->bounds;
		$oShape->free();
	}
	$selectlayer->close();
}

if($bounds != false && !(isset($extent))) {
	$bounds->minx = $bounds->minx - $buffer;
	$bounds->miny = $bounds->miny - $buffer;
	$bounds->maxx = $bounds->maxx + $buffer;
	$bounds->maxy = $bounds->maxy + $buffer;
	$extent = $bounds->minx.' '.$bounds->miny.' '.$bounds->maxx.' '.$bounds->maxy;
}


$layerTitles = explode(',',$layers);
for($l = 0; $l < count($layerTitles); $l++) {
	$xmlLayer = getMapLayer($mapbook, $layerTitles[$l]);
	$layersElm->appendChild($printBook->importNode($xmlLayer, true));
}

# Setup the Extent
$input = $printBook->createElement('input');
$input->setAttribute('mapext', $extent);

$canvas->appendChild($input);

$parcelsElm = $printBook->createElement('parcels');
$parcelsElm->appendChild($printBook->createTextNode($query_string));
$input->appendChild($parcelsElm);

#print $printBook->saveXML();

$UniqueHandle = 'print_output_'.time();
$PDFHandle = $UniqueHandle;
printPDF($printBook, $TEMP_DIRECTORY.$PDFHandle, $SELECT_MAPBOOK, $query_layer, $query_item);

#print "<br/><br/><a target='_blank' href='".$TEMP_WEB.$PDFHandle.".pdf'>Open Printable PDF Page in New Window</a>";
header('Content-type: application/pdf');
print file_get_contents($TEMP_DIRECTORY.$PDFHandle.'.pdf');

function getMapLayer($xml, $title) {
	$mapLayers = $xml->getElementsByTagName('map');
	for($m = 0; $m < $mapLayers->length; $m++) {
		if($mapLayers->item($m)->getAttribute('title') == $title) {
			return $mapLayers->item($m);
		}
	}
	return false;
}

#
# This function is stolen form print.php, renderImage should probably be moved to
# a general purposes library.  This is needed for pdfprint2.php.
#
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 {
#				print getPath($file)."<br/>";
				$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;
				$itemQueryName = false;
				$itemQueryValue = false;
				$itemQueryLayer = 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($pName == 'qitem') {
						$itemQueryName = $param->getAttribute('value');
					}
					if($pName == 'qstring') {
						$itemQueryValue = $param->getAttribute('value');
					}
					if($pName == 'qlayer') {
						$itemQueryLayer = $param->getAttribute('value');
					}

				}

				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 if($itemQueryName && $itemQueryValue && $itemQueryLayer) {
					$layer = $mapfile->getLayerByName($itemQueryLayer);
					$layer->queryByAttributes($itemQueryName, $itemQueryValue, MS_SINGLE);
					$layer->open();
					$layer->close();
					$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);
}

?>