<?php
#
# draw.php (c) 2007-2008 Dan "Ducky" Little
# Write for the GeoMOOSE project, sponsored by the OpenMNND Organization
# PHP Translation of the Perl script draw.pl
# Updated 2/2008 With new Features:
# 1) Make it actually work.
# 2) Add line width and color specification
#

# Make PHP Shut up a little bit
error_reporting(E_ERROR | E_PARSE);

include('Configuration.php');		# Pull in the global configuration
include('geomoose_php_util.php');


# 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($DRAWING_MAP)) {
	appError('Could not find: '.$DRAWING_MAP);
}

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($TEMP_DIRECTORY.'/'.$id, $shapeFileType);
if(!isset($shapefile)) { appError("Cannot Open Shapefile! ".$TEMP_DIRECTORY."/".$id.".shp\n"); }
$shapefile->addShape($shape);

# Store some useful information in a Shapefile
#$dbh = DBI->connect("DBI:XBase:$TEMP_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),
	array("class", "C", 3)
);

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

$dbase = dbase_open($TEMP_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>$DRAWING_MAP</file>";
	print "	<param name='ID' value='$id'/>";
	print "</map>";
	print "</return>";
}

?>
