<?php
#
# draw.php (c) 2007 Dan "Ducky" Little
# Write for the GeoMOOSE project, sponsored by the OpenMNND Organization
# PHP Translation of the Perl script draw.pl
#
dl('php_mapscript.'.PHP_SHLIB_SUFFIX); # LOAD THE MAPSCRIPT!
dl('php_dbase.'.PHP_SHLIB_SUFFIX);	# LOAD THE DBASE TOOLS

# GLOBAL CONFIGURATION VARIABLES
$drawingMapFile = '/ms4w/apps/GeoMOOSE/maps/internal/draw.map';
$directory = '/ms4w/tmp/ms_tmp';

# Get in the information from the request
$coordinates = $_REQUEST['coords'];
$title = $_REQUEST['title'];
$shapeType = $_REQUEST['shape'];
$buffer = $_REQUEST['buffer'];
$layer = $_REQUEST['layer'];
$output = $_REQUEST['output'];
# Unique Id, the Process Number combined with the UNIX time.
$id = getmypid().time();


# This checks for the existance of the select mapfile.
# If it does not exist the application quits with an error message.
if(!file_exists($drawingMapFile)) {
	appError('Could not find: '.$drawingMapFile);
}

if(!isset($coordinates)) {
	appError('Coordinates not set! ('.$coordinates.')');
}

if(!isset($output)) {
	$output = 'xml';
}

# This checks to see what "shape" is being passed to the script to query against.
$shapeFileType = MS_SHP_POLYGON;
if($shapeType == "point") {
	$shapeType = MS_SHAPE_POINT;
	$shapeFileType = MS_SHP_POINT;
} elseif($shapeType == 'circle') {
} elseif($shapeType == 'line') {
	$shapeType = MS_SHAPE_LINE;
	if(empty($buffer)) {
		$buffer = 1;	# Makes the line work if there is no buffer specified or the buffer = 0
	}
} else {
	$shapeType = MS_SHAPE_POLYGON;
}

# Convert the coordinates to a new shape object
# This takes the coordinates from the CGI and adds them to a Shape for querying.
$shape = ms_newShapeObj($shapeType);
$coords = array();
$coords = explode(' ', $coordinates);
$line = ms_newLineObj();
foreach ($coords as $coord) {
	list($x, $y) = explode(',',$coord);
	$line->addXY($x,$y);
}
$shape->add($line);	# This adds the line with all the coordinates from the CGI
#$shape->setBounds();	# This initalizes the shape.

# Buffer as desired.
if(isset($buffer)) {
	$shape = $shape->buffer($buffer);	# Mapscript using GEOS to bufffer the shape
	if(!isset($shape)) { 			# Check to make sure the function returned a valid shape, if not, error.
		appError("Buffering Failed. Buffer size: $buffer. Verify mapscript was linked with GEOS and that the buffer is a positive-real number.");
	}
}

# Create a new Coordinate string based on any potential buffering.
# This is needed because after the object has been buffered it will have a new coordinate string.
# This information is passed back to the GeoMOOSE client so that it can set the "mapshape" parameter
# which displays the layer highlighting.
$coordString = '';
for($line = 0; $line < $shape->{numlines}; $line++) {
	$lineObj = $shape->line($line);
	for($point = 0; $point < $lineObj->{numpoints}; $point++) {
		$pointObj = $lineObj->point($point);
		$coordString = $coordString.$pointObj->{x}.' '.$pointObj->{y}.' ';
	}
}


# Write out a shapefile
$shapefile = ms_newShapefileObj($directory.'/'.$id, $shapeFileType);
if(!isset($shapefile)) { appError("Cannot Open Shapefile! ".$directory."/".$id.".shp\n"); }
$shapefile->addShape($shape);

# Store some useful information in a Shapefile
#$dbh = DBI->connect("DBI:XBase:$directory");
#$dbh->do("create table $id (title char(64), id char(64),area float, perimeter float)");
#$dbh->do("insert into $id values ('$title', '$id', $area, $perimeter)");

$dbFields = array(
	array("title",     "C", 64),
	array("id",     "C",  64),
	array("area",      "N",   64, 3),
	array("perimeter",    "N", 64, 3),
);

if(!dbase_create($directory.'/'.$id.'.dbf', $dbFields)) {
	appError('Could not create database');
}

$dbase = dbase_open($directory.'/'.$id.'.dbf', 2);
if(!$dbase) {
	appError('Could not open dbase file!');
}
dbase_add_record($dbase, array($title, $id, $area, $perimeter));
dbase_close($dbase);

# Give the client the ID back so it can reference it later
if($output == 'text') {
#print "Content-type: text/plain\n\n";
	header('Content-type: text/plain');
	print $id;
} elseif($output == 'xml') {
	header('Content-type: text/xml');
	print "<return>";
	print "<selection title='$title' id='$id'/>";
	print "<map title='$title' default='true' opacity='50'>";
	print "	<file>$drawingMapFile</file>";
	print "	<param name='ID' value='$id'/>";
	print "</map>";
	print "</return>";
}

function appError($msg) {
	print "<html>";
	print "<head><title>GeoMOOSE Drawing Error</title></head>";
	print "<body>";
	print "<h3>Selection Service Message</h3>";
	print "<b style='color:red'>".$msg."</b>";
	print "</body>";
	print "</html>";
	exit(0);
}

?>