Skip to content

Commit

Permalink
First commit
Browse files Browse the repository at this point in the history
  • Loading branch information
jbelien committed Jun 23, 2017
1 parent 2af6496 commit eb0e3ab
Show file tree
Hide file tree
Showing 8 changed files with 558 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules/
vendor/
composer.lock
config.yml
14 changes: 14 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "geo6/drawing-tool",
"description": "Draw an area and export it using ogr2ogr in several formats",
"type": "project",
"license": "GPL-3.0",
"authors": [
{
"name": "Jonathan Beliën"
}
],
"require": {
"symfony/yaml": "^3.2"
}
}
1 change: 1 addition & 0 deletions data/municipalities.json

Large diffs are not rendered by default.

163 changes: 163 additions & 0 deletions export.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
<?php
require __DIR__.'/vendor/autoload.php';
require 'fn.php';

use Symfony\Component\Yaml\Yaml;

$config = Yaml::parse(file_get_contents(__DIR__.'/config.yml'));

if (isset($_GET['id'])) {
if (file_exists(sys_get_temp_dir().'/drawing-tool/'.$_GET['id']) && is_dir(sys_get_temp_dir().'/drawing-tool/'.$_GET['id'])) {
$glob = glob(sys_get_temp_dir().'/drawing-tool/'.$_GET['id'].'/*.zip');
if (count($glob) === 1) {
$file = $glob[0];

if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); }

header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime($file)).' GMT');
header('Cache-Control: private', FALSE);
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($file));
header('Connection: close');
readfile($file); // push it out
exit();
} else {
header("HTTP/1.1 404 Not Found");
exit();
}
} else {
header("HTTP/1.1 404 Not Found");
exit();
}
}
else if (isset($_POST['json'])) {
header('Content-type: application/json');

try {
$json = json_decode($_POST['json']);
if (is_null($json)) {
throw new ErrorException(json_last_error_msg());
}
} catch (ErrorException $e) {
echo json_encode($e);
exit();
}

$warnings = array();
$temp = sys_get_temp_dir();
$id = uniqid();
$time = date('YmdHis');

$dir = $temp.'/drawing-tool';
if (!file_exists($dir) || !is_dir($dir)) { mkdir($dir); }

$dir .= '/'.$id;
if (!file_exists($dir) || !is_dir($dir)) { mkdir($dir); }

if (!file_exists($dir.'/GeoJSON') || !is_dir($dir.'/GeoJSON')) { mkdir($dir.'/GeoJSON'); }
file_put_contents($dir.'/GeoJSON/'.$time.'WGS84.json', json_encode($json));

$source = $dir.'/GeoJSON/'.$time.'WGS84.json';
$valid = TRUE;
$validGeometry = array();

try {
$pg = pg_connect('host='.$config['postgresql']['host'].' port='.$config['postgresql']['port'].' dbname='.$config['postgresql']['dbname'].' user='.$config['postgresql']['user'].' password='.$config['postgresql']['password']);

foreach ($json->features as $i => $feature) {
$q = pg_query_params($pg, "SELECT ST_IsValid(ST_GeomFromGeoJSON($1))", array(
json_encode($feature->geometry)
));
$r = pg_fetch_result($q, 0, 0);
pg_free_result($q);
if ($r === 'f') {
$valid = FALSE;
$q = pg_query_params("SELECT ST_AsGeoJSON(ST_MakeValid(ST_GeomFromGeoJSON($1)), 6)", array(
json_encode($feature->geometry)
));
$geom = pg_fetch_result($q, 0, 0);
pg_free_result($q);

$feature->geometry = json_decode($geom);
}

$validGeometry[$i] = $feature->geometry;
}

if ($valid === FALSE) {
file_put_contents($source, json_encode($json));
}

pg_close($pg);
} catch (ErrorException $e) {
echo json_encode($e);
exit();
}

foreach ($config['formats'] as $format) {
$params = (isset($format['params']) ? $format['params'] : array());

if (isset($format['srs'])) {
foreach ($format['srs'] as $srs) {
if ($srs === 'EPSG:31370') {
$fname = $time.'Lambert72';
} else if ($srs === 'EPSG:4326') {
$fname = $time.'WGS84';
} else {
$fname = $time;
}
export($source, $dir.'/'.$format['code'].'/'.$fname, $format['code'], $srs, $params);
}
} else {
$fname = $time.'WGS84';
export($source, $dir.'/'.$format['code'].'/'.$fname, $format['code'], 'EPSG:4326', $params);
}
}

try {
$zip = new ZipArchive;
$zipOpen = $zip->open($dir.'/'.$time.'.zip', ZipArchive::CREATE);
if ($zipOpen !== TRUE) {
switch ($zipOpen) {
case ZipArchive::ER_EXISTS:
throw new ErrorException('File already exists.');
break;
/*
Add missing error codes
*/
default:
throw new ErrorException('Unknown error.');
break;
}
}

$glob = glob($dir.'/*/*.*');
foreach ($glob as $g) {
$zip->addFile($g, basename(dirname($g)).'/'.basename($g));
}

$zip->close();

$result = array(
'id' => $id,
'filename' => $time.'.zip'
);

if ($valid === FALSE) {
$result['validGeometry'] = $validGeometry;
}

echo json_encode($result);
} catch (ErrorException $e) {
echo json_encode($e);
exit();
}
}
exit();
83 changes: 83 additions & 0 deletions fn.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php
/**
*
*/
function ogr2ogr($format, $dst, $src, $params = NULL, &$stdout = NULL, &$stderr = NULL) {
if (is_array($src)) {
$source = escapeshellarg($src[0]);
$source .= ' ';
$layers = explode(' ', $src[1]); foreach ($layers as $l) $source .= escapeshellarg($l);
} else {
$source = escapeshellarg($src);
}

$descriptorspec = array(
0 => array('pipe', 'r'), // stdin
1 => array('pipe', 'w'), // stdout
2 => array('pipe', 'w') // stderr
);

$process = proc_open('ogr2ogr -f '.escapeshellarg($format).' '.$params.' '.escapeshellarg($dst).' '.$source, $descriptorspec, $pipes);

if (is_resource($process)) {
$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);

$stderr = stream_get_contents($pipes[2]) ;
fclose($pipes[2]);

$return_value = proc_close($process);
} else {
return FALSE;
}

return ($return_value === 0);
}

/**
*
*/
function export($source, $file, $format, $srs = 'EPSG:4326', $params = array()) {
global $warnings;

$dir = dirname($file);
$fname = basename($file);

switch ($format) {
case "ESRI Shapefile":
$file .= ".shp";
break;
case "GML":
$file .= ".gml";
break;
case "KML":
$file .= ".kml";
break;
case "MapInfo File":
if (isset($params['dsco']) && in_array('FORMAT=MIF', $params['dsco'])) {
$file .= ".mif";
} else {
$file .= ".tab";
}
break;
default:
break;
}

try {
if (!file_exists($dir) || !is_dir($dir)) { mkdir($dir, 0777, TRUE); }

$params = '';
if ($srs !== 'EPSG:4326') {
$params .= ' -s_srs EPSG:4326';
$params .= ' -t_srs '.$srs;
}

$ogr = ogr2ogr($format, $file, $source, $params, $stdout, $stderr);
if ($ogr === FALSE) {
throw new Exception($stderr);
}
} catch (Exception $e) {
$warnings[] = $e->getMessage();
}
}
Loading

0 comments on commit eb0e3ab

Please sign in to comment.