From 296a752e289a4615450b7e80d45dfc137b23a0a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Jan=C3=A1k?= Date: Fri, 11 Apr 2014 10:51:19 +0200 Subject: [PATCH 01/21] Cleaning of the PHP - router, object code, same functionality Fixes #14 Fixes #17 Fixes #19 --- .htaccess | 77 +- tileserver-mbtiles.php | 123 --- tileserver-tms.php | 85 -- tileserver-wmts.php | 472 ----------- tileserver.php | 1707 +++++++++++++++++++++++++++++++--------- 5 files changed, 1339 insertions(+), 1125 deletions(-) delete mode 100644 tileserver-mbtiles.php delete mode 100644 tileserver-tms.php delete mode 100644 tileserver-wmts.php diff --git a/.htaccess b/.htaccess index 5dac278..6c408e4 100644 --- a/.htaccess +++ b/.htaccess @@ -12,8 +12,12 @@ Options -MultiViews # Mapping of the WMTS standardized URLs to real files and XML capabilities to tileserver.php -RewriteEngine On +#check htaccess functionality +SetEnv HTACCESS on +DirectoryIndex tileserver.php +RewriteEngine on + # WMTS RESTful # ------------ # The file can be accessed directly: @@ -32,68 +36,11 @@ RewriteRule ^([\w\d\._-]+)/.+?(\d+)/(\d+)/(\d+)\.(\w+)$ $1/$2/$3/$4.$5 [L] # rewrite .jpeg -> .jpg RewriteRule ^(.+).jpeg$ $1.jpg [L] -# MBTiles support at /layer/z/x/y.ext - loads the tile from mbtiles with php -# TODO: serve also 404 errors for tiles -RewriteRule ^([^\/]+\.mbtiles)\/.*?(\d+)\/(\d+)\/(\d+)\.(\w+)$ tileserver-mbtiles.php?tileset=$1&z=$2&x=$3&y=$4&ext=$5 [L] -RewriteRule ^([^\/]+\.mbtiles)\/.*?(\d+)\/(\d+)\/(\d+)\.grid.json?$ tileserver-mbtiles.php?tileset=$1&z=$2&x=$3&y=$4&ext=grid [QSA,L] -# TODO: use mod_sqlite if available to map the tiles to URL directly by apache +# Not modified HTTP 302 +RewriteRule .* - [E=HTTP_IF_MODIFIED_SINCE:%{HTTP:If-Modified-Since}] +RewriteRule .* - [E=HTTP_IF_NONE_MATCH:%{HTTP:If-None-Match}] -# WMTS KVP -# -------- -# map the /?key=value&... -> /layer/z/x/y.ext KVP getTile queries directly to files - -# format passed as mime-extension, cleaning formats (jpeg->jpg) -RewriteCond %{QUERY_STRING} ^(.*)format=image/jpeg(.*)$ [NC] -RewriteRule ^(.*)$ $1?%1format=jpg%2 [N] -RewriteCond %{QUERY_STRING} ^(.*)format=jpeg(.*)$ [NC] -RewriteRule ^(.*)$ $1?%1format=jpg%2 [N] -RewriteCond %{QUERY_STRING} ^(.*)format=image/png(.*)$ [NC] -RewriteRule ^(.*)$ $1?%1format=png%2 [N] - -# variable order of keys: TODO: sort the same way as mime-extension to fixed order -RewriteCond %{QUERY_STRING} ^.*request=gettile.*layer=([\w\d\._-]+).*tilematrix=(\d+).*tilerow=(\d+).*tilecol=(\d+).*format=(\w+).*$ [NC] -RewriteRule ^ %1/%2/%3/%4.%5 [L] -RewriteCond %{QUERY_STRING} ^.*request=gettile.*layer=([\w\d\._-]+).*format=(\w+).*tilematrix=(\d+).*tilerow=(\d+).*tilecol=(\d+).*$ [NC] -RewriteRule ^ %1/%3/%5/%4.%2 [L] -RewriteCond %{QUERY_STRING} ^.*request=gettile.*layer=([\w\d\._-]+).*tilematrix=(\d+).*tilecol=(\d+).*tilerow=(\d+).*format=(\w+).*$ [NC] -RewriteRule ^ %1/%2/%4/%3.%5 [L] -# Example: http://www.tileserver.com/wmts?request=getTile&layer=grandcanyon&tileMatrix=10&tilerow=192&tilecol=401&format=png -# Example: http://www.tileserver.com/wmts?service=WMTS&request=GetTile&version=1.0.0&layer=ne2geo&style=&format=image/jpeg&TileMatrixSet=WGS84&TileMatrix=1&TileRow=2&TileCol=2 - -# WMTS ServiceMetadata (GetCapabilities) -# -------------------------------------- -RewriteRule ^.*WMTSCapabilities.xml$ tileserver-wmts.php [QSA,L] -RewriteRule ^wmts$ tileserver-wmts.php [QSA,L] -RewriteCond %{QUERY_STRING} ^.*request=getcapabilities.*$ [NC] -RewriteRule ^ tileserver-wmts.php [L] -# Example: http://www.tileserver.com/dev/?service=WMTS&version=1.0.0&request=GetCapabilities - -# TMS XML (ArcBruTile) -# -------------------- -RewriteRule ^tms$ tileserver-tms.php [QSA,L] -RewriteRule ^(.+)/tms$ tileserver-tms.php?layer=$1 [QSA,L] -# Example: http://www.tileserver.com/dev/?service=WMTS&version=1.0.0&request=GetCapabilities - -# request for non-existent tiles -> layer/none.png or none.png -#RewriteCond %{REQUEST_FILENAME} !-f -#RewriteRule ^([\w\d\._-]+)/(\d+)/(\d+)/(\d+)\.png$ $1/none.png [L] -#RewriteCond %{REQUEST_FILENAME} !-f -#RewriteRule ^([\w\d\._-]+)/none\.png$ none.png [L] - -# request for non-existent tiles -> layer/none.jpg or none.jpg -#RewriteCond %{REQUEST_FILENAME} !-f -#RewriteRule ^([\w\d\._-]+)/(\d+)/(\d+)/(\d+)\.jpg$ $1/none.jpg [L] -#RewriteCond %{REQUEST_FILENAME} !-f -#RewriteRule ^([\w\d\._-]+)/none\.jpg$ none.jpg [L] - -# TileJSON JSONP wrapper for MapBOX.js API -RewriteRule ^maps.jsonp?$ tileserver.php?service=json [QSA,L] -RewriteCond %{REQUEST_URI} !\.grid\.json [NC] -RewriteRule ^(.+).jsonp?$ tileserver.php?service=json&layer=$1 [QSA,L] - -# If-Modified-Since (if php is not installed as cgi then comment lines below) -#RewriteRule .* - [E=HTTP_IF_MODIFIED_SINCE:%{HTTP:If-Modified-Since}] -#RewriteRule .* - [E=HTTP_IF_NONE_MATCH:%{HTTP:If-None-Match}] - -# handle all request on the root '/' by tileserver.php -RewriteRule ^$ tileserver.php?service=html [QSA,L] \ No newline at end of file +RewriteCond %{REQUEST_FILENAME} !-f +RewriteCond %{REQUEST_FILENAME} !-d +RewriteCond $1 !^(tileserver\.php) +RewriteRule ^(.*)$ tileserver.php/$1 [L] \ No newline at end of file diff --git a/tileserver-mbtiles.php b/tileserver-mbtiles.php deleted file mode 100644 index 9a1d4d9..0000000 --- a/tileserver-mbtiles.php +++ /dev/null @@ -1,123 +0,0 @@ -404 Not Found"; - echo "TileServer.php could not found what you requested."; - die(); - // TODO: if ($_GET['ext'] == 'png') { ... - // TODO: better image 256x256px !!! - // header("Content-type: image/png"); -//print("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\rIDAT\x08\xd7c````\x00\x00\x00\x05\x00\x01^\xf3*:\x00\x00\x00\x00IEND\xaeB`\x82"); -} -$tileset = $_GET['tileset']; - -if (isset($_GET['tileset'])) { - - $tileset = $_GET['tileset']; - $flip = true; - try { - $db = new PDO('sqlite:' . $tileset, '', '', array(PDO::ATTR_PERSISTENT => true)); - if (!isset($db)) { - header('Content-type: text/plain'); - print 'Incorrect tileset name: ' . $_GET['tileset']; - exit; - } - // http://c.tile.openstreetmap.org/12/2392/1190.png - $z = floatval($_GET['z']); - $y = floatval($_GET['y']); - $x = floatval($_GET['x']); - if ($flip) { - $y = pow(2, $z) - 1 - $y; - } - if ($_GET['ext'] != 'grid' && $_GET['ext'] != 'json') { - - - $result = $db->query('select tile_data as t from tiles where zoom_level=' . $z . ' and tile_column=' . $x . ' and tile_row=' . $y); - $data = $result->fetchColumn(); - if (!isset($data) || $data === FALSE) { - // TODO: Put here ready to use empty tile!!! - $png = imagecreatetruecolor(256, 256); - imagesavealpha($png, true); - $trans_colour = imagecolorallocatealpha($png, 0, 0, 0, 127); - imagefill($png, 0, 0, $trans_colour); - header('Content-type: image/png'); - imagepng($png); - //header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found'); - } else { - $result = $db->query('select value from metadata where name="format"'); - $resultdata = $result->fetchColumn(); - $format = isset($resultdata) && $resultdata !== FALSE ? $resultdata : 'png'; - if ($format == 'jpg') - $format = 'jpeg'; - header('Content-type: image/' . $format); - print $data; - } - } elseif ($_GET['ext'] == 'grid' || $_GET['ext'] == 'json') { - //Get and return UTFgrid - $result = $db->query('SELECT grid FROM grids WHERE tile_column = ' . $x . ' AND tile_row = ' . $y . ' AND zoom_level = ' . $z); - $data = $result->fetchColumn(); - - if (!isset($data) || $data === FALSE) { - // if not exists grid data return empty json - header('Access-Control-Allow-Origin: *'); - echo 'grid({});'; - die; - } else { - $grid = gzuncompress($data); - $grid = substr(trim($grid), 0, -1); - - //adds legend (data) to output - $grid .= ',"data":{'; - $result = $db->query('SELECT key_name as key, key_json as json FROM grid_data WHERE zoom_level=' . $z . ' and tile_column=' . $x . ' and tile_row=' . $y); - while ($r = $result->fetch(PDO::FETCH_ASSOC)) { - $grid .= '"' . $r['key'] . '":' . $r['json'] . ','; - } - $grid = rtrim($grid, ',') . '}}'; - - // CORS headers - header('Access-Control-Allow-Origin: *'); - - if (isset($_GET['callback'])) { - header("Content-Type:text/javascript charset=utf-8"); - echo $_GET['callback'] . '(' . $grid . ');'; - } else { - header("Content-Type:text/javascript; charset=utf-8"); - echo 'grid(' . $grid . ');'; - } - } - } - } catch (PDOException $e) { - header('Content-type: text/plain'); - print 'Error querying the database: ' . $e->getMessage(); - } -} -/* - function getbaseurl() { - return 'http://'.$_SERVER['HTTP_HOST'].preg_replace('/\/(1.0.0\/)?[^\/]*$/','/',$_SERVER['REQUEST_URI']); - } - */ - -function readparams($db) { - $params = array(); - $result = $db->query('select name, value from metadata'); - while ($row = $result->fetch(PDO::FETCH_ASSOC)) { - $params[$row['name']] = $row['value']; - } - return $params; -} - -function readzooms($db) { - $zooms = array(); - $result = $db->query('select zoom_level from tiles group by zoom_level order by zoom_level'); - while ($zoom = $result->fetchColumn()) { - $zooms[] = $zoom; - } - return $zooms; -} - -?> diff --git a/tileserver-tms.php b/tileserver-tms.php deleted file mode 100644 index cc5ea05..0000000 --- a/tileserver-tms.php +++ /dev/null @@ -1,85 +0,0 @@ -\n"; - -// Accepted GET strings -$layer = (array_key_exists('layer', $_GET)) ? $_GET['layer'] : ""; - -# ----------- -# TMS SERVICE -# ----------- -if ($layer === ""): - - $maps = maps(); -?> - - -\n"; - } - ?> - - -LatLonToMeters($bounds[1], $bounds[0]); - list( $maxx, $maxy ) = $mercator->LatLonToMeters($bounds[3], $bounds[2]); - $bounds = array( $minx, $miny, $maxx, $maxy ); - $initialResolution = 156543.03392804062; - } - $format = $m['format']; - $mime = ($format == 'jpg') ? 'image/jpeg' : 'image/png'; -?> - - <?php echo htmlspecialchars($title) ?> - - - - - - - - - - - - diff --git a/tileserver-wmts.php b/tileserver-wmts.php deleted file mode 100644 index 4a8125f..0000000 --- a/tileserver-wmts.php +++ /dev/null @@ -1,472 +0,0 @@ -\n"; ?> - - - - - OGC WMTS - 1.0.0 - - - - - - - - - - RESTful - - - - - - - - KVP - - - - - - - - - - - - - RESTful - - - - - - - KVP - - - - - - - - - - -LatLonToMeters($bounds[1], $bounds[0]); - list( $maxx, $maxy ) = $mercator->LatLonToMeters($bounds[3], $bounds[2]); - $bounds3857 = array( $minx, $miny, $maxx, $maxy ); - } - -?> - - - - - - - - - - - - - - - - - - - - - - - - - - GoogleMapsCompatible - the wellknown 'GoogleMapsCompatible' tile matrix set defined by OGC WMTS specification - GoogleMapsCompatible - urn:ogc:def:crs:EPSG:6.18:3:3857 - urn:ogc:def:wkss:OGC:1.0:GoogleMapsCompatible - - 0 - 559082264.0287178 - -20037508.34278925 20037508.34278925 - 256 - 256 - 1 - 1 - - - 1 - 279541132.0143589 - -20037508.34278925 20037508.34278925 - 256 - 256 - 2 - 2 - - - 2 - 139770566.0071794 - -20037508.34278925 20037508.34278925 - 256 - 256 - 4 - 4 - - - 3 - 69885283.00358972 - -20037508.34278925 20037508.34278925 - 256 - 256 - 8 - 8 - - - 4 - 34942641.50179486 - -20037508.34278925 20037508.34278925 - 256 - 256 - 16 - 16 - - - 5 - 17471320.75089743 - -20037508.34278925 20037508.34278925 - 256 - 256 - 32 - 32 - - - 6 - 8735660.375448715 - -20037508.34278925 20037508.34278925 - 256 - 256 - 64 - 64 - - - 7 - 4367830.187724357 - -20037508.34278925 20037508.34278925 - 256 - 256 - 128 - 128 - - - 8 - 2183915.093862179 - -20037508.34278925 20037508.34278925 - 256 - 256 - 256 - 256 - - - 9 - 1091957.546931089 - -20037508.34278925 20037508.34278925 - 256 - 256 - 512 - 512 - - - 10 - 545978.7734655447 - -20037508.34278925 20037508.34278925 - 256 - 256 - 1024 - 1024 - - - 11 - 272989.3867327723 - -20037508.34278925 20037508.34278925 - 256 - 256 - 2048 - 2048 - - - 12 - 136494.6933663862 - -20037508.34278925 20037508.34278925 - 256 - 256 - 4096 - 4096 - - - 13 - 68247.34668319309 - -20037508.34278925 20037508.34278925 - 256 - 256 - 8192 - 8192 - - - 14 - 34123.67334159654 - -20037508.34278925 20037508.34278925 - 256 - 256 - 16384 - 16384 - - - 15 - 17061.83667079827 - -20037508.34278925 20037508.34278925 - 256 - 256 - 32768 - 32768 - - - 16 - 8530.918335399136 - -20037508.34278925 20037508.34278925 - 256 - 256 - 65536 - 65536 - - - 17 - 4265.459167699568 - -20037508.34278925 20037508.34278925 - 256 - 256 - 131072 - 131072 - - - 18 - 2132.729583849784 - -20037508.34278925 20037508.34278925 - 256 - 256 - 262144 - 262144 - - - - - WGS84 - GoogleCRS84Quad - urn:ogc:def:crs:EPSG:6.3:4326 - - -180.000000 -90.000000 - 180.000000 90.000000 - - urn:ogc:def:wkss:OGC:1.0:GoogleCRS84Quad - - 0 - 279541132.01435887813568115234 - 90.000000 -180.000000 - 256 - 256 - 2 - 1 - - - 1 - 139770566.00717943906784057617 - 90.000000 -180.000000 - 256 - 256 - 4 - 2 - - - 2 - 69885283.00358971953392028809 - 90.000000 -180.000000 - 256 - 256 - 8 - 4 - - - 3 - 34942641.50179485976696014404 - 90.000000 -180.000000 - 256 - 256 - 16 - 8 - - - 4 - 17471320.75089742988348007202 - 90.000000 -180.000000 - 256 - 256 - 32 - 16 - - - 5 - 8735660.37544871494174003601 - 90.000000 -180.000000 - 256 - 256 - 64 - 32 - - - 6 - 4367830.18772435747087001801 - 90.000000 -180.000000 - 256 - 256 - 128 - 64 - - - 7 - 2183915.09386217873543500900 - 90.000000 -180.000000 - 256 - 256 - 256 - 128 - - - 8 - 1091957.54693108936771750450 - 90.000000 -180.000000 - 256 - 256 - 512 - 256 - - - 9 - 545978.77346554468385875225 - 90.000000 -180.000000 - 256 - 256 - 1024 - 512 - - - 10 - 272989.38673277234192937613 - 90.000000 -180.000000 - 256 - 256 - 2048 - 1024 - - - 11 - 136494.69336638617096468806 - 90.000000 -180.000000 - 256 - 256 - 4096 - 2048 - - - 12 - 68247.34668319308548234403 - 90.000000 -180.000000 - 256 - 256 - 8192 - 4096 - - - 13 - 34123.67334159654274117202 - 90.000000 -180.000000 - 256 - 256 - 16384 - 8192 - - - 14 - 17061.83667079825318069197 - 90.000000 -180.000000 - 256 - 256 - 32768 - 16384 - - - 15 - 8530.91833539912659034599 - 90.000000 -180.000000 - 256 - 256 - 65536 - 32768 - - - 16 - 4265.45916769956329517299 - 90.000000 -180.000000 - 256 - 256 - 131072 - 65536 - - - 17 - 2132.72958384978574031265 - 90.000000 -180.000000 - 256 - 256 - 262144 - 131072 - - - - - - \ No newline at end of file diff --git a/tileserver.php b/tileserver.php index a71c175..11e3f62 100644 --- a/tileserver.php +++ b/tileserver.php @@ -3,413 +3,1360 @@ * TileServer.php project * ====================== * https://github.com/klokantech/tileserver-php/ - * Copyright (C) 2012 - Klokan Technologies GmbH + * Copyright (C) 2014 - Klokan Technologies GmbH */ -# Set you own config values here: -$config = array( - "baseUrls" => array("http://localhost/"), - "serverTitle" => "TileServer.php v0.1", -); +Router::serve(array( + '/' => 'Server:getInfo', + '/test' => 'Server:getInfo', + '/html' => 'Server:getHtml', + '/:string.json' => 'Json:getJson', + '/:string.jsonp' => 'Json:getJsonp', + '/:string/:number/:number/:number.grid.json' => 'Json:getUTFGrid', + '/wmts/' => 'Wmts:getCapabilities', + '/wmts' => 'Wmts:getTile', + '/wmts/1.0.0/WMTSCapabilities.xml' => 'Wmts:getCapabilities', + '/:string/:number/:number/:number.:string' => 'Wmts:getTile', + '/tms' => 'Tms:getCapabilities', + '/tms/' => 'Tms:getCapabilities', + '/:string/tms' => 'Tms:getLayerCapabilities', + '/:string/tms/' => 'Tms:getLayerCapabilities', + '/:string/tms/:number/:number/:number.:string' => 'Tms:getTile', +)); -# PHP debugging -ini_set("error_reporting", "true"); -error_reporting(E_ALL|E_STRCT); +/** + * Server base + */ +class Server { -# Global variable + ccepted GET / POST variables from the outside world -$baseUrl = $config['baseUrls'][0]; -// TODO: We can detext the baseUrl as well - for defined requests + /** + * Configuration of TileServer [baseUrls, serverTitle, host] + * @var array + */ + public $config; -$service = (array_key_exists('service', $_GET)) ? $_GET['service'] : ""; -$layer = (array_key_exists('layer', $_GET)) ? $_GET['layer'] : ""; -$callback = (array_key_exists('callback', $_GET)) ? $_GET['callback'] : ""; + /** + * Datasets stored in file structure + * @var array + */ + public $fileLayer = array(); -# CORS header -header('Access-Control-Allow-Origin: *'); + /** + * Datasets stored in database + * @var array + */ + public $dbLayer = array(); -# ------------ -# TEST SERVICE -# ------------ -if ($service == 'test') { - header("Content-Type: text/plain; charset=utf-8"); - echo "TileServer.php (", $config['serverTitle'], ') at ', $baseUrl; - die(); -} + /** + * PDO database connection + * @var object + */ + private $db; -# ------------ -# HTML SERVICE -# ------------ -if ($service == 'html'): - $maps = maps(); -?> - - - - - <?php echo $config['serverTitle'] ?> - - - - -

Welcome to

-

-This server distributes maps to desktop, web, and mobile applications. -

-

-The mapping data are available as OpenGIS Web Map Tiling Service (OGC WMTS), OSGEO Tile Map Service (TMS), and popular XYZ urls described with TileJSON metadata. -

- -

Wrong configuration of the "BaseURL" in tileserver.php

-

-Please modify 'tileserver.php' file and replace the '' in the $config variable with '' (with slash in the end) or other correct address to your server. Multiple CNAME can be used for better performance - more in readme.txt. -

- - -

No maps available yet

-

-Ready to go - just upload some maps into directory: / on this server. -

-

-Note: The maps can be a directory with tiles in XYZ format with metadata.json file.
-You can easily convert existing geodata (GeoTIFF, ECW, MrSID, etc) to this tile structure with MapTiler Cluster or open-source projects such as GDAL2Tiles or MapTiler or simply upload any maps in MBTiles format made by TileMill. Helpful is also the mbutil tool. Serving directly from .mbtiles files is supported, but with decreased performance. -

- -Available maps"; - echo ""; -} -?> - - - -metadataFromMetadataJson($mj); + array_push($this->fileLayer, $layer); + } + } + if ($mbts) { + foreach ($mbts as $mbt) { + $this->dbLayer[] = $this->metadataFromMbtiles($mbt); + } + } else { + echo 'Server: No JSON or MBtiles file with metadata'; + die; + } } - $output = json_encode($output); - $output = str_replace("\\/","/",$output); - if ($callback) echo "$callback($output);"; - else echo $output; -die; -endif; - -# INTERNAL FUNCTIONS: - -function maps() { - $maps = array(); - # Scan all directories with metadata.json - $mjs = glob('*/metadata.json'); - if ($mjs) foreach ($mjs as $mj) $maps[] = metadataFromMetadataJson($mj); - # Scan all mbtiles - $mbts = glob('*.mbtiles'); - if ($mbts) foreach ($mbts as $mbt) $maps[] = metadataFromMbtiles($mbt); - return $maps; -} - -function layer( $layer ) { - if (strpos($layer, '.mbtiles') === false) - return metadataFromMetadataJson($layer.'/metadata.json'); - else - return metadataFromMbtiles($layer); -} - -function metadataFromMetadataJson( $jsonFileName ) { - $metadata = json_decode( file_get_contents($jsonFileName), true ); - $metadata = metadataValidation($metadata); - $metadata['basename'] = str_replace('/metadata.json', '', $jsonFileName); - return $metadata; -} - -function metadataFromMbtiles( $mbt ) { - $metadata = array(); - $db = new PDO('sqlite:'.$mbt,'','',array(PDO::ATTR_PERSISTENT => true)); - if (isset($db)) { - $result = $db->query('select * from metadata'); - $resultdata = $result->fetchAll(); - foreach ($resultdata as $r) { - $metadata[$r['name']] = $r['value']; - } - $metadata = metadataValidation($metadata); - $metadata['basename'] = $mbt; + /** + * Processing params from router + * @param array $params + */ + public function setParams($params) { + if (isset($params[1])) { + $this->layer = $params[1]; + } + if (isset($params[2])) { + $this->z = $params[2]; + $this->y = $params[3]; + $this->x = $params[4]; + } + if (isset($params[5])) { + $this->ext = $params[5]; + } } - return $metadata; + + /** + * Get variable don't independent on sensitivity + * @param string $key + * @return string + */ + public function getGlobal($key) { + $keys[] = $key; + $keys[] = strtolower($key); + $keys[] = strtoupper($key); + $keys[] = ucfirst($key); + foreach ($keys as $key) { + if (isset($_GET[$key])) { + return $_GET[$key]; + } + } + echo 'Server: Unknown variable:' . $key; + die; + } + + /** + * Testing if is a database layer + * @param string $layer + * @return boolean + */ + public function isDBLayer($layer) { + foreach ($this->dbLayer as $DBLayer) { + $basename = explode('.', $DBLayer['basename']); + if ($basename[0] == $layer) { + return TRUE; + } + } + return false; + } + + /** + * Testing if is a file layer + * @param string $layer + * @return boolean + */ + public function isFileLyer($layer) { + foreach ($this->fileLayer as $DBLayer) { + if ($DBLayer['basename'] == $layer) { + return TRUE; + } + } + return false; + } + + /** + * + * @param string $jsonFileName + * @return array + */ + public function metadataFromMetadataJson($jsonFileName) { + $metadata = json_decode(file_get_contents($jsonFileName), true); + $metadata = $this->metadataValidation($metadata); + $metadata['basename'] = str_replace('/metadata.json', '', $jsonFileName); + return $metadata; + } + + /** + * Loads metadata from MBtiles + * @param string $mbt + * @return object + */ + public function metadataFromMbtiles($mbt) { + $metadata = array(); + $this->DBconnect($mbt); + $result = $this->db->query('select * from metadata'); + + $resultdata = $result->fetchAll(); + foreach ($resultdata as $r) { + $metadata[$r['name']] = $r['value']; + } + $metadata = $this->metadataValidation($metadata); + $mbt = explode('.', $mbt); + $metadata['basename'] = $mbt[0]; + return $metadata; + } + + /** + * Valids metaJSON + * @param object $metadata + * @return object + */ + public function metadataValidation($metadata) { + if (array_key_exists('bounds', $metadata)) { +// TODO: Calculate bounds from tiles if bounds is missing - with GlobalMercator + $metadata['bounds'] = array_map('floatval', explode(',', $metadata['bounds'])); + } + if (!array_key_exists('profile', $metadata)) { + $metadata['profile'] = 'mercator'; + } +// TODO: detect format, minzoom, maxzoom, thumb +// scandir() for directory / SQL for mbtiles + if (array_key_exists('minzoom', $metadata)) + $metadata['minzoom'] = intval($metadata['minzoom']); + else + $metadata['minzoom'] = 0; + if (array_key_exists('maxzoom', $metadata)) + $metadata['maxzoom'] = intval($metadata['maxzoom']); + else + $metadata['maxzoom'] = 18; + if (!array_key_exists('format', $metadata)) { + $metadata['format'] = 'png'; + } + /* + if (!array_key_exists('thumb', $metadata )) { + $metadata['profile'] = 'mercator'; + } + */ + return $metadata; + } + + /** + * SQLite connection + * @param string $tileset + */ + public function DBconnect($tileset) { + try { + $this->db = new PDO('sqlite:' . $tileset, '', '', array(PDO::ATTR_PERSISTENT => true)); + } catch (Exception $exc) { + echo $exc->getTraceAsString(); + die; + } + + if (!isset($this->db)) { + header('Content-type: text/plain'); + echo 'Incorrect tileset name: ' . $tileset; + exit; + } + } + + /** + * Check if file is modified and set Etag headers + * @param string $filename + * @return boolean + */ + public function isModified($filename) { + $filename = $filename . '.mbtiles'; + $lastModifiedTime = filemtime($filename); + $eTag = md5_file($filename); + header("Last-Modified: " . gmdate("D, d M Y H:i:s", $lastModifiedTime) . " GMT"); + header("Etag:" . $eTag); + if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $lastModifiedTime || + trim($_SERVER['HTTP_IF_NONE_MATCH']) == $eTag) { + return TRUE; + } else { + return FALSE; + } + } + + /** + * Returns tile of dataset + * @param string $tileset + * @param integer $z + * @param integer $y + * @param integer $x + * @param string $ext + */ + public function getTile($tileset, $z, $y, $x, $ext) { + if ($this->isDBLayer($tileset)) { + if ($this->isModified($tileset) == TRUE) { + header('HTTP/1.1 304 Not Modified'); + } + $this->DBconnect($tileset . '.mbtiles'); + $z = floatval($z); + $y = floatval($y); + $x = floatval($x); + $result = $this->db->query('select tile_data as t from tiles where zoom_level=' . $z . ' and tile_column=' . $x . ' and tile_row=' . $y); + $data = $result->fetchColumn(); + if (!isset($data) || $data === FALSE) { + $this->getCleanTile(); + } else { + $result = $this->db->query('select value from metadata where name="format"'); + $resultdata = $result->fetchColumn(); + $format = isset($resultdata) && $resultdata !== FALSE ? $resultdata : 'png'; + if ($format == 'jpg') { + $format = 'jpeg'; + } + header('Content-type: image/' . $format); + echo $data; + } + } elseif ($this->isFileLyer($tileset)) { + $name = './' . $tileset . '/' . $z . '/' . $y . '/' . $x . '.' . $ext; + if ($fp = @fopen($name, 'rb')) { + header('Content-Type: image/' . $ext); + header('Content-Length: ' . filesize($name)); + fpassthru($fp); + die; + } else { + $this->getCleanTile(); + } + } else { + echo 'Server: Unknow dataset'; + die; + } + } + + public function getCleanTile() { + $png = imagecreatetruecolor(256, 256); + imagesavealpha($png, true); + $trans_colour = imagecolorallocatealpha($png, 0, 0, 0, 127); + imagefill($png, 0, 0, $trans_colour); + header('Content-type: image/png'); + imagepng($png); + die; + } + + /** + * Returns tile's UTFGrid + * @param string $tileset + * @param integer $z + * @param integer $y + * @param integer $x + */ + public function getUTFGrid($tileset, $z, $y, $x) { + if ($this->isDBLayer($tileset)) { + if ($this->isModified($tileset) == TRUE) { + header('HTTP/1.1 304 Not Modified'); + } + $this->DBconnect($tileset . '.mbtiles'); + try { + $result = $this->db->query('SELECT grid FROM grids WHERE tile_column = ' . $x . ' AND tile_row = ' . $y . ' AND zoom_level = ' . $z); + $data = $result->fetchColumn(); + if (!isset($data) || $data === FALSE) { + header('Access-Control-Allow-Origin: *'); + echo 'grid({});'; + die; + } else { + $grid = gzuncompress($data); + $grid = substr(trim($grid), 0, -1); + + //adds legend (data) to output + $grid .= ',"data":{'; + $result = $this->db->query('SELECT key_name as key, key_json as json FROM grid_data WHERE zoom_level=' . $z . ' and tile_column=' . $x . ' and tile_row=' . $y); + while ($r = $result->fetch(PDO::FETCH_ASSOC)) { + $grid .= '"' . $r['key'] . '":' . $r['json'] . ','; + } + $grid = rtrim($grid, ',') . '}}'; + header('Access-Control-Allow-Origin: *'); + if (isset($_GET['callback'])) { + header("Content-Type:text/javascript charset=utf-8"); + echo $_GET['callback'] . '(' . $grid . ');'; + } else { + header("Content-Type:text/javascript; charset=utf-8"); + echo 'grid(' . $grid . ');'; + } + } + } catch (PDOException $e) { + header('Content-type: text/plain'); + print 'Error querying the database: ' . $e->getMessage(); + } + } else { + echo 'Server: no MBTiles tileset'; + die; + } + } + + /** + * Returns server info + */ + public function getInfo() { + $this->setDatasets(); + $maps = array_merge($this->fileLayer, $this->dbLayer); + header('Content-Type: text/html;charset=UTF-8'); + echo '' . $this->config['serverTitle'] . ''; + if (!isset($_SERVER['HTACCESS'])) { + echo '

Warning: No .htaccess support!

'; + } + foreach ($maps as $map) { + $extend = '['; + foreach ($map['bounds'] as $ext) { + $extend = $extend . ' ' . $ext; + } + $extend = $extend . ' ]'; + if (strpos($map['basename'], 'mbtiles') !== false) { + echo '

Available MBtiles tileset: ' . $map['basename'] . '
'; + } else { + echo '

Available file tileset: ' . $map['basename'] . '
'; + } + echo 'Bounds: ' . $extend . '

'; + } + echo ''; + } + + /** + * Returns html viewer + */ + public function getHtml() { + $this->setDatasets(); + $maps = array_merge($this->fileLayer, $this->dbLayer); + header('Content-Type: text/html;charset=UTF-8'); + echo '' . $this->config['serverTitle'] . ''; + echo ' + + +

Welcome to ' . $this->config['serverTitle'] . '

+

This server distributes maps to desktop, web, and mobile applications.

+

The mapping data are available as OpenGIS Web Map Tiling Service (OGC WMTS), OSGEO Tile Map Service (TMS), and popular XYZ urls described with TileJSON metadata.

'; + if (!isset($_SERVER['HTACCESS'])) { + echo '

Warning: No .htaccess support!

'; + } + if (!isset($maps)) { + echo '

No maps available yet

+

+ Ready to go - just upload some maps into directory:' . getcwd() . '/ on this server.

+

Note: The maps can be a directory with tiles in XYZ format with metadata.json file.
+ You can easily convert existing geodata (GeoTIFF, ECW, MrSID, etc) to this tile structure with MapTiler Cluster or open-source projects such as GDAL2Tiles or MapTiler or simply upload any maps in MBTiles format made by TileMill. Helpful is also the mbutil tool. Serving directly from .mbtiles files is supported, but with decreased performance.

'; + } else { + echo ''; + } + echo ''; + } + } -function metadataValidation( $metadata ) { - if (array_key_exists('bounds', $metadata )) { - // TODO: Calculate bounds from tiles if bounds is missing - with GlobalMercator - $metadata['bounds'] = array_map( 'floatval', explode(',', $metadata['bounds'] )); - } - if (!array_key_exists('profile', $metadata )) { - $metadata['profile'] = 'mercator'; - } - // TODO: detect format, minzoom, maxzoom, thumb - // scandir() for directory / SQL for mbtiles - if (array_key_exists('minzoom', $metadata )) - $metadata['minzoom'] = intval( $metadata['minzoom'] ); - else - $metadata['minzoom'] = 0; - if (array_key_exists('maxzoom', $metadata )) - $metadata['maxzoom'] = intval( $metadata['maxzoom'] ); - else - $metadata['maxzoom'] = 18; - if (!array_key_exists('format', $metadata )) { - $metadata['format'] = 'png'; - } - /* - if (!array_key_exists('thumb', $metadata )) { - $metadata['profile'] = 'mercator'; - } - */ - return $metadata; +/** + * JSON service + */ +class Json extends Server { + + /** + * Callback for JSONP default grid + * @var string + */ + private $callback = 'grid'; + + /** + * @param array $params + */ + public $layer = 'index'; + + /** + * @var integer + */ + public $z; + + /** + * @var integer + */ + public $y; + + /** + * @var integer + */ + public $x; + + /** + * @var string + */ + public $ext; + + /** + * + * @param array $params + */ + public function __construct($params) { + parent::__construct(); + parent::setParams($params); + parent::setDatasets(); + if (isset($_GET['callback']) && !empty($_GET['callback'])) { + $this->callback = $_GET['callback']; + } + } + + /** + * Adds metadata about layer + * @param array $metadata + * @return array + */ + public function metadataTileJson($metadata) { + $metadata['tilejson'] = '2.0.0'; + $metadata['scheme'] = 'xyz'; + $tiles = array(); +//foreach ($this->config['baseUrls'] as $url) + $tiles[] = 'http://' . $this->config['host'] . $metadata['basename'] . '/{z}/{x}/{y}.' . $metadata['format']; + $metadata['tiles'] = $tiles; + return $metadata; + } + + /** + * Creates JSON from array + * @param string $basename + * @return string + */ + private function createJson($basename) { + $maps = array_merge($this->fileLayer, $this->dbLayer); + if ($basename == 'index') { + $output = '['; + foreach ($maps as $map) { + $output = $output . json_encode($this->metadataTileJson($map), JSON_UNESCAPED_SLASHES) . ','; + } + $output = substr_replace($output, ']', -1); + } else { + foreach ($maps as $map) { + if (strpos($map['basename'], $basename) !== false) { + $output = json_encode($this->metadataTileJson($map), JSON_UNESCAPED_SLASHES); + break; + } + } + if (!isset($output)) { + $output = 'TileServer: unknown map ' . $basename; + echo 'TileServer: unknown map ' . $basename; + die; + } + } + return $output; + } + + /** + * Returns JSON with callback + */ + public function getJson() { + header('Access-Control-Allow-Origin: *'); + header("Content-Type:application/javascript charset=utf-8"); + echo $this->createJson($this->layer); + } + + /** + * Returns JSONP with callback + */ + public function getJsonp() { + header('Access-Control-Allow-Origin: *'); + header("Content-Type:text/javascript charset=utf-8"); + echo $this->callback . '(' . $this->createJson($this->layer) . ');'; + } + + /** + * Returns UTFGrid in JSON format + */ + public function getUTFGrid() { + parent::getUTFGrid($this->layer, $this->z, $this->y, $this->x); + } + } -function metadataTileJson( $metadata ) { - global $config; - $metadata['tilejson'] = '2.0.0'; - $metadata['scheme'] = 'xyz'; - $tiles = array(); - foreach($config['baseUrls'] as $url) - $tiles[] = $url.$metadata['basename'].'/{z}/{x}/{y}.'.$metadata['format']; - #print_r($tiles); - $metadata['tiles'] = $tiles; - return $metadata; +/** + * Web map tile service + */ +class Wmts extends Server { + + /** + * @param array $params + */ + public $layer; + + /** + * @var integer + */ + public $z; + + /** + * @var integer + */ + public $y; + + /** + * @var integer + */ + public $x; + + /** + * @var string + */ + public $ext; + + /** + * + * @param array $params + */ + public function __construct($params) { + parent::__construct(); + parent::setDatasets(); + } + + /** + * Returns tilesets getCapabilities + */ + public function getCapabilities() { + header("Content-type: application/xml"); + echo ''; + echo ' + + + ' . $this->config['serverTitle'] . ' + OGC WMTS + 1.0.0 + + + + + + + + + + RESTful + + + + + + + + KVP + + + + + + + + + + + + + RESTful + + + + + + + KVP + + + + + + + + '; + $maps = array_merge($this->fileLayer, $this->dbLayer); + $mercator = new GlobalMercator(); + foreach ($maps as $m) { + if (strpos($m['basename'], '.') !== false) { + $basename = explode('.', $m['basename']); + } else { + $basename = $m['basename']; + } + $title = (array_key_exists('name', $m)) ? $m['name'] : $basename; + $profile = $m['profile']; + $bounds = $m['bounds']; + $format = $m['format']; + $mime = ($format == 'jpg') ? 'image/jpeg' : 'image/png'; + if ($profile == 'geodetic') { + $tileMatrixSet = "WGS84"; + } else { + $tileMatrixSet = "GoogleMapsCompatible"; + list( $minx, $miny ) = $mercator->LatLonToMeters($bounds[1], $bounds[0]); + list( $maxx, $maxy ) = $mercator->LatLonToMeters($bounds[3], $bounds[2]); + $bounds3857 = array($minx, $miny, $maxx, $maxy); + } + echo' + ' . $title . ' + ' . $basename . ''; + echo ' + ' . $bounds[0] . ' ' . $bounds[1] . ' + ' . $bounds[2] . ' ' . $bounds[3] . ' + + + ' . $mime . ' + + ' . $tileMatrixSet . ' + + + '; + } + echo ' + GoogleMapsCompatible + the wellknown "GoogleMapsCompatible" tile matrix set defined by OGC WMTS specification + GoogleMapsCompatible + urn:ogc:def:crs:EPSG:6.18:3:3857 + urn:ogc:def:wkss:OGC:1.0:GoogleMapsCompatible + + 0 + 559082264.0287178 + -20037508.34278925 20037508.34278925 + 256 + 256 + 1 + 1 + + + 1 + 279541132.0143589 + -20037508.34278925 20037508.34278925 + 256 + 256 + 2 + 2 + + + 2 + 139770566.0071794 + -20037508.34278925 20037508.34278925 + 256 + 256 + 4 + 4 + + + 3 + 69885283.00358972 + -20037508.34278925 20037508.34278925 + 256 + 256 + 8 + 8 + + + 4 + 34942641.50179486 + -20037508.34278925 20037508.34278925 + 256 + 256 + 16 + 16 + + + 5 + 17471320.75089743 + -20037508.34278925 20037508.34278925 + 256 + 256 + 32 + 32 + + + 6 + 8735660.375448715 + -20037508.34278925 20037508.34278925 + 256 + 256 + 64 + 64 + + + 7 + 4367830.187724357 + -20037508.34278925 20037508.34278925 + 256 + 256 + 128 + 128 + + + 8 + 2183915.093862179 + -20037508.34278925 20037508.34278925 + 256 + 256 + 256 + 256 + + + 9 + 1091957.546931089 + -20037508.34278925 20037508.34278925 + 256 + 256 + 512 + 512 + + + 10 + 545978.7734655447 + -20037508.34278925 20037508.34278925 + 256 + 256 + 1024 + 1024 + + + 11 + 272989.3867327723 + -20037508.34278925 20037508.34278925 + 256 + 256 + 2048 + 2048 + + + 12 + 136494.6933663862 + -20037508.34278925 20037508.34278925 + 256 + 256 + 4096 + 4096 + + + 13 + 68247.34668319309 + -20037508.34278925 20037508.34278925 + 256 + 256 + 8192 + 8192 + + + 14 + 34123.67334159654 + -20037508.34278925 20037508.34278925 + 256 + 256 + 16384 + 16384 + + + 15 + 17061.83667079827 + -20037508.34278925 20037508.34278925 + 256 + 256 + 32768 + 32768 + + + 16 + 8530.918335399136 + -20037508.34278925 20037508.34278925 + 256 + 256 + 65536 + 65536 + + + 17 + 4265.459167699568 + -20037508.34278925 20037508.34278925 + 256 + 256 + 131072 + 131072 + + + 18 + 2132.729583849784 + -20037508.34278925 20037508.34278925 + 256 + 256 + 262144 + 262144 + + + + WGS84 + GoogleCRS84Quad + urn:ogc:def:crs:EPSG:6.3:4326 + + -180.000000 -90.000000 + 180.000000 90.000000 + + urn:ogc:def:wkss:OGC:1.0:GoogleCRS84Quad + + 0 + 279541132.01435887813568115234 + 90.000000 -180.000000 + 256 + 256 + 2 + 1 + + + 1 + 139770566.00717943906784057617 + 90.000000 -180.000000 + 256 + 256 + 4 + 2 + + + 2 + 69885283.00358971953392028809 + 90.000000 -180.000000 + 256 + 256 + 8 + 4 + + + 3 + 34942641.50179485976696014404 + 90.000000 -180.000000 + 256 + 256 + 16 + 8 + + + 4 + 17471320.75089742988348007202 + 90.000000 -180.000000 + 256 + 256 + 32 + 16 + + + 5 + 8735660.37544871494174003601 + 90.000000 -180.000000 + 256 + 256 + 64 + 32 + + + 6 + 4367830.18772435747087001801 + 90.000000 -180.000000 + 256 + 256 + 128 + 64 + + + 7 + 2183915.09386217873543500900 + 90.000000 -180.000000 + 256 + 256 + 256 + 128 + + + 8 + 1091957.54693108936771750450 + 90.000000 -180.000000 + 256 + 256 + 512 + 256 + + + 9 + 545978.77346554468385875225 + 90.000000 -180.000000 + 256 + 256 + 1024 + 512 + + + 10 + 272989.38673277234192937613 + 90.000000 -180.000000 + 256 + 256 + 2048 + 1024 + + + 11 + 136494.69336638617096468806 + 90.000000 -180.000000 + 256 + 256 + 4096 + 2048 + + + 12 + 68247.34668319308548234403 + 90.000000 -180.000000 + 256 + 256 + 8192 + 4096 + + + 13 + 34123.67334159654274117202 + 90.000000 -180.000000 + 256 + 256 + 16384 + 8192 + + + 14 + 17061.83667079825318069197 + 90.000000 -180.000000 + 256 + 256 + 32768 + 16384 + + + 15 + 8530.91833539912659034599 + 90.000000 -180.000000 + 256 + 256 + 65536 + 32768 + + + 16 + 4265.45916769956329517299 + 90.000000 -180.000000 + 256 + 256 + 131072 + 65536 + + + 17 + 2132.72958384978574031265 + 90.000000 -180.000000 + 256 + 256 + 262144 + 131072 + + + + +'; + } + + /** + * Returns tile via WMTS specification + */ + public function getTile() { + $request = $this->getGlobal('Request'); + if (isset($_GET['request'])) { + if (strpos('/', $_GET['Format']) !== FALSE) { + $format = explode('/', $_GET['Format']); + } else { + $format = $this->getGlobal('Format'); + } + parent::getTile($this->getGlobal('Layer'), $this->getGlobal('TileMatrix'), $this->getGlobal('TileRow'), $this->getGlobal('TileRow'), $format[1]); + } else { + parent::getTile($this->layer, $this->z, $this->y, $this->x, $this->ext); + } + } + } -function selfUrl( $serverOnly = false ) { - if(!isset($_SERVER['REQUEST_URI'])){ - $serverrequri = $_SERVER['PHP_SELF']; - }else{ - $serverrequri = $_SERVER['REQUEST_URI']; - } - $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : ""; - $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]); - if ($serverOnly) return 'http'.$s.'://'.$_SERVER['SERVER_NAME'].$port."/"; - return 'http'.$s.'://'.$_SERVER['SERVER_NAME'].$port.$serverrequri; -} +/** + * Tile map service + */ +class Tms extends Server { -function doConditionalGet($timestamp) { - $last_modified = gmdate('D, d M Y H:i:s \G\M\T', $timestamp); - $etag = '"'.md5($last_modified).'"'; - // Send the headers - header("Last-Modified: $last_modified"); - header("ETag: $etag"); - // See if the client has provided the required headers - $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? - stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']) : - false; - $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? - stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : - false; - if (!$if_modified_since && !$if_none_match) { - return; + /** + * @param array $params + */ + public $layer; + + /** + * @var integer + */ + public $z; + + /** + * @var integer + */ + public $y; + + /** + * @var integer + */ + public $x; + + /** + * @var string + */ + public $ext; + + /** + * + * @param array $params + */ + public function __construct($params) { + parent::__construct(); + parent::setParams($params); + parent::setDatasets(); + } + + /** + * Returns getCapabilities metadata request + */ + public function getCapabilities() { + $maps = array_merge($this->fileLayer, $this->dbLayer); + header("Content-type: application/xml"); + echo''; + foreach ($maps as $m) { + $basename = $m['basename']; + $title = (array_key_exists('name', $m) ) ? $m['name'] : $basename; + $profile = $m['profile']; + if ($profile == 'geodetic') { + $srs = "EPSG:4326"; + } else { + $srs = "EPSG:3857"; + echo ''; + } } - // At least one of the headers is there - check them - if ($if_none_match && $if_none_match != $etag) { - return; // etag is there but doesn't match + echo ''; + } + + /** + * Prints metadata about layer + */ + public function getLayerCapabilities() { + $maps = array_merge($this->fileLayer, $this->dbLayer); + foreach ($maps as $map) { + if (strpos($map['basename'], $this->layer) !== false) { + $m = $map; + break; + } } - if ($if_modified_since && $if_modified_since != $last_modified) { - return; // if-modified-since is there but doesn't match + $title = (array_key_exists('name', $m)) ? $m['name'] : $m['basename']; + $description = (array_key_exists('description', $m)) ? $m['description'] : ""; + $bounds = $m['bounds']; + if ($m['profile'] == 'geodetic') { + $srs = "EPSG:4326"; + $originx = -180.0; + $originy = -90.0; + $initialResolution = 0.703125; + } else { + $srs = "EPSG:3857"; + $originx = -20037508.342789; + $originy = -20037508.342789; + $mercator = new GlobalMercator(); + list( $minx, $miny ) = $mercator->LatLonToMeters($bounds[1], $bounds[0]); + list( $maxx, $maxy ) = $mercator->LatLonToMeters($bounds[3], $bounds[2]); + $bounds = array($minx, $miny, $maxx, $maxy); + $initialResolution = 156543.03392804062; } - // Nothing has changed since their last request - serve a 304 and exit - header('HTTP/1.0 304 Not Modified'); - exit; + $mime = ($m['format'] == 'jpg') ? 'image/jpeg' : 'image/png'; + header("Content-type: application/xml"); + echo ' + ' . htmlspecialchars($title) . ' + ' . htmlspecialchars($description) . ' + ' . $srs . ' + + + + '; + for ($zoom = $m['minzoom']; $zoom < $m['maxzoom'] + 1; $zoom++) { + echo ''; + } + echo''; + } + + /** + * Process getTile request + */ + public function getTile() { + parent::getTile($this->layer, $this->z, $this->y, $this->x, $this->ext); + } + } /* -TODO: https://github.com/klokantech/tileserver-php/issues/2 + GlobalMapTiles - part of Aggregate Map Tools + Version 1.0 + Copyright (c) 2009 The Bivings Group + All rights reserved. + Author: John Bafford + + http://www.bivings.com/ + http://bafford.com/softare/aggregate-map-tools/ + + Based on GDAL2Tiles / globalmaptiles.py + Original python version Copyright (c) 2008 Klokan Petr Pridal. All rights reserved. + http://www.klokan.cz/projects/gdal2tiles/ + + 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, sublic ense, + 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 abov + e 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. + */ + +class GlobalMercator { + + var $tileSize; + var $initialResolution; + var $originShift; + +//Initialize the TMS Global Mercator pyramid + function __construct($tileSize = 256) { + $this->tileSize = $tileSize; + $this->initialResolution = 2 * M_PI * 6378137 / $this->tileSize; +# 156543.03392804062 for tileSize 256 Pixels + $this->originShift = 2 * M_PI * 6378137 / 2.0; +# 20037508.342789244 + } + +//Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:900913 + function LatLonToMeters($lat, $lon) { + $mx = $lon * $this->originShift / 180.0; + $my = log(tan((90 + $lat) * M_PI / 360.0)) / (M_PI / 180.0); + + $my *= $this->originShift / 180.0; + + return array($mx, $my); + } + +//Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84 Datum + function MetersToLatLon($mx, $my) { + $lon = ($mx / $this->originShift) * 180.0; + $lat = ($my / $this->originShift) * 180.0; + + $lat = 180 / M_PI * (2 * atan(exp($lat * M_PI / 180.0)) - M_PI / 2.0); + + return array($lat, $lon); + } + +//Converts pixel coordinates in given zoom level of pyramid to EPSG:900913 + function PixelsToMeters($px, $py, $zoom) { + $res = $this->Resolution($zoom); + $mx = $px * $res - $this->originShift; + $my = $py * $res - $this->originShift; + + return array($mx, $my); + } + +//Converts EPSG:900913 to pyramid pixel coordinates in given zoom level + function MetersToPixels($mx, $my, $zoom) { + $res = $this->Resolution($zoom); + + $px = ($mx + $this->originShift) / $res; + $py = ($my + $this->originShift) / $res; + + return array($px, $py); + } + +//Returns a tile covering region in given pixel coordinates + function PixelsToTile($px, $py) { + $tx = ceil($px / $this->tileSize) - 1; + $ty = ceil($py / $this->tileSize) - 1; + + return array($tx, $ty); + } + +//Returns tile for given mercator coordinates + function MetersToTile($mx, $my, $zoom) { + list($px, $py) = $this->MetersToPixels($mx, $my, $zoom); + + return $this->PixelsToTile($px, $py); + } + +//Returns bounds of the given tile in EPSG:900913 coordinates + function TileBounds($tx, $ty, $zoom) { + list($minx, $miny) = $this->PixelsToMeters($tx * $this->tileSize, $ty * $this->tileSize, $zoom); + list($maxx, $maxy) = $this->PixelsToMeters(($tx + 1) * $this->tileSize, ($ty + 1) * $this->tileSize, $zoom); + + return array($minx, $miny, $maxx, $maxy); + } + +//Returns bounds of the given tile in latutude/longitude using WGS84 datum + function TileLatLonBounds($tx, $ty, $zoom) { + $bounds = $this->TileBounds($tx, $ty, $zoom); + + list($minLat, $minLon) = $this->MetersToLatLon($bounds[0], $bounds[1]); + list($maxLat, $maxLon) = $this->MetersToLatLon($bounds[2], $bounds[3]); + + return array($minLat, $minLon, $maxLat, $maxLon); + } + +//Resolution (meters/pixel) for given zoom level (measured at Equator) + function Resolution($zoom) { + return $this->initialResolution / (1 < $zoom); + } -function geoToMercTile($lon, $lat, $zoom) { - $xtile = floor((($lon + 180) / 360) * pow(2, $zoom)); - $ytile = floor((1 - log(tan(deg2rad($lat)) + 1 / cos(deg2rad($lat))) / pi()) /2 * pow(2, $zoom)); - return array($xtile, $ytile); } -function geoToGeoTile($lon, $lat, $zoom) { - $res = 180 / 256.0 / pow(2, $zoom); - $xtile = floor( ceil( (180 + $lat) / $res / 256.0 ) - 1 ); - $ytile = floor( ceil( (90 + $lon) / $res / 256.0 ) - 1 ); - return array($xtile, $ytile); +/** + * Simple router + */ +class Router { + + /** + * @param array $routes + */ + public static function serve($routes) { + $request_method = strtolower($_SERVER['REQUEST_METHOD']); + $path_info = '/'; + if (!empty($_SERVER['PATH_INFO'])) { + $path_info = $_SERVER['PATH_INFO']; + } else if (!empty($_SERVER['ORIG_PATH_INFO']) && $_SERVER['ORIG_PATH_INFO'] !== '/tileserver.php') { + $path_info = $_SERVER['ORIG_PATH_INFO']; + } else { + if (!empty($_SERVER['REQUEST_URI'])) { + $path_info = (strpos($_SERVER['REQUEST_URI'], '?') > 0) ? strstr($_SERVER['REQUEST_URI'], '?', true) : $_SERVER['REQUEST_URI']; + } + } + $discovered_handler = null; + $regex_matches = array(); + if (isset($routes[$path_info])) { + $discovered_handler = $routes[$path_info]; + } else if ($routes) { + $tokens = array( + ':string' => '([a-zA-Z]+)', + ':number' => '([0-9]+)', + ':alpha' => '([a-zA-Z0-9-_]+)' + ); + foreach ($routes as $pattern => $handler_name) { + $pattern = strtr($pattern, $tokens); + if (preg_match('#^/?' . $pattern . '/?$#', $path_info, $matches)) { + $discovered_handler = $handler_name; + $regex_matches = $matches; + break; + } + } + } + $handler_instance = null; + if ($discovered_handler) { + if (is_string($discovered_handler)) { + if (strpos($discovered_handler, ':') !== false) { + $discoverered_class = explode(':', $discovered_handler); + $discoverered_method = explode(':', $discovered_handler); + $handler_instance = new $discoverered_class[0]($regex_matches); + call_user_func(array($handler_instance, $discoverered_method[1])); + } else { + $handler_instance = new $discovered_handler($regex_matches); + } + } elseif (is_callable($discovered_handler)) { + $handler_instance = $discovered_handler(); + } + } else { + $handler_instance = new Server; + $handler_instance->getInfo(); + } + } + } - -function tileRange($bounds, $minzoom, $maxzoom) { - for ($z=$minzoom; $z < $maxzoom+1; $z++) { - print "$z\n"; - list($minx, $miny) = geoToMercTile($bounds[0], $bounds[1], $z); - list($maxx, $maxy) = geoToMercTile($bounds[2], $bounds[3], $z); - print_r( array($minx, $miny, $maxx, $maxy) ); - } -} - -// Better use the port of Klokans' GlobalMapTiles: -*/ - -/* - GlobalMapTiles - part of Aggregate Map Tools - Version 1.0 - Copyright (c) 2009 The Bivings Group - All rights reserved. - Author: John Bafford - - http://www.bivings.com/ - http://bafford.com/softare/aggregate-map-tools/ - - Based on GDAL2Tiles / globalmaptiles.py - Original python version Copyright (c) 2008 Klokan Petr Pridal. All rights reserved. - http://www.klokan.cz/projects/gdal2tiles/ - - 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. -*/ - -class GlobalMercator -{ - var $tileSize; - var $initialResolution; - var $originShift; - - //Initialize the TMS Global Mercator pyramid - function __construct($tileSize = 256) - { - $this->tileSize = $tileSize; - $this->initialResolution = 2 * M_PI * 6378137 / $this->tileSize; - # 156543.03392804062 for tileSize 256 Pixels - $this->originShift = 2 * M_PI * 6378137 / 2.0; - # 20037508.342789244 - } - - //Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:900913 - function LatLonToMeters($lat, $lon) - { - $mx = $lon * $this->originShift / 180.0; - $my = log( tan((90 + $lat) * M_PI / 360.0 )) / (M_PI / 180.0); - - $my *= $this->originShift / 180.0; - - return array($mx, $my); - } - - //Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84 Datum - function MetersToLatLon($mx, $my) - { - $lon = ($mx / $this->originShift) * 180.0; - $lat = ($my / $this->originShift) * 180.0; - - $lat = 180 / M_PI * (2 * atan( exp( $lat * M_PI / 180.0)) - M_PI / 2.0); - - return array($lat, $lon); - } - - //Converts pixel coordinates in given zoom level of pyramid to EPSG:900913 - function PixelsToMeters($px, $py, $zoom) - { - $res = $this->Resolution($zoom); - $mx = $px * $res - $this->originShift; - $my = $py * $res - $this->originShift; - - return array($mx, $my); - } - - //Converts EPSG:900913 to pyramid pixel coordinates in given zoom level - function MetersToPixels($mx, $my, $zoom) - { - $res = $this->Resolution( $zoom ); - - $px = ($mx + $this->originShift) / $res; - $py = ($my + $this->originShift) / $res; - - return array($px, $py); - } - - //Returns a tile covering region in given pixel coordinates - function PixelsToTile($px, $py) - { - $tx = ceil( $px / $this->tileSize ) - 1; - $ty = ceil( $py / $this->tileSize ) - 1; - - return array($tx, $ty); - } - - //Returns tile for given mercator coordinates - function MetersToTile($mx, $my, $zoom) - { - list($px, $py) = $this->MetersToPixels($mx, $my, $zoom); - - return $this->PixelsToTile($px, $py); - } - - //Returns bounds of the given tile in EPSG:900913 coordinates - function TileBounds($tx, $ty, $zoom) - { - list($minx, $miny) = $this->PixelsToMeters( $tx*$this->tileSize, $ty*$this->tileSize, $zoom ); - list($maxx, $maxy) = $this->PixelsToMeters( ($tx+1)*$this->tileSize, ($ty+1)*$this->tileSize, $zoom ); - - return array($minx, $miny, $maxx, $maxy); - } - - //Returns bounds of the given tile in latutude/longitude using WGS84 datum - function TileLatLonBounds($tx, $ty, $zoom) - { - $bounds = $this->TileBounds($tx, $ty, $zoom); - - list($minLat, $minLon) = $this->MetersToLatLon($bounds[0], $bounds[1]); - list($maxLat, $maxLon) = $this->MetersToLatLon($bounds[2], $bounds[3]); - - return array($minLat, $minLon, $maxLat, $maxLon); - } - - //Resolution (meters/pixel) for given zoom level (measured at Equator) - function Resolution($zoom) - { - return $this->initialResolution / (1 << $zoom); - } -} -$mercator = new GlobalMercator(); -?> From 212bc74fed7e6568f011c76ddecc7da95f2ba76c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Jan=C3=A1k?= Date: Fri, 11 Apr 2014 11:08:04 +0200 Subject: [PATCH 02/21] Enabled as default html page with tileserver-js --- tileserver.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tileserver.php b/tileserver.php index 11e3f62..c338714 100644 --- a/tileserver.php +++ b/tileserver.php @@ -7,7 +7,7 @@ */ Router::serve(array( - '/' => 'Server:getInfo', + '/' => 'Server:getHtml', '/test' => 'Server:getInfo', '/html' => 'Server:getHtml', '/:string.json' => 'Json:getJson', @@ -303,6 +303,9 @@ class Server { } } + /** + * Returns clean tile + */ public function getCleanTile() { $png = imagecreatetruecolor(256, 256); imagesavealpha($png, true); @@ -1354,8 +1357,9 @@ class Router { $handler_instance = $discovered_handler(); } } else { + //default page $handler_instance = new Server; - $handler_instance->getInfo(); + $handler_instance->getHtml(); } } From 56bfb34889951184222583aa1087ef3cd7953648 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Jan=C3=A1k?= Date: Mon, 14 Apr 2014 12:29:03 +0200 Subject: [PATCH 03/21] Fixed wmts/tms problems. --- tileserver.php | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/tileserver.php b/tileserver.php index c338714..c99a1af 100644 --- a/tileserver.php +++ b/tileserver.php @@ -1,4 +1,5 @@ ////.ext * @param array $params */ public function setParams($params) { @@ -96,8 +97,8 @@ class Server { } if (isset($params[2])) { $this->z = $params[2]; - $this->y = $params[3]; - $this->x = $params[4]; + $this->x = $params[3]; + $this->y = $params[4]; } if (isset($params[5])) { $this->ext = $params[5]; @@ -107,7 +108,7 @@ class Server { /** * Get variable don't independent on sensitivity * @param string $key - * @return string + * @return boolean */ public function getGlobal($key) { $keys[] = $key; @@ -119,8 +120,7 @@ class Server { return $_GET[$key]; } } - echo 'Server: Unknown variable:' . $key; - die; + return FALSE; } /** @@ -273,6 +273,10 @@ class Server { $z = floatval($z); $y = floatval($y); $x = floatval($x); + $flip = true; + if ($flip) { + $y = pow(2, $z) - 1 - $y; + } $result = $this->db->query('select tile_data as t from tiles where zoom_level=' . $z . ' and tile_column=' . $x . ' and tile_row=' . $y); $data = $result->fetchColumn(); if (!isset($data) || $data === FALSE) { @@ -298,7 +302,7 @@ class Server { $this->getCleanTile(); } } else { - echo 'Server: Unknow dataset'; + echo 'Server: Unknown or not specified dataset'; die; } } @@ -585,6 +589,9 @@ class Wmts extends Server { public function __construct($params) { parent::__construct(); parent::setDatasets(); + if (isset($params)) { + parent::setParams($params); + } } /** @@ -626,7 +633,7 @@ class Wmts extends Server { - + RESTful @@ -1044,13 +1051,13 @@ class Wmts extends Server { */ public function getTile() { $request = $this->getGlobal('Request'); - if (isset($_GET['request'])) { + if ($request) { if (strpos('/', $_GET['Format']) !== FALSE) { $format = explode('/', $_GET['Format']); } else { $format = $this->getGlobal('Format'); } - parent::getTile($this->getGlobal('Layer'), $this->getGlobal('TileMatrix'), $this->getGlobal('TileRow'), $this->getGlobal('TileRow'), $format[1]); + parent::getTile($this->getGlobal('Layer'), $this->getGlobal('TileMatrix'), $this->getGlobal('TileRow'), $this->getGlobal('TileCol'), $format[1]); } else { parent::getTile($this->layer, $this->z, $this->y, $this->x, $this->ext); } From f93f5e8b45b352e0ba75b15a89ca056e3ac70532 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Jan=C3=A1k?= Date: Wed, 23 Apr 2014 14:30:27 +0200 Subject: [PATCH 04/21] Problems with path url have been fixed. Global config variable have been added. --- .htaccess | 7 ++++- tileserver.php | 71 +++++++++++++++++++++++++++----------------------- 2 files changed, 44 insertions(+), 34 deletions(-) diff --git a/.htaccess b/.htaccess index 6c408e4..5cdf0b2 100644 --- a/.htaccess +++ b/.htaccess @@ -13,10 +13,15 @@ Options -MultiViews # Mapping of the WMTS standardized URLs to real files and XML capabilities to tileserver.php #check htaccess functionality -SetEnv HTACCESS on DirectoryIndex tileserver.php RewriteEngine on + +#some hostings require RewriteBase e.g. 1&1.com +#RewriteBase / +#RewriteBase /folder/ + +AcceptPathInfo on # WMTS RESTful # ------------ diff --git a/tileserver.php b/tileserver.php index c99a1af..587a983 100644 --- a/tileserver.php +++ b/tileserver.php @@ -7,6 +7,10 @@ * Copyright (C) 2014 - Klokan Technologies GmbH */ +global $config; +$config['serverTitle'] = 'TileServer-php v0.2'; +//$config['baseUrls'] = ['t0.server.com', 't1.server.com']; + Router::serve(array( '/' => 'Server:getHtml', '/test' => 'Server:getInfo', @@ -54,15 +58,21 @@ class Server { */ private $db; - /** + /** sercer.com/ts.php * Set config */ public function __construct() { - $ru = explode('/', $_SERVER['REQUEST_URI']); - $reqestUri = $_SERVER['HTTP_HOST'] . '/' . $ru[1] . '/'; - $this->config['baseUrls'] = array('http://' . $reqestUri); - $this->config['serverTitle'] = 'TileServer-php v0.2'; - $this->config['host'] = $reqestUri; + $this->config = $GLOBALS['config']; + if (!isset($this->config['baseUrls'])) { + //TODO if contains tileserver.php add to path + $ru = explode('/', $_SERVER['REQUEST_URI']); + $this->config['baseUrls'][0] = $_SERVER['HTTP_HOST']; + if (isset($ru[2])) { + //autodetection for http://server/ or http://server/directory + //subdirectories must be specified $con + $this->config['baseUrls'][0] = $this->config['baseUrls'][0] . '/' . $ru[1]; + } + } } /** @@ -76,8 +86,7 @@ class Server { $layer = $this->metadataFromMetadataJson($mj); array_push($this->fileLayer, $layer); } - } - if ($mbts) { + } elseif ($mbts) { foreach ($mbts as $mbt) { $this->dbLayer[] = $this->metadataFromMbtiles($mbt); } @@ -193,6 +202,8 @@ class Server { if (array_key_exists('bounds', $metadata)) { // TODO: Calculate bounds from tiles if bounds is missing - with GlobalMercator $metadata['bounds'] = array_map('floatval', explode(',', $metadata['bounds'])); + } else { + $metadata['bounds'] = array(-180, -85.051128779807, 180, 85.051128779807); } if (!array_key_exists('profile', $metadata)) { $metadata['profile'] = 'mercator'; @@ -378,9 +389,6 @@ class Server { $maps = array_merge($this->fileLayer, $this->dbLayer); header('Content-Type: text/html;charset=UTF-8'); echo '' . $this->config['serverTitle'] . ''; - if (!isset($_SERVER['HTACCESS'])) { - echo '

Warning: No .htaccess support!

'; - } foreach ($maps as $map) { $extend = '['; foreach ($map['bounds'] as $ext) { @@ -407,13 +415,10 @@ class Server { echo '' . $this->config['serverTitle'] . ''; echo ' - +

Welcome to ' . $this->config['serverTitle'] . '

This server distributes maps to desktop, web, and mobile applications.

The mapping data are available as OpenGIS Web Map Tiling Service (OGC WMTS), OSGEO Tile Map Service (TMS), and popular XYZ urls described with TileJSON metadata.

'; - if (!isset($_SERVER['HTACCESS'])) { - echo '

Warning: No .htaccess support!

'; - } if (!isset($maps)) { echo '

No maps available yet

@@ -490,8 +495,9 @@ class Json extends Server { $metadata['tilejson'] = '2.0.0'; $metadata['scheme'] = 'xyz'; $tiles = array(); -//foreach ($this->config['baseUrls'] as $url) - $tiles[] = 'http://' . $this->config['host'] . $metadata['basename'] . '/{z}/{x}/{y}.' . $metadata['format']; + foreach ($this->config['baseUrls'] as $url) { + $tiles[] = 'http://' . $url . '/' . $metadata['basename'] . '/{z}/{x}/{y}.' . $metadata['format']; + } $metadata['tiles'] = $tiles; return $metadata; } @@ -516,11 +522,10 @@ class Json extends Server { break; } } - if (!isset($output)) { - $output = 'TileServer: unknown map ' . $basename; - echo 'TileServer: unknown map ' . $basename; - die; - } + } + if (!isset($output)) { + echo 'TileServer: unknown map ' . $basename; + die; } return $output; } @@ -612,7 +617,7 @@ class Wmts extends Server { - + RESTful @@ -620,7 +625,7 @@ class Wmts extends Server { - + KVP @@ -633,14 +638,14 @@ class Wmts extends Server { - + RESTful - + KVP @@ -687,8 +692,8 @@ class Wmts extends Server { ' . $tileMatrixSet . ' - + '; } echo ' @@ -1042,7 +1047,7 @@ class Wmts extends Server { - + '; } @@ -1122,7 +1127,7 @@ class Tms extends Server { $srs = "EPSG:3857"; echo ''; + . '" href="http://' . $this->config['baseUrls'][0] . '/' . $basename . '/tms" />'; } } echo ''; @@ -1159,7 +1164,7 @@ class Tms extends Server { } $mime = ($m['format'] == 'jpg') ? 'image/jpeg' : 'image/png'; header("Content-type: application/xml"); - echo ' + echo ' ' . htmlspecialchars($title) . ' ' . htmlspecialchars($description) . ' ' . $srs . ' @@ -1168,7 +1173,7 @@ class Tms extends Server { '; for ($zoom = $m['minzoom']; $zoom < $m['maxzoom'] + 1; $zoom++) { - echo ''; + echo ''; } echo''; } @@ -1364,7 +1369,7 @@ class Router { $handler_instance = $discovered_handler(); } } else { - //default page +//default page $handler_instance = new Server; $handler_instance->getHtml(); } From 4a4a2ee3482f015f9ea884298b7ff8a458244c01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Jan=C3=A1k?= Date: Wed, 23 Apr 2014 16:08:09 +0200 Subject: [PATCH 05/21] Problems with old php versions have been fixed. --- tileserver.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tileserver.php b/tileserver.php index 587a983..d5bfc79 100644 --- a/tileserver.php +++ b/tileserver.php @@ -67,9 +67,9 @@ class Server { //TODO if contains tileserver.php add to path $ru = explode('/', $_SERVER['REQUEST_URI']); $this->config['baseUrls'][0] = $_SERVER['HTTP_HOST']; - if (isset($ru[2])) { + if (isset($ru[2]) && !empty($ru[2]) && $ru[2] !== 'tms') { //autodetection for http://server/ or http://server/directory - //subdirectories must be specified $con + //subdirectories must be specified $config['baseUrls'] $this->config['baseUrls'][0] = $this->config['baseUrls'][0] . '/' . $ru[1]; } } @@ -512,13 +512,13 @@ class Json extends Server { if ($basename == 'index') { $output = '['; foreach ($maps as $map) { - $output = $output . json_encode($this->metadataTileJson($map), JSON_UNESCAPED_SLASHES) . ','; + $output = $output . json_encode($this->metadataTileJson($map)) . ','; } $output = substr_replace($output, ']', -1); } else { foreach ($maps as $map) { if (strpos($map['basename'], $basename) !== false) { - $output = json_encode($this->metadataTileJson($map), JSON_UNESCAPED_SLASHES); + $output = json_encode($this->metadataTileJson($map)); break; } } From 2dfb1952aa59deb14d798a130c54ea4a26f87c4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Jan=C3=A1k?= Date: Wed, 23 Apr 2014 17:01:08 +0200 Subject: [PATCH 06/21] Tileserver now supports *.json with callback. --- tileserver.php | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/tileserver.php b/tileserver.php index d5bfc79..4674d9c 100644 --- a/tileserver.php +++ b/tileserver.php @@ -67,7 +67,7 @@ class Server { //TODO if contains tileserver.php add to path $ru = explode('/', $_SERVER['REQUEST_URI']); $this->config['baseUrls'][0] = $_SERVER['HTTP_HOST']; - if (isset($ru[2]) && !empty($ru[2]) && $ru[2] !== 'tms') { + if (isset($ru[2]) && (!empty($ru[2]) || $ru[2] !== 'tms')) { //autodetection for http://server/ or http://server/directory //subdirectories must be specified $config['baseUrls'] $this->config['baseUrls'][0] = $this->config['baseUrls'][0] . '/' . $ru[1]; @@ -86,11 +86,17 @@ class Server { $layer = $this->metadataFromMetadataJson($mj); array_push($this->fileLayer, $layer); } - } elseif ($mbts) { + } else { + $e = 1; + } + if ($mbts) { foreach ($mbts as $mbt) { $this->dbLayer[] = $this->metadataFromMbtiles($mbt); } } else { + $e = 1; + } + if (isset($e)) { echo 'Server: No JSON or MBtiles file with metadata'; die; } @@ -152,7 +158,7 @@ class Server { * @param string $layer * @return boolean */ - public function isFileLyer($layer) { + public function isFileLayer($layer) { foreach ($this->fileLayer as $DBLayer) { if ($DBLayer['basename'] == $layer) { return TRUE; @@ -302,7 +308,7 @@ class Server { header('Content-type: image/' . $format); echo $data; } - } elseif ($this->isFileLyer($tileset)) { + } elseif ($this->isFileLayer($tileset)) { $name = './' . $tileset . '/' . $z . '/' . $y . '/' . $x . '.' . $ext; if ($fp = @fopen($name, 'rb')) { header('Content-Type: image/' . $ext); @@ -536,7 +542,11 @@ class Json extends Server { public function getJson() { header('Access-Control-Allow-Origin: *'); header("Content-Type:application/javascript charset=utf-8"); - echo $this->createJson($this->layer); + if ($this->callback !== 'grid') { + echo $this->callback . '(' . $this->createJson($this->layer) . ');'; + } else { + echo $this->createJson($this->layer); + } } /** From b6470bd4483fd1fc9ccbd44db33dc73f0ed916cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Jan=C3=A1k?= Date: Thu, 24 Apr 2014 14:56:01 +0200 Subject: [PATCH 07/21] Better router. TileServer now uses .js and .css files from maptiler.com. --- .htaccess | 8 ++--- tileserver.php | 82 +++++++++++++++++++++++++------------------------- 2 files changed, 44 insertions(+), 46 deletions(-) diff --git a/.htaccess b/.htaccess index 5cdf0b2..9bcd5f2 100644 --- a/.htaccess +++ b/.htaccess @@ -2,8 +2,8 @@ # Restrictions for data crawlers Options -Indexes -Options +FollowSymLinks -Options -MultiViews +#Options +FollowSymLinks +#Options -MultiViews # Optional CORS header for cross-domain origin access to all data # @@ -20,8 +20,6 @@ RewriteEngine on #some hostings require RewriteBase e.g. 1&1.com #RewriteBase / #RewriteBase /folder/ - -AcceptPathInfo on # WMTS RESTful # ------------ @@ -48,4 +46,4 @@ RewriteRule .* - [E=HTTP_IF_NONE_MATCH:%{HTTP:If-None-Match}] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond $1 !^(tileserver\.php) -RewriteRule ^(.*)$ tileserver.php/$1 [L] \ No newline at end of file +RewriteRule ^(.*)$ tileserver.php?/$1 [L,QSA] \ No newline at end of file diff --git a/tileserver.php b/tileserver.php index 4674d9c..993939a 100644 --- a/tileserver.php +++ b/tileserver.php @@ -18,16 +18,13 @@ Router::serve(array( '/:string.json' => 'Json:getJson', '/:string.jsonp' => 'Json:getJsonp', '/:string/:number/:number/:number.grid.json' => 'Json:getUTFGrid', - '/wmts/' => 'Wmts:getCapabilities', - '/wmts' => 'Wmts:getTile', + '/wmts' => 'Wmts:get', '/wmts/1.0.0/WMTSCapabilities.xml' => 'Wmts:getCapabilities', '/:string/:number/:number/:number.:string' => 'Wmts:getTile', '/tms' => 'Tms:getCapabilities', - '/tms/' => 'Tms:getCapabilities', - '/:string/tms' => 'Tms:getLayerCapabilities', - '/:string/tms/' => 'Tms:getLayerCapabilities', + '/tms/:string' => 'Tms:getLayerCapabilities', '/:string/tms/:number/:number/:number.:string' => 'Tms:getTile', -)); + )); /** * Server base @@ -63,16 +60,6 @@ class Server { */ public function __construct() { $this->config = $GLOBALS['config']; - if (!isset($this->config['baseUrls'])) { - //TODO if contains tileserver.php add to path - $ru = explode('/', $_SERVER['REQUEST_URI']); - $this->config['baseUrls'][0] = $_SERVER['HTTP_HOST']; - if (isset($ru[2]) && (!empty($ru[2]) || $ru[2] !== 'tms')) { - //autodetection for http://server/ or http://server/directory - //subdirectories must be specified $config['baseUrls'] - $this->config['baseUrls'][0] = $this->config['baseUrls'][0] . '/' . $ru[1]; - } - } } /** @@ -96,10 +83,10 @@ class Server { } else { $e = 1; } - if (isset($e)) { - echo 'Server: No JSON or MBtiles file with metadata'; - die; - } +// if (isset($e)) { +// echo 'Server: No JSON or MBtiles file with metadata'; +// die; +// } } /** @@ -125,14 +112,11 @@ class Server { * @param string $key * @return boolean */ - public function getGlobal($key) { - $keys[] = $key; - $keys[] = strtolower($key); - $keys[] = strtoupper($key); - $keys[] = ucfirst($key); - foreach ($keys as $key) { - if (isset($_GET[$key])) { - return $_GET[$key]; + public function getGlobal($isKey) { + $get = $_GET; + foreach ($get as $key => $value) { + if(strtolower($isKey) == strtolower($key)){ + return $value; } } return FALSE; @@ -419,9 +403,9 @@ class Server { $maps = array_merge($this->fileLayer, $this->dbLayer); header('Content-Type: text/html;charset=UTF-8'); echo '' . $this->config['serverTitle'] . ''; - echo ' - - + echo ' + +

Welcome to ' . $this->config['serverTitle'] . '

This server distributes maps to desktop, web, and mobile applications.

The mapping data are available as OpenGIS Web Map Tiling Service (OGC WMTS), OSGEO Tile Map Service (TMS), and popular XYZ urls described with TileJSON metadata.

'; @@ -609,6 +593,18 @@ class Wmts extends Server { } } + /** + * Tests request from url and call method + */ + public function get(){ + $request = $this->getGlobal('Request'); + if($request !== FALSE && $request == 'gettile'){ + $this->getTile(); + }else{ + $this->getCapabilities(); + } + } + /** * Returns tilesets getCapabilities */ @@ -1069,10 +1065,11 @@ class Wmts extends Server { if ($request) { if (strpos('/', $_GET['Format']) !== FALSE) { $format = explode('/', $_GET['Format']); + $format = $format[1]; } else { $format = $this->getGlobal('Format'); } - parent::getTile($this->getGlobal('Layer'), $this->getGlobal('TileMatrix'), $this->getGlobal('TileRow'), $this->getGlobal('TileCol'), $format[1]); + parent::getTile($this->getGlobal('Layer'), $this->getGlobal('TileMatrix'), $this->getGlobal('TileRow'), $this->getGlobal('TileCol'), $format); } else { parent::getTile($this->layer, $this->z, $this->y, $this->x, $this->ext); } @@ -1137,7 +1134,7 @@ class Tms extends Server { $srs = "EPSG:3857"; echo ''; + . '" href="http://' . $this->config['baseUrls'][0] . '/tms/' . $basename . '" />'; } } echo ''; @@ -1333,7 +1330,7 @@ class Router { /** * @param array $routes */ - public static function serve($routes) { + public static function serve($routes) { $request_method = strtolower($_SERVER['REQUEST_METHOD']); $path_info = '/'; if (!empty($_SERVER['PATH_INFO'])) { @@ -1347,17 +1344,20 @@ class Router { } $discovered_handler = null; $regex_matches = array(); - if (isset($routes[$path_info])) { - $discovered_handler = $routes[$path_info]; - } else if ($routes) { + + if ($routes) { $tokens = array( ':string' => '([a-zA-Z]+)', ':number' => '([0-9]+)', ':alpha' => '([a-zA-Z0-9-_]+)' ); + global $config; foreach ($routes as $pattern => $handler_name) { $pattern = strtr($pattern, $tokens); - if (preg_match('#^/?' . $pattern . '/?$#', $path_info, $matches)) { + if (preg_match('#/?' . $pattern . '/?$#', $path_info, $matches)) { + if(!isset($config['baseUrls'])){ + $config['baseUrls'][0] = $_SERVER['HTTP_HOST'].preg_replace('#/?'.$pattern.'/?$#', '', $path_info); + } $discovered_handler = $handler_name; $regex_matches = $matches; break; @@ -1379,9 +1379,9 @@ class Router { $handler_instance = $discovered_handler(); } } else { -//default page - $handler_instance = new Server; - $handler_instance->getHtml(); + echo 'Router: No route'; die; + //$handler_instance = new Server; + //$handler_instance->getHtml(); } } From 9bbb1bce05c9651354803390d6c2875246b74f27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Jan=C3=A1k?= Date: Thu, 24 Apr 2014 17:08:15 +0200 Subject: [PATCH 08/21] Httacess updates. --- .htaccess | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/.htaccess b/.htaccess index 9bcd5f2..7b375ab 100644 --- a/.htaccess +++ b/.htaccess @@ -1,9 +1,7 @@ # tileserver.php integration with Apache via .htaccess # Restrictions for data crawlers -Options -Indexes -#Options +FollowSymLinks -#Options -MultiViews +#Options -Indexes # Optional CORS header for cross-domain origin access to all data # @@ -19,7 +17,10 @@ RewriteEngine on #some hostings require RewriteBase e.g. 1&1.com #RewriteBase / -#RewriteBase /folder/ +#RewriteBase /cosi/ + +#some hostings require -MultiViews e.g. 1&1.com +#Options -MultiViews # WMTS RESTful # ------------ @@ -28,12 +29,12 @@ RewriteEngine on # map /wmts/layer/[ANYTHING]z/x/y.ext -> /layer/z/x/y.ext (WMTS ignoring tilematrixset,style,..) # BTW This is used only by Gaia which ignores the -RewriteRule ^wmts/([\w\d\._-]+)/.*?(\d+)/(\d+)/(\d+)\.(\w+)$ $1/$2/$4/$3.$5 [L] +RewriteRule ^wmts/([\w\d\._-]+)/.*?(\d+)/(\d+)/(\d+)\.(\w+)$ $1/$2/$4/$3.$5 [N] # Example: http://www.tileserver.com/wmts/grandcanyon/style/tilematrixset/10/192/401.png # map /layer/[ANYTHING]z/x/y.ext -> /layer/z/x/y.ext (WMTS ignoring tilematrix,style,..) RewriteCond %{REQUEST_FILENAME} !-f -RewriteRule ^([\w\d\._-]+)/.+?(\d+)/(\d+)/(\d+)\.(\w+)$ $1/$2/$3/$4.$5 [L] +RewriteRule ^([\w\d\._-]+)/.+?(\d+)/(\d+)/(\d+)\.(\w+)$ $1/$2/$3/$4.$5 [N] # Example: http://www.tileserver.com/grandcanyon/style/tilematrixset/10/192/401.png # rewrite .jpeg -> .jpg From 1f1dd22227c8495f1849c354b1e14a5731c43c63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Jan=C3=A1k?= Date: Fri, 25 Apr 2014 10:22:02 +0200 Subject: [PATCH 09/21] Increase the speed with mbtiles. --- tileserver.php | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/tileserver.php b/tileserver.php index 993939a..9c40dff 100644 --- a/tileserver.php +++ b/tileserver.php @@ -23,7 +23,6 @@ Router::serve(array( '/:string/:number/:number/:number.:string' => 'Wmts:getTile', '/tms' => 'Tms:getCapabilities', '/tms/:string' => 'Tms:getLayerCapabilities', - '/:string/tms/:number/:number/:number.:string' => 'Tms:getTile', )); /** @@ -88,7 +87,7 @@ class Server { // die; // } } - + /** * Processing params from router ////.ext * @param array $params @@ -128,13 +127,11 @@ class Server { * @return boolean */ public function isDBLayer($layer) { - foreach ($this->dbLayer as $DBLayer) { - $basename = explode('.', $DBLayer['basename']); - if ($basename[0] == $layer) { - return TRUE; - } + if(is_file($layer.'.mbtiles')){ + return TRUE; + } else { + return FALSE; } - return false; } /** @@ -143,12 +140,11 @@ class Server { * @return boolean */ public function isFileLayer($layer) { - foreach ($this->fileLayer as $DBLayer) { - if ($DBLayer['basename'] == $layer) { - return TRUE; - } + if(is_dir($layer)){ + return TRUE; + } else { + return FALSE; } - return false; } /** @@ -470,7 +466,6 @@ class Json extends Server { public function __construct($params) { parent::__construct(); parent::setParams($params); - parent::setDatasets(); if (isset($_GET['callback']) && !empty($_GET['callback'])) { $this->callback = $_GET['callback']; } @@ -524,6 +519,7 @@ class Json extends Server { * Returns JSON with callback */ public function getJson() { + parent::setDatasets(); header('Access-Control-Allow-Origin: *'); header("Content-Type:application/javascript charset=utf-8"); if ($this->callback !== 'grid') { @@ -537,6 +533,7 @@ class Json extends Server { * Returns JSONP with callback */ public function getJsonp() { + parent::setDatasets(); header('Access-Control-Allow-Origin: *'); header("Content-Type:text/javascript charset=utf-8"); echo $this->callback . '(' . $this->createJson($this->layer) . ');'; @@ -587,7 +584,6 @@ class Wmts extends Server { */ public function __construct($params) { parent::__construct(); - parent::setDatasets(); if (isset($params)) { parent::setParams($params); } @@ -601,6 +597,7 @@ class Wmts extends Server { if($request !== FALSE && $request == 'gettile'){ $this->getTile(); }else{ + parent::setDatasets(); $this->getCapabilities(); } } @@ -1114,13 +1111,13 @@ class Tms extends Server { public function __construct($params) { parent::__construct(); parent::setParams($params); - parent::setDatasets(); } /** * Returns getCapabilities metadata request */ public function getCapabilities() { + parent::setDatasets(); $maps = array_merge($this->fileLayer, $this->dbLayer); header("Content-type: application/xml"); echo''; @@ -1144,6 +1141,7 @@ class Tms extends Server { * Prints metadata about layer */ public function getLayerCapabilities() { + parent::setDatasets(); $maps = array_merge($this->fileLayer, $this->dbLayer); foreach ($maps as $map) { if (strpos($map['basename'], $this->layer) !== false) { From 2461a184a861a8727de4ad137c3fe40c30f37c60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Jan=C3=A1k?= Date: Fri, 25 Apr 2014 11:37:42 +0200 Subject: [PATCH 10/21] Add grids to metadata.json "Fixies #1" --- tileserver.php | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/tileserver.php b/tileserver.php index 9c40dff..2447b5e 100644 --- a/tileserver.php +++ b/tileserver.php @@ -52,9 +52,9 @@ class Server { * PDO database connection * @var object */ - private $db; + public $db; - /** sercer.com/ts.php + /** * Set config */ public function __construct() { @@ -484,6 +484,16 @@ class Json extends Server { $tiles[] = 'http://' . $url . '/' . $metadata['basename'] . '/{z}/{x}/{y}.' . $metadata['format']; } $metadata['tiles'] = $tiles; + if($this->isDBLayer($metadata['basename'])){ + $this->DBconnect($metadata['basename'].'.mbtiles'); + $res = $this->db->query('SELECT grid FROM grids LIMIT 1'); + if($res){ + foreach ($this->config['baseUrls'] as $url) { + $grids[] = 'http://' . $url . '/' . $metadata['basename'] . '/{z}/{x}/{y}.grid.json'; + } + $metadata['grids'] = $grids; + } + } return $metadata; } From 0f059f4fb77ee5e141e31f9a932914f6416f2998 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Jan=C3=A1k?= Date: Mon, 28 Apr 2014 14:12:51 +0200 Subject: [PATCH 11/21] Problems with WMTS have been fixed. --- .htaccess | 20 ++++---- testt/.htaccess | 50 ++++++++++++++++++++ tileserver.php | 120 ++++++++++++++++++++++++++---------------------- 3 files changed, 125 insertions(+), 65 deletions(-) create mode 100644 testt/.htaccess diff --git a/.htaccess b/.htaccess index 7b375ab..82b0d8f 100644 --- a/.htaccess +++ b/.htaccess @@ -17,7 +17,7 @@ RewriteEngine on #some hostings require RewriteBase e.g. 1&1.com #RewriteBase / -#RewriteBase /cosi/ +#RewriteBase /server/ #some hostings require -MultiViews e.g. 1&1.com #Options -MultiViews @@ -27,15 +27,15 @@ RewriteEngine on # The file can be accessed directly: # Example: http://www.tileserver.com/grandcanyon/10/192/401.png -# map /wmts/layer/[ANYTHING]z/x/y.ext -> /layer/z/x/y.ext (WMTS ignoring tilematrixset,style,..) -# BTW This is used only by Gaia which ignores the -RewriteRule ^wmts/([\w\d\._-]+)/.*?(\d+)/(\d+)/(\d+)\.(\w+)$ $1/$2/$4/$3.$5 [N] -# Example: http://www.tileserver.com/wmts/grandcanyon/style/tilematrixset/10/192/401.png - -# map /layer/[ANYTHING]z/x/y.ext -> /layer/z/x/y.ext (WMTS ignoring tilematrix,style,..) -RewriteCond %{REQUEST_FILENAME} !-f -RewriteRule ^([\w\d\._-]+)/.+?(\d+)/(\d+)/(\d+)\.(\w+)$ $1/$2/$3/$4.$5 [N] -# Example: http://www.tileserver.com/grandcanyon/style/tilematrixset/10/192/401.png +## map /wmts/layer/[ANYTHING]z/x/y.ext -> /layer/z/x/y.ext (WMTS ignoring tilematrixset,style,..) +## BTW This is used only by Gaia which ignores the +#RewriteRule ^wmts/([\w\d\._-]+)/.+?(\d+)/(\d+)/(\d+)\.(\w+)$ $1/$2/$4/$3.$5 [N] +## Example: http://www.tileserver.com/wmts/grandcanyon/style/tilematrixset/10/192/401.png +# +## map /layer/[ANYTHING]z/x/y.ext -> /layer/z/x/y.ext (WMTS ignoring tilematrix,style,..) +#RewriteCond %{REQUEST_FILENAME} !-f +#RewriteRule ^([\w\d\._-]+)/.+?(\d+)/(\d+)/(\d+)\.(\w+)$ $1/$2/$3/$4.$5 [N] +## Example: http://www.tileserver.com/grandcanyon/style/tilematrixset/10/192/401.png # rewrite .jpeg -> .jpg RewriteRule ^(.+).jpeg$ $1.jpg [L] diff --git a/testt/.htaccess b/testt/.htaccess new file mode 100644 index 0000000..9a96f73 --- /dev/null +++ b/testt/.htaccess @@ -0,0 +1,50 @@ +# tileserver.php integration with Apache via .htaccess + +# Restrictions for data crawlers +Options -Indexes + + Options -MultiViews + + +# Optional CORS header for cross-domain origin access to all data +# +# Header set Access-Control-Allow-Origin * +# + +# Mapping of the WMTS standardized URLs to real files and XML capabilities to tileserver.php + +#check htaccess functionality +DirectoryIndex tileserver.php + +RewriteEngine on + +#some hostings require RewriteBase e.g. 1&1.com +RewriteBase / +#RewriteBase /cosi/ + +# WMTS RESTful +# ------------ +# The file can be accessed directly: +# Example: http://www.tileserver.com/grandcanyon/10/192/401.png + +# map /wmts/layer/[ANYTHING]z/x/y.ext -> /layer/z/x/y.ext (WMTS ignoring tilematrixset,style,..) +# BTW This is used only by Gaia which ignores the +RewriteRule ^wmts/([\w\d\._-]+)/.*?(\d+)/(\d+)/(\d+)\.(\w+)$ $1/$2/$4/$3.$5 [N] +# Example: http://www.tileserver.com/wmts/grandcanyon/style/tilematrixset/10/192/401.png + +# map /layer/[ANYTHING]z/x/y.ext -> /layer/z/x/y.ext (WMTS ignoring tilematrix,style,..) +RewriteCond %{REQUEST_FILENAME} !-f +RewriteRule ^([\w\d\._-]+)/.+?(\d+)/(\d+)/(\d+)\.(\w+)$ $1/$2/$3/$4.$5 [N] +# Example: http://www.tileserver.com/grandcanyon/style/tilematrixset/10/192/401.png + +# rewrite .jpeg -> .jpg +RewriteRule ^(.+).jpeg$ $1.jpg [L] + +# Not modified HTTP 302 +RewriteRule .* - [E=HTTP_IF_MODIFIED_SINCE:%{HTTP:If-Modified-Since}] +RewriteRule .* - [E=HTTP_IF_NONE_MATCH:%{HTTP:If-None-Match}] + +RewriteCond %{REQUEST_FILENAME} !-f +RewriteCond %{REQUEST_FILENAME} !-d +RewriteCond $1 !^(tileserver\.php) +RewriteRule ^(.*)$ tileserver.php?/$1 [L,QSA] \ No newline at end of file diff --git a/tileserver.php b/tileserver.php index 2447b5e..29e67f2 100644 --- a/tileserver.php +++ b/tileserver.php @@ -8,7 +8,7 @@ */ global $config; -$config['serverTitle'] = 'TileServer-php v0.2'; +$config['serverTitle'] = 'TileServer-php v1'; //$config['baseUrls'] = ['t0.server.com', 't1.server.com']; Router::serve(array( @@ -17,13 +17,16 @@ Router::serve(array( '/html' => 'Server:getHtml', '/:string.json' => 'Json:getJson', '/:string.jsonp' => 'Json:getJsonp', - '/:string/:number/:number/:number.grid.json' => 'Json:getUTFGrid', + '/:string/:number/:number/:number.:string.json' => 'Json:getUTFGrid', '/wmts' => 'Wmts:get', - '/wmts/1.0.0/WMTSCapabilities.xml' => 'Wmts:getCapabilities', + '/wmts/1.0.0/WMTSCapabilities.xml' => 'Wmts:get', + '/wmts/:string/:number/:number/:number.:string' => 'Wmts:getTile', + '/wmts/:string/:string/:number/:number/:number.:string' => 'Wmts:getTile', + '/wmts/:string/:string/:string/:number/:number/:number.:string' => 'Wmts:getTile', '/:string/:number/:number/:number.:string' => 'Wmts:getTile', '/tms' => 'Tms:getCapabilities', '/tms/:string' => 'Tms:getLayerCapabilities', - )); +)); /** * Server base @@ -31,7 +34,7 @@ Router::serve(array( class Server { /** - * Configuration of TileServer [baseUrls, serverTitle, host] + * Configuration of TileServer [baseUrls, serverTitle] * @var array */ public $config; @@ -54,7 +57,7 @@ class Server { */ public $db; - /** + /** * Set config */ public function __construct() { @@ -72,22 +75,14 @@ class Server { $layer = $this->metadataFromMetadataJson($mj); array_push($this->fileLayer, $layer); } - } else { - $e = 1; } if ($mbts) { foreach ($mbts as $mbt) { $this->dbLayer[] = $this->metadataFromMbtiles($mbt); } - } else { - $e = 1; } -// if (isset($e)) { -// echo 'Server: No JSON or MBtiles file with metadata'; -// die; -// } } - + /** * Processing params from router ////.ext * @param array $params @@ -96,13 +91,14 @@ class Server { if (isset($params[1])) { $this->layer = $params[1]; } - if (isset($params[2])) { - $this->z = $params[2]; - $this->x = $params[3]; - $this->y = $params[4]; + $params = array_reverse($params); + if (isset($params[3])) { + $this->z = $params[3]; + $this->x = $params[2]; + $this->y = $params[1]; } - if (isset($params[5])) { - $this->ext = $params[5]; + if (isset($params[0])) { + $this->ext = $params[0]; } } @@ -114,7 +110,7 @@ class Server { public function getGlobal($isKey) { $get = $_GET; foreach ($get as $key => $value) { - if(strtolower($isKey) == strtolower($key)){ + if (strtolower($isKey) == strtolower($key)) { return $value; } } @@ -127,9 +123,9 @@ class Server { * @return boolean */ public function isDBLayer($layer) { - if(is_file($layer.'.mbtiles')){ + if (is_file($layer . '.mbtiles')) { return TRUE; - } else { + } else { return FALSE; } } @@ -140,9 +136,9 @@ class Server { * @return boolean */ public function isFileLayer($layer) { - if(is_dir($layer)){ + if (is_dir($layer)) { return TRUE; - } else { + } else { return FALSE; } } @@ -230,7 +226,7 @@ class Server { if (!isset($this->db)) { header('Content-type: text/plain'); echo 'Incorrect tileset name: ' . $tileset; - exit; + die; } } @@ -289,7 +285,7 @@ class Server { echo $data; } } elseif ($this->isFileLayer($tileset)) { - $name = './' . $tileset . '/' . $z . '/' . $y . '/' . $x . '.' . $ext; + $name = './' . $tileset . '/' . $z . '/' . $x . '/' . $y . '.' . $ext; if ($fp = @fopen($name, 'rb')) { header('Content-Type: image/' . $ext); header('Content-Length: ' . filesize($name)); @@ -324,20 +320,24 @@ class Server { * @param integer $y * @param integer $x */ - public function getUTFGrid($tileset, $z, $y, $x) { + public function getUTFGrid($tileset, $z, $y, $x, $flip = TRUE) { if ($this->isDBLayer($tileset)) { if ($this->isModified($tileset) == TRUE) { header('HTTP/1.1 304 Not Modified'); } - $this->DBconnect($tileset . '.mbtiles'); + if ($flip) { + $y = pow(2, $z) - 1 - $y; + } try { + $this->DBconnect($tileset . '.mbtiles'); $result = $this->db->query('SELECT grid FROM grids WHERE tile_column = ' . $x . ' AND tile_row = ' . $y . ' AND zoom_level = ' . $z); - $data = $result->fetchColumn(); - if (!isset($data) || $data === FALSE) { + if (!isset($result) || $result === FALSE) { header('Access-Control-Allow-Origin: *'); - echo 'grid({});'; + echo 'grid({error});'; die; } else { + $data = $result->fetchColumn(); + $grid = gzuncompress($data); $grid = substr(trim($grid), 0, -1); @@ -375,6 +375,10 @@ class Server { $maps = array_merge($this->fileLayer, $this->dbLayer); header('Content-Type: text/html;charset=UTF-8'); echo '' . $this->config['serverTitle'] . ''; + echo '

' . $this->config['serverTitle'] . '

'; + echo 'TileJSON service: ' . $this->config['baseUrls'][0] . '/index.json
'; + echo 'WMTS service: ' . $this->config['baseUrls'][0] . '/wmts
'; + echo 'TMS service: ' . $this->config['baseUrls'][0] . '/tms'; foreach ($maps as $map) { $extend = '['; foreach ($map['bounds'] as $ext) { @@ -386,8 +390,11 @@ class Server { } else { echo '

Available file tileset: ' . $map['basename'] . '
'; } + echo 'Metadata: ' + . $this->config['baseUrls'][0] . '/' . $map['basename'] . '.json
'; echo 'Bounds: ' . $extend . '

'; } + echo '

Copyright (C) 2014 - Klokan Technologies GmbH

'; echo ''; } @@ -401,7 +408,7 @@ class Server { echo '' . $this->config['serverTitle'] . ''; echo ' - +

Welcome to ' . $this->config['serverTitle'] . '

This server distributes maps to desktop, web, and mobile applications.

The mapping data are available as OpenGIS Web Map Tiling Service (OGC WMTS), OSGEO Tile Map Service (TMS), and popular XYZ urls described with TileJSON metadata.

'; @@ -484,10 +491,10 @@ class Json extends Server { $tiles[] = 'http://' . $url . '/' . $metadata['basename'] . '/{z}/{x}/{y}.' . $metadata['format']; } $metadata['tiles'] = $tiles; - if($this->isDBLayer($metadata['basename'])){ - $this->DBconnect($metadata['basename'].'.mbtiles'); + if ($this->isDBLayer($metadata['basename'])) { + $this->DBconnect($metadata['basename'] . '.mbtiles'); $res = $this->db->query('SELECT grid FROM grids LIMIT 1'); - if($res){ + if ($res) { foreach ($this->config['baseUrls'] as $url) { $grids[] = 'http://' . $url . '/' . $metadata['basename'] . '/{z}/{x}/{y}.grid.json'; } @@ -602,11 +609,11 @@ class Wmts extends Server { /** * Tests request from url and call method */ - public function get(){ + public function get() { $request = $this->getGlobal('Request'); - if($request !== FALSE && $request == 'gettile'){ + if ($request !== FALSE && $request == 'gettile') { $this->getTile(); - }else{ + } else { parent::setDatasets(); $this->getCapabilities(); } @@ -617,11 +624,11 @@ class Wmts extends Server { */ public function getCapabilities() { header("Content-type: application/xml"); - echo ''; - echo ' + echo ' + - ' . $this->config['serverTitle'] . ' + tileserverphp OGC WMTS 1.0.0 @@ -651,7 +658,7 @@ class Wmts extends Server { - + RESTful @@ -691,10 +698,11 @@ class Wmts extends Server { list( $maxx, $maxy ) = $mercator->LatLonToMeters($bounds[3], $bounds[2]); $bounds3857 = array($minx, $miny, $maxx, $maxy); } - echo' + echo' + ' . $title . ' - ' . $basename . ''; - echo ' + ' . $basename . ' + ' . $bounds[0] . ' ' . $bounds[1] . ' ' . $bounds[2] . ' ' . $bounds[3] . ' @@ -706,12 +714,13 @@ class Wmts extends Server { ' . $tileMatrixSet . ' + . $this->config['baseUrls'][0] . '/wmts/' . $basename . '/{TileMatrixSet}/{TileMatrix}/{TileCol}/{TileRow}.' . $format . '"/> '; } - echo ' + echo ' + GoogleMapsCompatible - the wellknown "GoogleMapsCompatible" tile matrix set defined by OGC WMTS specification + the wellknown \'GoogleMapsCompatible\' tile matrix set defined by OGC WMTS specification GoogleMapsCompatible urn:ogc:def:crs:EPSG:6.18:3:3857 urn:ogc:def:wkss:OGC:1.0:GoogleMapsCompatible @@ -1338,7 +1347,7 @@ class Router { /** * @param array $routes */ - public static function serve($routes) { + public static function serve($routes) { $request_method = strtolower($_SERVER['REQUEST_METHOD']); $path_info = '/'; if (!empty($_SERVER['PATH_INFO'])) { @@ -1352,7 +1361,7 @@ class Router { } $discovered_handler = null; $regex_matches = array(); - + if ($routes) { $tokens = array( ':string' => '([a-zA-Z]+)', @@ -1363,8 +1372,8 @@ class Router { foreach ($routes as $pattern => $handler_name) { $pattern = strtr($pattern, $tokens); if (preg_match('#/?' . $pattern . '/?$#', $path_info, $matches)) { - if(!isset($config['baseUrls'])){ - $config['baseUrls'][0] = $_SERVER['HTTP_HOST'].preg_replace('#/?'.$pattern.'/?$#', '', $path_info); + if (!isset($config['baseUrls'])) { + $config['baseUrls'][0] = $_SERVER['HTTP_HOST'] . preg_replace('#/?' . $pattern . '/?$#', '', $path_info); } $discovered_handler = $handler_name; $regex_matches = $matches; @@ -1387,7 +1396,8 @@ class Router { $handler_instance = $discovered_handler(); } } else { - echo 'Router: No route'; die; + echo 'Router: No route'; + die; //$handler_instance = new Server; //$handler_instance->getHtml(); } From 4d6ee2c714dbab5ca6526b418e3e0462593f6ca8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Jan=C3=A1k?= Date: Mon, 28 Apr 2014 14:24:25 +0200 Subject: [PATCH 12/21] Problems with response speed have been fixed. --- tileserver.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tileserver.php b/tileserver.php index 29e67f2..e232a0f 100644 --- a/tileserver.php +++ b/tileserver.php @@ -238,7 +238,7 @@ class Server { public function isModified($filename) { $filename = $filename . '.mbtiles'; $lastModifiedTime = filemtime($filename); - $eTag = md5_file($filename); + $eTag = md5($lastModifiedTime); header("Last-Modified: " . gmdate("D, d M Y H:i:s", $lastModifiedTime) . " GMT"); header("Etag:" . $eTag); if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $lastModifiedTime || @@ -261,6 +261,7 @@ class Server { if ($this->isDBLayer($tileset)) { if ($this->isModified($tileset) == TRUE) { header('HTTP/1.1 304 Not Modified'); + die; } $this->DBconnect($tileset . '.mbtiles'); $z = floatval($z); From 656ffba9df3d313fe1b484614b58b7bd616fcd32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Jan=C3=A1k?= Date: Mon, 28 Apr 2014 16:20:46 +0200 Subject: [PATCH 13/21] Test file deleted. --- testt/.htaccess | 50 ------------------------------------------------- 1 file changed, 50 deletions(-) delete mode 100644 testt/.htaccess diff --git a/testt/.htaccess b/testt/.htaccess deleted file mode 100644 index 9a96f73..0000000 --- a/testt/.htaccess +++ /dev/null @@ -1,50 +0,0 @@ -# tileserver.php integration with Apache via .htaccess - -# Restrictions for data crawlers -Options -Indexes - - Options -MultiViews - - -# Optional CORS header for cross-domain origin access to all data -# -# Header set Access-Control-Allow-Origin * -# - -# Mapping of the WMTS standardized URLs to real files and XML capabilities to tileserver.php - -#check htaccess functionality -DirectoryIndex tileserver.php - -RewriteEngine on - -#some hostings require RewriteBase e.g. 1&1.com -RewriteBase / -#RewriteBase /cosi/ - -# WMTS RESTful -# ------------ -# The file can be accessed directly: -# Example: http://www.tileserver.com/grandcanyon/10/192/401.png - -# map /wmts/layer/[ANYTHING]z/x/y.ext -> /layer/z/x/y.ext (WMTS ignoring tilematrixset,style,..) -# BTW This is used only by Gaia which ignores the -RewriteRule ^wmts/([\w\d\._-]+)/.*?(\d+)/(\d+)/(\d+)\.(\w+)$ $1/$2/$4/$3.$5 [N] -# Example: http://www.tileserver.com/wmts/grandcanyon/style/tilematrixset/10/192/401.png - -# map /layer/[ANYTHING]z/x/y.ext -> /layer/z/x/y.ext (WMTS ignoring tilematrix,style,..) -RewriteCond %{REQUEST_FILENAME} !-f -RewriteRule ^([\w\d\._-]+)/.+?(\d+)/(\d+)/(\d+)\.(\w+)$ $1/$2/$3/$4.$5 [N] -# Example: http://www.tileserver.com/grandcanyon/style/tilematrixset/10/192/401.png - -# rewrite .jpeg -> .jpg -RewriteRule ^(.+).jpeg$ $1.jpg [L] - -# Not modified HTTP 302 -RewriteRule .* - [E=HTTP_IF_MODIFIED_SINCE:%{HTTP:If-Modified-Since}] -RewriteRule .* - [E=HTTP_IF_NONE_MATCH:%{HTTP:If-None-Match}] - -RewriteCond %{REQUEST_FILENAME} !-f -RewriteCond %{REQUEST_FILENAME} !-d -RewriteCond $1 !^(tileserver\.php) -RewriteRule ^(.*)$ tileserver.php?/$1 [L,QSA] \ No newline at end of file From 8478f7dc7d7e5798d56ea51054c0db8a391bdf85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Jan=C3=A1k?= Date: Mon, 28 Apr 2014 16:29:41 +0200 Subject: [PATCH 14/21] WMTS KVP in htaccess --- .htaccess | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/.htaccess b/.htaccess index 82b0d8f..0c76e7e 100644 --- a/.htaccess +++ b/.htaccess @@ -37,6 +37,28 @@ RewriteEngine on #RewriteRule ^([\w\d\._-]+)/.+?(\d+)/(\d+)/(\d+)\.(\w+)$ $1/$2/$3/$4.$5 [N] ## Example: http://www.tileserver.com/grandcanyon/style/tilematrixset/10/192/401.png +## WMTS KVP +## -------- +## map the /?key=value&... -> /layer/z/x/y.ext KVP getTile queries directly to files +# +## format passed as mime-extension, cleaning formats (jpeg->jpg) +#RewriteCond %{QUERY_STRING} ^(.*)format=image/jpeg(.*)$ [NC] +#RewriteRule ^(.*)$ $1?%1format=jpg%2 [N] +#RewriteCond %{QUERY_STRING} ^(.*)format=jpeg(.*)$ [NC] +#RewriteRule ^(.*)$ $1?%1format=jpg%2 [N] +#RewriteCond %{QUERY_STRING} ^(.*)format=image/png(.*)$ [NC] +#RewriteRule ^(.*)$ $1?%1format=png%2 [N] +# +## variable order of keys: TODO: sort the same way as mime-extension to fixed order +#RewriteCond %{QUERY_STRING} ^.*request=gettile.*layer=([\w\d\._-]+).*tilematrix=(\d+).*tilerow=(\d+).*tilecol=(\d+).*format=(\w+).*$ [NC] +#RewriteRule ^ %1/%2/%3/%4.%5 [N] +#RewriteCond %{QUERY_STRING} ^.*request=gettile.*layer=([\w\d\._-]+).*format=(\w+).*tilematrix=(\d+).*tilerow=(\d+).*tilecol=(\d+).*$ [NC] +#RewriteRule ^ %1/%3/%5/%4.%2 [N] +#RewriteCond %{QUERY_STRING} ^.*request=gettile.*layer=([\w\d\._-]+).*tilematrix=(\d+).*tilecol=(\d+).*tilerow=(\d+).*format=(\w+).*$ [NC] +#RewriteRule ^ %1/%2/%4/%3.%5 [N] +## Example: http://www.tileserver.com/wmts?request=getTile&layer=grandcanyon&tileMatrix=10&tilerow=192&tilecol=401&format=png +## Example: http://www.tileserver.com/wmts?service=WMTS&request=GetTile&version=1.0.0&layer=ne2geo&style=&format=image/jpeg&TileMatrixSet=WGS84&TileMatrix=1&TileRow=2&TileCol=2 + # rewrite .jpeg -> .jpg RewriteRule ^(.+).jpeg$ $1.jpg [L] From 3042384d13863195c01206d4a1d1b575590852eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Jan=C3=A1k?= Date: Mon, 28 Apr 2014 17:34:38 +0200 Subject: [PATCH 15/21] Options object passed to the constructor for tileserver-js. --- tileserver.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tileserver.php b/tileserver.php index e232a0f..b81be2d 100644 --- a/tileserver.php +++ b/tileserver.php @@ -409,7 +409,7 @@ class Server { echo '' . $this->config['serverTitle'] . ''; echo ' - +

Welcome to ' . $this->config['serverTitle'] . '

This server distributes maps to desktop, web, and mobile applications.

The mapping data are available as OpenGIS Web Map Tiling Service (OGC WMTS), OSGEO Tile Map Service (TMS), and popular XYZ urls described with TileJSON metadata.

'; From c953b0cecb7339f8eb231e587df34a7f7bf3a6af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Jan=C3=A1k?= Date: Tue, 29 Apr 2014 09:22:19 +0200 Subject: [PATCH 16/21] Empty index.json missing [ #22 --- tileserver.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tileserver.php b/tileserver.php index b81be2d..0aa1fe2 100644 --- a/tileserver.php +++ b/tileserver.php @@ -517,7 +517,11 @@ class Json extends Server { foreach ($maps as $map) { $output = $output . json_encode($this->metadataTileJson($map)) . ','; } - $output = substr_replace($output, ']', -1); + if(strlen($output) > 1){ + $output = substr_replace($output, ']', -1); + }else{ + $output = $output.']'; + } } else { foreach ($maps as $map) { if (strpos($map['basename'], $basename) !== false) { From 4cd86eefc37c9c3be86d7e0a7ec6e78199815955 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Jan=C3=A1k?= Date: Thu, 1 May 2014 10:25:33 +0200 Subject: [PATCH 17/21] TileJSON url passed to the constructor closes #24 --- tileserver.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tileserver.php b/tileserver.php index 0aa1fe2..0c56fdf 100644 --- a/tileserver.php +++ b/tileserver.php @@ -409,7 +409,7 @@ class Server { echo '' . $this->config['serverTitle'] . ''; echo ' - +

Welcome to ' . $this->config['serverTitle'] . '

This server distributes maps to desktop, web, and mobile applications.

The mapping data are available as OpenGIS Web Map Tiling Service (OGC WMTS), OSGEO Tile Map Service (TMS), and popular XYZ urls described with TileJSON metadata.

'; @@ -517,10 +517,10 @@ class Json extends Server { foreach ($maps as $map) { $output = $output . json_encode($this->metadataTileJson($map)) . ','; } - if(strlen($output) > 1){ + if (strlen($output) > 1) { $output = substr_replace($output, ']', -1); - }else{ - $output = $output.']'; + } else { + $output = $output . ']'; } } else { foreach ($maps as $map) { @@ -1405,7 +1405,7 @@ class Router { die; //$handler_instance = new Server; //$handler_instance->getHtml(); + } } - } } From cd5cd44e759ae12681e368e9bd17ea10250c94bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Jan=C3=A1k?= Date: Mon, 19 May 2014 17:55:00 +0200 Subject: [PATCH 18/21] Some changes of router for better running without htaccess. --- tileserver.php | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/tileserver.php b/tileserver.php index 0c56fdf..6fa706b 100644 --- a/tileserver.php +++ b/tileserver.php @@ -1359,6 +1359,9 @@ class Router { $path_info = $_SERVER['PATH_INFO']; } else if (!empty($_SERVER['ORIG_PATH_INFO']) && $_SERVER['ORIG_PATH_INFO'] !== '/tileserver.php') { $path_info = $_SERVER['ORIG_PATH_INFO']; + } else if (!empty($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'],'/tileserver.php') !== false) { + $path_info = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; + $config['baseUrls'][0] = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '?'; } else { if (!empty($_SERVER['REQUEST_URI'])) { $path_info = (strpos($_SERVER['REQUEST_URI'], '?') > 0) ? strstr($_SERVER['REQUEST_URI'], '?', true) : $_SERVER['REQUEST_URI']; @@ -1401,11 +1404,12 @@ class Router { $handler_instance = $discovered_handler(); } } else { - echo 'Router: No route'; - die; - //$handler_instance = new Server; - //$handler_instance->getHtml(); + if(!isset($config['baseUrls'][0])){ + $config['baseUrls'][0] = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '?'; } + $handler_instance = new Server; + $handler_instance->getHtml(); } + } } From ed5618886f1d1b5344caaeed56e0aeaad68e30c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Jan=C3=A1k?= Date: Mon, 19 May 2014 18:01:11 +0200 Subject: [PATCH 19/21] In file names are not allowed numbers. --- tileserver.php | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/tileserver.php b/tileserver.php index 6fa706b..3413256 100644 --- a/tileserver.php +++ b/tileserver.php @@ -15,17 +15,17 @@ Router::serve(array( '/' => 'Server:getHtml', '/test' => 'Server:getInfo', '/html' => 'Server:getHtml', - '/:string.json' => 'Json:getJson', - '/:string.jsonp' => 'Json:getJsonp', - '/:string/:number/:number/:number.:string.json' => 'Json:getUTFGrid', + '/:alpha.json' => 'Json:getJson', + '/:alpha.jsonp' => 'Json:getJsonp', + '/:alpha/:number/:number/:number.:alpha.json' => 'Json:getUTFGrid', '/wmts' => 'Wmts:get', '/wmts/1.0.0/WMTSCapabilities.xml' => 'Wmts:get', - '/wmts/:string/:number/:number/:number.:string' => 'Wmts:getTile', - '/wmts/:string/:string/:number/:number/:number.:string' => 'Wmts:getTile', - '/wmts/:string/:string/:string/:number/:number/:number.:string' => 'Wmts:getTile', - '/:string/:number/:number/:number.:string' => 'Wmts:getTile', + '/wmts/:alpha/:number/:number/:number.:alpha' => 'Wmts:getTile', + '/wmts/:alpha/:alpha/:number/:number/:number.:alpha' => 'Wmts:getTile', + '/wmts/:alpha/:alpha/:alpha/:number/:number/:number.:alpha' => 'Wmts:getTile', + '/:alpha/:number/:number/:number.:alpha' => 'Wmts:getTile', '/tms' => 'Tms:getCapabilities', - '/tms/:string' => 'Tms:getLayerCapabilities', + '/tms/:alpha' => 'Tms:getLayerCapabilities', )); /** From cba3048506f3b8a72971161564d526f35b0513ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Jan=C3=A1k?= Date: Mon, 19 May 2014 18:58:54 +0200 Subject: [PATCH 20/21] Issue Malformed UTFGrid (?) fixed. Fixes #26 --- tileserver.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tileserver.php b/tileserver.php index 3413256..d120f4f 100644 --- a/tileserver.php +++ b/tileserver.php @@ -334,7 +334,7 @@ class Server { $result = $this->db->query('SELECT grid FROM grids WHERE tile_column = ' . $x . ' AND tile_row = ' . $y . ' AND zoom_level = ' . $z); if (!isset($result) || $result === FALSE) { header('Access-Control-Allow-Origin: *'); - echo 'grid({error});'; + echo '{}'; die; } else { $data = $result->fetchColumn(); @@ -350,12 +350,13 @@ class Server { } $grid = rtrim($grid, ',') . '}}'; header('Access-Control-Allow-Origin: *'); - if (isset($_GET['callback'])) { + + if (isset($_GET['callback']) && !empty($_GET['callback'])) { header("Content-Type:text/javascript charset=utf-8"); echo $_GET['callback'] . '(' . $grid . ');'; } else { header("Content-Type:text/javascript; charset=utf-8"); - echo 'grid(' . $grid . ');'; + echo $grid; } } } catch (PDOException $e) { From 08b77f4bf403ab606f857bf426a1bc3866644467 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dalibor=20Jan=C3=A1k?= Date: Mon, 19 May 2014 19:47:11 +0200 Subject: [PATCH 21/21] Tileserver-php now running without .htaccess "Fixes #23" --- tileserver.php | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/tileserver.php b/tileserver.php index d120f4f..32af253 100644 --- a/tileserver.php +++ b/tileserver.php @@ -242,7 +242,7 @@ class Server { header("Last-Modified: " . gmdate("D, d M Y H:i:s", $lastModifiedTime) . " GMT"); header("Etag:" . $eTag); if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $lastModifiedTime || - trim($_SERVER['HTTP_IF_NONE_MATCH']) == $eTag) { + @trim($_SERVER['HTTP_IF_NONE_MATCH']) == $eTag) { return TRUE; } else { return FALSE; @@ -350,7 +350,7 @@ class Server { } $grid = rtrim($grid, ',') . '}}'; header('Access-Control-Allow-Origin: *'); - + if (isset($_GET['callback']) && !empty($_GET['callback'])) { header("Content-Type:text/javascript charset=utf-8"); echo $_GET['callback'] . '(' . $grid . ');'; @@ -546,9 +546,9 @@ class Json extends Server { header('Access-Control-Allow-Origin: *'); header("Content-Type:application/javascript charset=utf-8"); if ($this->callback !== 'grid') { - echo $this->callback . '(' . $this->createJson($this->layer) . ');'; + echo $this->callback . '(' . $this->createJson($this->layer) . ');'; die; } else { - echo $this->createJson($this->layer); + echo $this->createJson($this->layer); die; } } @@ -1360,7 +1360,7 @@ class Router { $path_info = $_SERVER['PATH_INFO']; } else if (!empty($_SERVER['ORIG_PATH_INFO']) && $_SERVER['ORIG_PATH_INFO'] !== '/tileserver.php') { $path_info = $_SERVER['ORIG_PATH_INFO']; - } else if (!empty($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'],'/tileserver.php') !== false) { + } else if (!empty($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '/tileserver.php') !== false) { $path_info = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; $config['baseUrls'][0] = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '?'; } else { @@ -1405,8 +1405,15 @@ class Router { $handler_instance = $discovered_handler(); } } else { - if(!isset($config['baseUrls'][0])){ - $config['baseUrls'][0] = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '?'; + if (!isset($config['baseUrls'][0])) { + $config['baseUrls'][0] = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '?'; + } + if (strpos($_SERVER['REQUEST_URI'], '=') != FALSE) { + $kvp = explode('=', $_SERVER['REQUEST_URI']); + $_GET['callback'] = $kvp[1]; + $params[0] = 'index'; + $handler_instance = new Json($params); + $handler_instance->getJson(); } $handler_instance = new Server; $handler_instance->getHtml();