<?
/*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.*/

#
# GeoMOOSE 2 PHP Editing Capabilities
# This requires a PostGIS database.
#

include('config.php');

# Get the operation.
$operation = $_REQUEST['op'];
$layer = $_REQUEST['layer'];
$cgiTable = $_REQUEST['table'];

# Load the appropriate configuration file.
# TOOD: ADD PATH CHECKING TO THE $cgiTable VARIABLE TO PREVENT PATH REDIRECTION!!!
$config = parse_ini_file('../../conf/editor/'.$cgiTable.'.ini');

# Now load the table information from that INI file...
$tableName = $config['tablename'];
$geometryColumn = $config['geometry_column'];
$primaryKeyColumn = $config['primary_key_column'];
$primaryKeySequence = $config['primary_key_sequence'];
$dbName = $config['dbname'];
$host = $config['host'];
$username = $config['username'];
$password = $config['password'];
$layerName = $config['layerpath'];

# Get the required fields, turn them into lists
# then turn them into a hash table so that we can recall them
# more efficently later.
$requiredForCreateList = explode(',', $config['required_for_create']);
$requiredForUpdateList = explode(',', $config['required_for_update']);

$requiredForCreate = array();
$requiredForUpdate = array();
foreach($requiredForUpdateList as $req) {
	$requiredForUpdate[$req] = false;
}
foreach($requiredForCreateList as $req) {
	$requiredForCreate[$req] = false;
}


# Connect to the database
$connectString = sprintf('host=%s dbname=%s user=%s password=%s', $host, $dbName, $username, $password);
$connection = pg_connect($connectString);

# Make an array of the feature information.
$feature_info = array();
foreach($_REQUEST as $k=>$v)  {
	$key_arr = explode(':', $k);
	if($key_arr[0] == 'feature') {
		$attr = $key_arr[1];
		if($operation != 'create' || $key_arr[1] != $primaryKeyColumn) {
			$feature_info[$attr] = $v;
		}
		if($v != null && $v != '') {
			$requiredForUpdate[$attr] = true;
			$requiredForCreate[$attr] = true;
		}
	}
}

$sql = '';
if($operation == 'create') {
	# Check for required fields
	foreach($requiredForCreate as $k=>$v) {
		if(!$v) {
			print "Missing required field: $k";
			die;
		}
	}
	$columnNames = implode(',', array_keys($feature_info));

	$columnValues = array();
	$value_arr = array();
	$paramCount = 1;

	# Add an id
	# Get an ID value for the new item.
	$pk_sql = sprintf("select nextval('%s') as new_id", $primaryKeySequence);
	$result = pg_query($pk_sql);
	$line = pg_fetch_array($result, null, PGSQL_ASSOC);
	$newId = $line['new_id'];
	
	# Add a primary key to the insert statement
	$columnNames = $primaryKeyColumn.','.$columnNames;
	array_push($columnValues, $newId);
	foreach($feature_info as $k=>$v) {
		if($k == $geometryColumn) {
			array_push($columnValues, "geomfromtext($".$paramCount.")");
		} else {
			array_push($columnValues, "$".$paramCount);
		}

		array_push($value_arr, $v);
		$paramCount++;
	}


	# Prepare the statement
	$sql = 'insert into %s (%s) values (%s)';
	$columnValues = implode(',', $columnValues);
	pg_prepare($connection, 'insert_sql', sprintf($sql, $tableName, $columnNames, $columnValues));
	$result = pg_execute($connection, 'insert_sql', $value_arr);
	$message = sprintf("Feature Inserted (Created ID: %d).<br/>", $newId);
} else if($operation == 'update') {
	# Check for required fields
	foreach($requiredForUpdate as $k=>$v) {
		if(!$v) {
			print "Missing required field: $k";
			die;
		}
	}

	# Die if there is no ID available for doing an update.
	$id = (int)$feature_info[$primaryKeyColumn];
	print $id < 1;
	if($feature_info[$primaryKeyColumn] < 1) {
		print 'No Feature ID available for update.';
		die;
	}
	$paramCount = 1;
	$bindValues = array();
	$updateParts = array();
	foreach($feature_info as $k=>$v) {
		if($k == $geometryColumn) {
			array_push($updateParts, $k." = geomfromtext($".$paramCount.")");
			array_push($bindValues, $v);
			$paramCount++;
		} else if($k != $primaryKeyColumn) {
			array_push($updateParts, $k." = $".$paramCount);
			array_push($bindValues, $v);
			$paramCount++;
		}
	}
	array_push($bindValues, $feature_info[$primaryKeyColumn]);
	$sql = sprintf('update %s set %s where %s = $%d', $tableName, implode(',',$updateParts), $primaryKeyColumn, $paramCount);
	pg_prepare($connection, 'update_sql', sprintf($sql, $tableName));
	$result = pg_execute($connection, 'update_sql', $bindValues);
	$message = sprintf('Feature Updated (%s=%d)', $primaryKeyColumn, $feature_info[$primaryKeyColumn]);
} else if($operation == 'delete') {
	# Die if there is no ID available for deleting.
	if($feature_info[$primaryKeyColumn] < 1) {
		print 'No Feature ID specified to delete.<br/>';
		die;
	}
	$sql = 'delete from %s where %s = $1';

	# Prepare the ole delete statement
	pg_prepare($connection, 'delete_sql', sprintf($sql, $tableName, $primaryKeyColumn));
	$result = pg_execute($connection, 'delete_sql', array($feature_info[$primaryKeyColumn]));
	$message = sprintf("Feature Removed (%s=%d)", $primaryKeyColumn, $feature_info[$primaryKeyColumn]);
} else {
	printf("Unknown operation: %s", $operation);
	die;
}

header('Content-type: text/xml');
print "<results>";
print "<script><![CDATA[";
printf(" GeoMOOSE.turnLayerOn('%s');\n", $layerName);
printf(" GeoMOOSE.refreshLayers('%s');\n", $layerName); 
print "]]></script>";
# Print a little header information
print "<html><![CDATA[";
print "<h3>GeoMOOSE Feature Editor</h3>";
print "<hr/>";
print $message;
print "<br/><br/>";
print "<center>";
print "<a href='javascript:GeoMOOSE.changeTab(CONFIGURATION.catalog_name);'>Back to Layers List</a>";
print "</center>";
print "]]></html>";
print "</results>";
pg_close($connection);

?>
