source: src/webapp/webservice/tileserver.php@ 654b10c

0.5 debian/bullseye debian/jessie
Last change on this file since 654b10c was f03591a, checked in by Joachim Langenbach <joachim.langenbach@…>, 9 years ago
  • Improved webclient file uploading
  • Improvded webservice
    • Map uploading
    • tileserver searches it's maps under maps now
  • Maps have spoken names now (set by the user during upload)
  • Moved to leaflet 1.1.0
  • Property mode set to 100644
File size: 41.6 KB
Line 
1<?php
2
3/*
4 * TileServer.php project
5 * ======================
6 * https://github.com/klokantech/tileserver-php/
7 * Copyright (C) 2016 - Klokan Technologies GmbH
8 */
9
10global $config;
11$config['serverTitle'] = 'GNUBoat Tileserver';
12$config['availableFormats'] = array('png', 'jpg', 'jpeg', 'gif', 'webp', 'pbf', 'hybrid');
13//$config['template'] = 'template.php';
14$config['baseUrls'] = array('../webservice');
15$config['mapDir'] = "maps";
16
17Router::serve(array(
18 '/' => 'Server:getHtml',
19 '/maps' => 'Server:getInfo',
20 '/html' => 'Server:getHtml',
21 '/:alpha/:number/:number/:number.grid.json' => 'Json:getUTFGrid',
22 '/:alpha.json' => 'Json:getJson',
23 '/:alpha.jsonp' => 'Json:getJsonp',
24 '/wmts' => 'Wmts:get',
25 '/wmts/1.0.0/WMTSCapabilities.xml' => 'Wmts:get',
26 '/wmts/:alpha/:number/:number/:alpha' => 'Wmts:getTile',
27 '/wmts/:alpha/:alpha/:number/:number/:alpha' => 'Wmts:getTile',
28 '/wmts/:alpha/:alpha/:alpha/:number/:number/:alpha' => 'Wmts:getTile',
29 '/:alpha/:number/:number/:alpha' => 'Wmts:getTile',
30 '/tms' => 'Tms:getCapabilities',
31 '/tms/:alpha' => 'Tms:getLayerCapabilities',
32));
33
34/**
35 * Server base
36 */
37class Server {
38
39 /**
40 * Configuration of TileServer [baseUrls, serverTitle]
41 * @var array
42 */
43 public $config;
44
45 /**
46 * Datasets stored in file structure
47 * @var array
48 */
49 public $fileLayer = array();
50
51 /**
52 * Datasets stored in database
53 * @var array
54 */
55 public $dbLayer = array();
56
57 /**
58 * PDO database connection
59 * @var object
60 */
61 public $db;
62
63 /**
64 * Set config
65 */
66 public function __construct() {
67 $this->config = $GLOBALS['config'];
68
69 //Get config from enviroment
70 $envServerTitle = getenv('serverTitle');
71 if($envServerTitle !== FALSE){
72 $this->config['serverTitle'] = $envServerTitle;
73 }
74 $envBaseUrls = getenv('baseUrls');
75 if($envBaseUrls !== FALSE){
76 $this->config['baseUrls'] = is_array($envBaseUrls) ?
77 $envBaseUrls : explode(',', $envBaseUrls);
78 }
79 $envTemplate = getenv('template');
80 if($envBaseUrls !== FALSE){
81 $this->config['template'] = $envTemplate;
82 }
83 }
84
85 /**
86 * Looks for datasets
87 */
88 public function setDatasets() {
89 $mjs = glob('*/metadata.json');
90 $mbts = glob($this->config['mapDir'] .'/*.mbtiles');
91 if ($mjs) {
92 foreach (array_filter($mjs, 'is_readable') as $mj) {
93 $layer = $this->metadataFromMetadataJson($mj);
94 array_push($this->fileLayer, $layer);
95 }
96 }
97 if ($mbts) {
98 foreach (array_filter($mbts, 'is_readable') as $mbt) {
99 $this->dbLayer[] = $this->metadataFromMbtiles($mbt);
100 }
101 }
102 }
103
104 /**
105 * Processing params from router <server>/<layer>/<z>/<x>/<y>.ext
106 * @param array $params
107 */
108 public function setParams($params) {
109 if (isset($params[1])) {
110 $this->layer = $params[1];
111 }
112 $params = array_reverse($params);
113 if (isset($params[2])) {
114 $this->z = $params[2];
115 $this->x = $params[1];
116 $file = explode('.', $params[0]);
117 $this->y = $file[0];
118 $this->ext = isset($file[1]) ? $file[1] : NULL;
119 }
120 }
121
122 /**
123 * Get variable don't independent on sensitivity
124 * @param string $key
125 * @return boolean
126 */
127 public function getGlobal($isKey) {
128 $get = $_GET;
129 foreach ($get as $key => $value) {
130 if (strtolower($isKey) == strtolower($key)) {
131 return $value;
132 }
133 }
134 return FALSE;
135 }
136
137 /**
138 * Testing if is a database layer
139 * @param string $layer
140 * @return boolean
141 */
142 public function isDBLayer($layer) {
143 if (is_file($this->config["mapDir"] ."/". $layer . '.mbtiles')) {
144 return TRUE;
145 } else {
146 return FALSE;
147 }
148 }
149
150 /**
151 * Testing if is a file layer
152 * @param string $layer
153 * @return boolean
154 */
155 public function isFileLayer($layer) {
156 if (is_dir($layer)) {
157 return TRUE;
158 } else {
159 return FALSE;
160 }
161 }
162
163 /**
164 * Get metadata from metadataJson
165 * @param string $jsonFileName
166 * @return array
167 */
168 public function metadataFromMetadataJson($jsonFileName) {
169 $metadata = json_decode(file_get_contents($jsonFileName), true);
170 $metadata['basename'] = str_replace('/metadata.json', '', $jsonFileName);
171 return $this->metadataValidation($metadata);
172 }
173
174 /**
175 * Loads metadata from MBtiles
176 * @param string $mbt
177 * @return object
178 */
179 public function metadataFromMbtiles($mbt) {
180 $metadata = array();
181 $this->DBconnect($mbt);
182 $result = $this->db->query('select * from metadata');
183
184 $resultdata = $result->fetchAll();
185 foreach ($resultdata as $r) {
186 $value = preg_replace('/(\\n)+/', '', $r['value']);
187 $metadata[$r['name']] = addslashes($value);
188 }
189 if (!array_key_exists('minzoom', $metadata)
190 || !array_key_exists('maxzoom', $metadata)
191 ) {
192 // autodetect minzoom and maxzoom
193 $result = $this->db->query('select min(zoom_level) as min, max(zoom_level) as max from tiles');
194 $resultdata = $result->fetchAll();
195 if (!array_key_exists('minzoom', $metadata)){
196 $metadata['minzoom'] = $resultdata[0]['min'];
197 }
198 if (!array_key_exists('maxzoom', $metadata)){
199 $metadata['maxzoom'] = $resultdata[0]['max'];
200 }
201 }
202 // autodetect format using JPEG magic number FFD8
203 if (!array_key_exists('format', $metadata)) {
204 $result = $this->db->query('select hex(substr(tile_data,1,2)) as magic from tiles limit 1');
205 $resultdata = $result->fetchAll();
206 $metadata['format'] = ($resultdata[0]['magic'] == 'FFD8')
207 ? 'jpg'
208 : 'png';
209 }
210 // autodetect bounds
211 if (!array_key_exists('bounds', $metadata)) {
212 $result = $this->db->query('select min(tile_column) as w, max(tile_column) as e, min(tile_row) as s, max(tile_row) as n from tiles where zoom_level='.$metadata['maxzoom']);
213 $resultdata = $result->fetchAll();
214 $w = -180 + 360 * ($resultdata[0]['w'] / pow(2, $metadata['maxzoom']));
215 $e = -180 + 360 * ((1 + $resultdata[0]['e']) / pow(2, $metadata['maxzoom']));
216 $n = $this->row2lat($resultdata[0]['n'], $metadata['maxzoom']);
217 $s = $this->row2lat($resultdata[0]['s'] - 1, $metadata['maxzoom']);
218 $metadata['bounds'] = implode(',', array($w, $s, $e, $n));
219 }
220 $mbt = explode('.', $mbt);
221 $metadata['basename'] = $mbt[0];
222 $metadata = $this->metadataValidation($metadata);
223 return $metadata;
224 }
225
226 /**
227 * Convert row number to latitude of the top of the row
228 * @param integer $r
229 * @param integer $zoom
230 * @return integer
231 */
232 public function row2lat($r, $zoom) {
233 $y = $r / pow(2, $zoom - 1 ) - 1;
234 return rad2deg(2.0 * atan(exp(3.191459196 * $y)) - 1.57079632679489661922);
235 }
236
237 /**
238 * Valids metaJSON
239 * @param object $metadata
240 * @return object
241 */
242 public function metadataValidation($metadata) {
243 if (!array_key_exists('bounds', $metadata)) {
244 $metadata['bounds'] = array(-180, -85.06, 180, 85.06);
245 } elseif (!is_array($metadata['bounds'])) {
246 $metadata['bounds'] = array_map('floatval', explode(',', $metadata['bounds']));
247 }
248 if (!array_key_exists('profile', $metadata)) {
249 $metadata['profile'] = 'mercator';
250 }
251 if (array_key_exists('minzoom', $metadata)){
252 $metadata['minzoom'] = intval($metadata['minzoom']);
253 }else{
254 $metadata['minzoom'] = 0;
255 }
256 if (array_key_exists('maxzoom', $metadata)){
257 $metadata['maxzoom'] = intval($metadata['maxzoom']);
258 }else{
259 $metadata['maxzoom'] = 18;
260 }
261 if (!array_key_exists('format', $metadata)) {
262 if(array_key_exists('tiles', $metadata)){
263 $pos = strrpos($metadata['tiles'][0], '.');
264 $metadata['format'] = trim(substr($metadata['tiles'][0], $pos + 1));
265 }
266 }
267 $formats = $this->config['availableFormats'];
268 if(!in_array(strtolower($metadata['format']), $formats)){
269 $metadata['format'] = 'png';
270 }
271 if (!array_key_exists('scale', $metadata)) {
272 $metadata['scale'] = 1;
273 }
274 if(!array_key_exists('tiles', $metadata)){
275 $tiles = array();
276 foreach ($this->config['baseUrls'] as $url) {
277 $url = '' . $this->config['protocol'] . '://' . $url . '/' .
278 $metadata['basename'] . '/{z}/{x}/{y}';
279 if(strlen($metadata['format']) <= 4){
280 $url .= '.' . $metadata['format'];
281 }
282 $tiles[] = $url;
283 }
284 $metadata['tiles'] = $tiles;
285 }
286 return $metadata;
287 }
288
289 /**
290 * SQLite connection
291 * @param string $tileset
292 */
293 public function DBconnect($tileset) {
294 try {
295 $this->db = new PDO('sqlite:' . $tileset, '', '', array(PDO::ATTR_PERSISTENT => true));
296 } catch (Exception $exc) {
297 error_log($exc->getTraceAsString());
298 die;
299 }
300
301 if (!isset($this->db)) {
302 header('Content-type: text/plain');
303 error_log('Incorrect tileset name: ' . $tileset);
304 die;
305 }
306 }
307
308 /**
309 * Check if file is modified and set Etag headers
310 * @param string $filename
311 * @return boolean
312 */
313 public function isModified($filename) {
314 $filename = $this->config["mapDir"] ."/". $filename . '.mbtiles';
315 $lastModifiedTime = filemtime($filename);
316 $eTag = md5($lastModifiedTime);
317 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastModifiedTime) . ' GMT');
318 header('Etag:' . $eTag);
319 if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $lastModifiedTime ||
320 @trim($_SERVER['HTTP_IF_NONE_MATCH']) == $eTag) {
321 return TRUE;
322 } else {
323 return FALSE;
324 }
325 }
326
327 /**
328 * Returns tile of dataset
329 * @param string $tileset
330 * @param integer $z
331 * @param integer $y
332 * @param integer $x
333 * @param string $ext
334 */
335 public function renderTile($tileset, $z, $y, $x, $ext) {
336 if ($this->isDBLayer($tileset)) {
337 if ($this->isModified($tileset) == TRUE) {
338 header('Access-Control-Allow-Origin: *');
339 header('HTTP/1.1 304 Not Modified');
340 die;
341 }
342 $this->DBconnect($this->config["mapDir"] ."/". $tileset . '.mbtiles');
343 $z = floatval($z);
344 $y = floatval($y);
345 $x = floatval($x);
346 $flip = true;
347 if ($flip) {
348 $y = pow(2, $z) - 1 - $y;
349 }
350 $result = $this->db->query('select tile_data as t from tiles where zoom_level=' . $z . ' and tile_column=' . $x . ' and tile_row=' . $y);
351 $data = $result->fetchColumn();
352 if (!isset($data) || $data === FALSE) {
353 //if tile doesn't exist
354 //select scale of tile (for retina tiles)
355 $result = $this->db->query('select value from metadata where name="scale"');
356 $resultdata = $result->fetchColumn();
357 $scale = isset($resultdata) && $resultdata !== FALSE ? $resultdata : 1;
358 $this->getCleanTile($scale, $ext);
359 } else {
360 $result = $this->db->query('select value from metadata where name="format"');
361 $resultdata = $result->fetchColumn();
362 $format = isset($resultdata) && $resultdata !== FALSE ? $resultdata : 'png';
363 if ($format == 'jpg') {
364 $format = 'jpeg';
365 }
366 if ($format == 'pbf') {
367 header('Content-type: application/x-protobuf');
368 header('Content-Encoding:gzip');
369 } else {
370 header('Content-type: image/' . $format);
371 }
372 header('Access-Control-Allow-Origin: *');
373 echo $data;
374 }
375 } elseif ($this->isFileLayer($tileset)) {
376 $name = './' . $tileset . '/' . $z . '/' . $x . '/' . $y;
377 $mime = 'image/';
378 if($ext != NULL){
379 $name .= '.' . $ext;
380 }
381 if ($fp = @fopen($name, 'rb')) {
382 if($ext != NULL){
383 $mime .= $ext;
384 }else{
385 //detect image type from file
386 $mimetypes = array('gif', 'jpeg', 'png');
387 $mime .= $mimetypes[exif_imagetype($name) - 1];
388 }
389 header('Access-Control-Allow-Origin: *');
390 header('Content-Type: ' . $mime);
391 header('Content-Length: ' . filesize($name));
392 fpassthru($fp);
393 die;
394 } else {
395 //scale of tile (for retina tiles)
396 $meta = json_decode(file_get_contents($tileset . '/metadata.json'));
397 if(!isset($meta->scale)){
398 $meta->scale = 1;
399 }
400 }
401 $this->getCleanTile($meta->scale, $ext);
402 } else {
403 header('HTTP/1.1 404 Not Found');
404 error_log('Server: Unknown or not specified dataset "' . $tileset . '"');
405 die;
406 }
407 }
408
409 /**
410 * Returns clean tile
411 * @param integer $scale Default 1
412 */
413 public function getCleanTile($scale = 1, $format = 'png') {
414 switch ($format) {
415 case 'pbf':
416 header('HTTP/1.1 404 Not Found');
417 header('Content-Type: application/json; charset=utf-8');
418 echo '{"message":"Tile does not exist"}';
419 break;
420 case 'webp':
421 header('Access-Control-Allow-Origin: *');
422 header('Content-type: image/webp');
423 echo base64_decode('UklGRhIAAABXRUJQVlA4TAYAAAAvQWxvAGs=');
424 break;
425 case 'jpg':
426 header('Access-Control-Allow-Origin: *');
427 header('Content-type: image/jpg');
428 echo base64_decode('/9j/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/yQALCAABAAEBAREA/8wABgAQEAX/2gAIAQEAAD8A0s8g/9k=');
429 break;
430 case 'png':
431 default:
432 header('Access-Control-Allow-Origin: *');
433 header('Content-type: image/png');
434 // 256x256 transparent optimised png tile
435 echo unpack('H', '89504e470d0a1a0a0000000d494844520000010000000100010300000066bc3a2500000003504c5445000000a77a3dda0000000174524e530040e6d8660000001f494441541819edc1010d000000c220fba77e0e37600000000000000000e70221000001f5a2bd040000000049454e44ae426082');
436 break;
437 }
438 die;
439 }
440
441 /**
442 * Returns tile's UTFGrid
443 * @param string $tileset
444 * @param integer $z
445 * @param integer $y
446 * @param integer $x
447 */
448 public function renderUTFGrid($tileset, $z, $y, $x, $flip = TRUE) {
449 if ($this->isDBLayer($tileset)) {
450 if ($this->isModified($tileset) == TRUE) {
451 header('HTTP/1.1 304 Not Modified');
452 }
453 if ($flip) {
454 $y = pow(2, $z) - 1 - $y;
455 }
456 try {
457 $this->DBconnect($this->config["mapDir"] ."/". $tileset . '.mbtiles');
458
459 $query = 'SELECT grid FROM grids WHERE tile_column = ' . $x . ' AND '
460 . 'tile_row = ' . $y . ' AND zoom_level = ' . $z;
461 $result = $this->db->query($query);
462 $data = $result->fetch(PDO::FETCH_ASSOC);
463
464 if ($data !== FALSE) {
465 $grid = gzuncompress($data['grid']);
466 $grid = substr(trim($grid), 0, -1);
467
468 //adds legend (data) to output
469 $grid .= ',"data":{';
470 $kquery = 'SELECT key_name as key, key_json as json FROM grid_data '
471 . 'WHERE zoom_level=' . $z . ' and '
472 . 'tile_column=' . $x . ' and tile_row=' . $y;
473 $result = $this->db->query($kquery);
474 while ($r = $result->fetch(PDO::FETCH_ASSOC)) {
475 $grid .= '"' . $r['key'] . '":' . $r['json'] . ',';
476 }
477 $grid = rtrim($grid, ',') . '}}';
478 header('Access-Control-Allow-Origin: *');
479
480 if (isset($_GET['callback']) && !empty($_GET['callback'])) {
481 header('Content-Type:text/javascript charset=utf-8');
482 echo $_GET['callback'] . '(' . $grid . ');';
483 } else {
484 header('Content-Type:text/javascript; charset=utf-8');
485 echo $grid;
486 }
487 } else {
488 header('Access-Control-Allow-Origin: *');
489 echo '{}';
490 die;
491 }
492 } catch (Exception $e) {
493 header('Content-type: text/plain');
494 print 'Error querying the database: ' . $e->getMessage();
495 }
496 } else {
497 echo 'Server: no MBTiles tileset';
498 die;
499 }
500 }
501
502 /**
503 * Returns server info
504 */
505 public function getInfo() {
506 $this->setDatasets();
507 $maps = array_merge($this->fileLayer, $this->dbLayer);
508 header('Content-Type: text/html;charset=UTF-8');
509 echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>' . $this->config['serverTitle'] . '</title></head><body>' .
510 '<h1>' . $this->config['serverTitle'] . '</h1>' .
511 'TileJSON service: <a href="//' . $this->config['baseUrls'][0] . '/index.json">' . $this->config['baseUrls'][0] . '/index.json</a><br>' .
512 'WMTS service: <a href="//' . $this->config['baseUrls'][0] . '/wmts">' . $this->config['baseUrls'][0] . '/wmts</a><br>' .
513 'TMS service: <a href="//' . $this->config['baseUrls'][0] . '/tms">' . $this->config['baseUrls'][0] . '/tms</a>';
514 foreach ($maps as $map) {
515 $extend = '[' . implode($map['bounds'], ', ') . ']';
516 echo '<p>Tileset: <b>' . $map['basename'] . '</b><br>' .
517 'Metadata: <a href="//' . $this->config['baseUrls'][0] . '/' . $map['basename'] . '.json">' .
518 $this->config['baseUrls'][0] . '/' . $map['basename'] . '.json</a><br>' .
519 'Bounds: ' . $extend ;
520 if(isset($map['crs'])){echo '<br>CRS: ' . $map['crs'];}
521 echo '</p>';
522 }
523 echo '<p>Copyright (C) 2016 - Klokan Technologies GmbH</p>';
524 echo '</body></html>';
525 }
526
527 /**
528 * Returns html viewer
529 */
530 public function getHtml() {
531 $this->setDatasets();
532 $maps = array_merge($this->fileLayer, $this->dbLayer);
533 if (isset($this->config['template']) && file_exists($this->config['template'])) {
534 $baseUrls = $this->config['baseUrls'];
535 $serverTitle = $this->config['serverTitle'];
536 include_once $this->config['template'];
537 } else {
538 header('Content-Type: text/html;charset=UTF-8');
539 echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>' . $this->config['serverTitle'] . '</title>';
540 echo '<link rel="stylesheet" type="text/css" href="//cdn.klokantech.com/tileviewer/v1/index.css" />
541 <script src="//cdn.klokantech.com/tileviewer/v1/index.js"></script><body>
542 <script>tileserver({index:"' . $this->config['protocol'] . '://' . $this->config['baseUrls'][0] . '/index.json", tilejson:"' . $this->config['protocol'] . '://' . $this->config['baseUrls'][0] . '/%n.json", tms:"' . $this->config['protocol'] . '://' . $this->config['baseUrls'][0] . '/tms", wmts:"' . $this->config['protocol'] . '://' . $this->config['baseUrls'][0] . '/wmts"});</script>
543 <h1>Welcome to ' . $this->config['serverTitle'] . '</h1>
544 <p>This server distributes maps to desktop, web, and mobile applications.</p>
545 <p>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.</p>';
546 if (!isset($maps)) {
547 echo '<h3 style="color:darkred;">No maps available yet</h3>
548 <p style="color:darkred; font-style: italic;">
549 Ready to go - just upload some maps into directory:' . getcwd() . '/ on this server.</p>
550 <p>Note: The maps can be a directory with tiles in XYZ format with metadata.json file.<br/>
551 You can easily convert existing geodata (GeoTIFF, ECW, MrSID, etc) to this tile structure with <a href="http://www.maptiler.com">MapTiler Cluster</a> or open-source projects such as <a href="http://www.klokan.cz/projects/gdal2tiles/">GDAL2Tiles</a> or <a href="http://www.maptiler.org/">MapTiler</a> or simply upload any maps in MBTiles format made by <a href="http://www.tilemill.com/">TileMill</a>. Helpful is also the <a href="https://github.com/mapbox/mbutil">mbutil</a> tool. Serving directly from .mbtiles files is supported, but with decreased performance.</p>';
552 } else {
553 echo '<ul>';
554 foreach ($maps as $map) {
555 echo "<li>" . $map['name'] . '</li>';
556 }
557 echo '</ul>';
558 }
559 echo '</body></html>';
560 }
561 }
562
563}
564
565/**
566 * JSON service
567 */
568class Json extends Server {
569
570 /**
571 * Callback for JSONP default grid
572 * @var string
573 */
574 private $callback = 'grid';
575
576 /**
577 * @param array $params
578 */
579 public $layer = 'index';
580
581 /**
582 * @var integer
583 */
584 public $z;
585
586 /**
587 * @var integer
588 */
589 public $y;
590
591 /**
592 * @var integer
593 */
594 public $x;
595
596 /**
597 * @var string
598 */
599 public $ext;
600
601 /**
602 *
603 * @param array $params
604 */
605 public function __construct($params) {
606 parent::__construct();
607 parent::setParams($params);
608 if (isset($_GET['callback']) && !empty($_GET['callback'])) {
609 $this->callback = $_GET['callback'];
610 }
611 }
612
613 /**
614 * Adds metadata about layer
615 * @param array $metadata
616 * @return array
617 */
618 public function metadataTileJson($metadata) {
619 $metadata['tilejson'] = '2.0.0';
620 $metadata['scheme'] = 'xyz';
621 if ($this->isDBLayer($metadata['basename'])) {
622 $this->DBconnect($this->config["mapDir"] ."/". $metadata['basename'] . '.mbtiles');
623 $res = $this->db->query('SELECT name FROM sqlite_master WHERE name="grids";');
624 if ($res) {
625 foreach ($this->config['baseUrls'] as $url) {
626 $grids[] = '' . $this->config['protocol'] . '://' . $url . '/' . $metadata['basename'] . '/{z}/{x}/{y}.grid.json';
627 }
628 $metadata['grids'] = $grids;
629 }
630 }
631 if (array_key_exists('json', $metadata)) {
632 $mjson = json_decode(stripslashes($metadata['json']));
633 foreach ($mjson as $key => $value) {
634 $metadata[$key] = $value;
635 }
636 unset($metadata['json']);
637 }
638 return $metadata;
639 }
640
641 /**
642 * Creates JSON from array
643 * @param string $basename
644 * @return string
645 */
646 private function createJson($basename) {
647 $maps = array_merge($this->fileLayer, $this->dbLayer);
648 if ($basename == 'index') {
649 $output = '[';
650 foreach ($maps as $map) {
651 $output = $output . json_encode($this->metadataTileJson($map)) . ',';
652 }
653 if (strlen($output) > 1) {
654 $output = substr_replace($output, ']', -1);
655 } else {
656 $output = $output . ']';
657 }
658 } else {
659 foreach ($maps as $map) {
660 if (strpos($map['basename'], $basename) !== false) {
661 $output = json_encode($this->metadataTileJson($map));
662 break;
663 }
664 }
665 }
666 if (!isset($output)) {
667 echo 'TileServer: unknown map ' . $basename;
668 die;
669 }
670 return stripslashes($output);
671 }
672
673 /**
674 * Returns JSON with callback
675 */
676 public function getJson() {
677 parent::setDatasets();
678 header('Access-Control-Allow-Origin: *');
679 header('Content-Type: application/json; charset=utf-8');
680 if ($this->callback !== 'grid') {
681 echo $this->callback . '(' . $this->createJson($this->layer) . ');'; die;
682 } else {
683 echo $this->createJson($this->layer); die;
684 }
685 }
686
687 /**
688 * Returns JSONP with callback
689 */
690 public function getJsonp() {
691 parent::setDatasets();
692 header('Access-Control-Allow-Origin: *');
693 header('Content-Type: application/javascript; charset=utf-8');
694 echo $this->callback . '(' . $this->createJson($this->layer) . ');';
695 }
696
697 /**
698 * Returns UTFGrid in JSON format
699 */
700 public function getUTFGrid() {
701 parent::renderUTFGrid($this->layer, $this->z, $this->y, $this->x);
702 }
703
704}
705
706/**
707 * Web map tile service
708 */
709class Wmts extends Server {
710
711 /**
712 * @param array $params
713 */
714 public $layer;
715
716 /**
717 * @var integer
718 */
719 public $z;
720
721 /**
722 * @var integer
723 */
724 public $y;
725
726 /**
727 * @var integer
728 */
729 public $x;
730
731 /**
732 * @var string
733 */
734 public $ext;
735
736 /**
737 *
738 * @param array $params
739 */
740 public function __construct($params) {
741 parent::__construct();
742 if (isset($params)) {
743 parent::setParams($params);
744 }
745 }
746
747 /**
748 * Tests request from url and call method
749 */
750 public function get() {
751 $request = $this->getGlobal('Request');
752 if ($request !== FALSE && $request == 'gettile') {
753 $this->getTile();
754 } else {
755 parent::setDatasets();
756 $this->getCapabilities();
757 }
758 }
759
760 /**
761 * Validates tilematrixset, calculates missing params
762 * @param Object $tileMatrix
763 * @return Object
764 */
765 public function parseTileMatrix($layer, $tileMatrix){
766
767 //process projection
768 if(isset($layer['proj4'])){
769 preg_match_all("/([^+= ]+)=([^= ]+)/", $layer['proj4'], $res);
770 $proj4 = array_combine($res[1], $res[2]);
771 }
772
773 for($i = 0; $i < count($tileMatrix); $i++){
774
775 if(!isset($tileMatrix[$i]['id'])){
776 $tileMatrix[$i]['id'] = (string) $i;
777 }
778 if (!isset($tileMatrix[$i]['extent']) && isset($layer['extent'])) {
779 $tileMatrix[$i]['extent'] = $layer['extent'];
780 }
781 if (!isset($tileMatrix[$i]['matrix_size'])) {
782 $tileExtent = $this->tilesOfExtent(
783 $tileMatrix[$i]['extent'],
784 $tileMatrix[$i]['origin'],
785 $tileMatrix[$i]['pixel_size'],
786 $tileMatrix[$i]['tile_size']
787 );
788 $tileMatrix[$i]['matrix_size'] = array(
789 $tileExtent[2] + 1,
790 $tileExtent[1] + 1
791 );
792 }
793 if(!isset($tileMatrix[$i]['origin']) && isset($tileMatrix[$i]['extent'])){
794 $tileMatrix[$i]['origin'] = array(
795 $tileMatrix[$i]['extent'][0], $tileMatrix[$i]['extent'][3]
796 );
797 }
798 // Origins of geographic coordinate systems are setting in opposite order
799 if (isset($proj4) && $proj4['proj'] === 'longlat') {
800 $tileMatrix[$i]['origin'] = array_reverse($tileMatrix[$i]['origin']);
801 }
802 if(!isset($tileMatrix[$i]['scale_denominator'])){
803 $tileMatrix[$i]['scale_denominator'] = count($tileMatrix) - $i;
804 }
805 if(!isset($tileMatrix[$i]['tile_size'])){
806 $tileSize = 256 * (int) $layer['scale'];
807 $tileMatrix[$i]['tile_size'] = array($tileSize, $tileSize);
808 }
809 }
810
811 return $tileMatrix;
812 }
813
814 /**
815 * Calculates corners of tilematrix
816 * @param array $extent
817 * @param array $origin
818 * @param array $pixel_size
819 * @param array $tile_size
820 * @return array
821 */
822 public function tilesOfExtent($extent, $origin, $pixel_size, $tile_size) {
823 $tiles = array(
824 $this->minsample($extent[0] - $origin[0], $pixel_size[0] * $tile_size[0]),
825 $this->minsample($extent[1] - $origin[1], $pixel_size[1] * $tile_size[1]),
826 $this->maxsample($extent[2] - $origin[0], $pixel_size[0] * $tile_size[0]),
827 $this->maxsample($extent[3] - $origin[1], $pixel_size[1] * $tile_size[1]),
828 );
829 return $tiles;
830 }
831
832 private function minsample($x, $f){
833 return $f > 0 ? floor($x / $f) : ceil(($x / $f) - 1);
834 }
835
836 private function maxsample($x, $f){
837 return $f < 0 ? floor($x / $f) : ceil(($x / $f) - 1);
838 }
839
840 /**
841 * Default TileMetrixSet for Pseudo Mercator projection 3857
842 * @param ?number $maxZoom
843 * @return string TileMatrixSet xml
844 */
845 public function getMercatorTileMatrixSet($maxZoom = 18){
846 $denominatorBase = 559082264.0287178;
847 $extent = array(-20037508.34,-20037508.34,20037508.34,20037508.34);
848 $tileMatrixSet = array();
849
850 for($i = 0; $i <= $maxZoom; $i++){
851 $matrixSize = pow(2, $i);
852 $tileMatrixSet[] = array(
853 'extent' => $extent,
854 'id' => (string) $i,
855 'matrix_size' => array($matrixSize, $matrixSize),
856 'origin' => array($extent[0], $extent[3]),
857 'scale_denominator' => $denominatorBase / pow(2, $i),
858 'tile_size' => array(256, 256)
859 );
860 }
861
862 return $this->getTileMatrixSet('GoogleMapsCompatible', $tileMatrixSet, 'EPSG:3857');
863 }
864
865 /**
866 * Default TileMetrixSet for WGS84 projection 4326
867 * @return string Xml
868 */
869 public function getWGS84TileMatrixSet(){
870 $extent = array(-180.000000, -90.000000, 180.000000, 90.000000);
871 $scaleDenominators = array(279541132.01435887813568115234, 139770566.00717943906784057617,
872 69885283.00358971953392028809, 34942641.50179485976696014404, 17471320.75089742988348007202,
873 8735660.37544871494174003601, 4367830.18772435747087001801, 2183915.09386217873543500900,
874 1091957.54693108936771750450, 545978.77346554468385875225, 272989.38673277234192937613,
875 136494.69336638617096468806, 68247.34668319308548234403, 34123.67334159654274117202,
876 17061.83667079825318069197, 8530.91833539912659034599, 4265.45916769956329517299,
877 2132.72958384978574031265);
878 $tileMatrixSet = array();
879
880 for($i = 0; $i <= 17; $i++){
881 $matrixSize = pow(2, $i);
882 $tileMatrixSet[] = array(
883 'extent' => $extent,
884 'id' => (string) $i,
885 'matrix_size' => array($matrixSize * 2, $matrixSize),
886 'origin' => array($extent[3], $extent[0]),
887 'scale_denominator' => $scaleDenominators[$i],
888 'tile_size' => array(256, 256)
889 );
890 }
891
892 return $this->getTileMatrixSet('WGS84', $tileMatrixSet, 'EPSG:4326');
893 }
894
895 /**
896 * Prints WMTS TileMatrixSet
897 * @param string $name
898 * @param array $tileMatrixSet Array of levels
899 * @param string $crs Code of crs eg: EPSG:3857
900 * @return string TileMatrixSet xml
901 */
902 public function getTileMatrixSet($name, $tileMatrixSet, $crs = 'EPSG:3857'){
903 $srs = explode(':', $crs);
904 $TileMatrixSet = '<TileMatrixSet>
905 <ows:Title>' . $name . '</ows:Title>
906 <ows:Abstract>' . $name . ' '. $crs .'</ows:Abstract>
907 <ows:Identifier>' . $name . '</ows:Identifier>
908 <ows:SupportedCRS>urn:ogc:def:crs:'.$srs[0].'::'.$srs[1].'</ows:SupportedCRS>';
909 // <WellKnownScaleSet>urn:ogc:def:wkss:OGC:1.0:GoogleMapsCompatible</WellKnownScaleSet>;
910 foreach($tileMatrixSet as $level){
911 $TileMatrixSet .= '
912 <TileMatrix>
913 <ows:Identifier>' . $level['id'] . '</ows:Identifier>
914 <ScaleDenominator>' . $level['scale_denominator'] . '</ScaleDenominator>
915 <TopLeftCorner>'. $level['origin'][0] . ' ' . $level['origin'][1] .'</TopLeftCorner>
916 <TileWidth>' . $level['tile_size'][0] . '</TileWidth>
917 <TileHeight>' . $level['tile_size'][1] . '</TileHeight>
918 <MatrixWidth>' . $level['matrix_size'][0] . '</MatrixWidth>
919 <MatrixHeight>' . $level['matrix_size'][1] . '</MatrixHeight>
920 </TileMatrix>';
921 }
922 $TileMatrixSet .= '</TileMatrixSet>';
923
924 return $TileMatrixSet;
925 }
926
927 /**
928 * Returns tilesets getCapabilities
929 */
930 public function getCapabilities() {
931
932 $layers = array_merge($this->fileLayer, $this->dbLayer);
933
934 //if TileMatrixSet is provided validate it
935 for($i = 0; $i < count($layers); $i++){
936 if($layers[$i]['profile'] == 'custom'){
937 $layers[$i]['tile_matrix'] = $this->parseTileMatrix(
938 $layers[$i],
939 $layers[$i]['tile_matrix']
940 );
941 }
942 }
943
944 header('Content-type: application/xml');
945 echo '<?xml version="1.0" encoding="UTF-8" ?>
946<Capabilities xmlns="http://www.opengis.net/wmts/1.0" xmlns:ows="http://www.opengis.net/ows/1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:gml="http://www.opengis.net/gml" xsi:schemaLocation="http://www.opengis.net/wmts/1.0 http://schemas.opengis.net/wmts/1.0/wmtsGetCapabilities_response.xsd" version="1.0.0">
947 <!-- Service Identification -->
948 <ows:ServiceIdentification>
949 <ows:Title>tileserverphp</ows:Title>
950 <ows:ServiceType>OGC WMTS</ows:ServiceType>
951 <ows:ServiceTypeVersion>1.0.0</ows:ServiceTypeVersion>
952 </ows:ServiceIdentification>
953 <!-- Operations Metadata -->
954 <ows:OperationsMetadata>
955 <ows:Operation name="GetCapabilities">
956 <ows:DCP>
957 <ows:HTTP>
958 <ows:Get xlink:href="' . $this->config['protocol'] . '://' . $this->config['baseUrls'][0] . '/wmts/1.0.0/WMTSCapabilities.xml">
959 <ows:Constraint name="GetEncoding">
960 <ows:AllowedValues>
961 <ows:Value>RESTful</ows:Value>
962 </ows:AllowedValues>
963 </ows:Constraint>
964 </ows:Get>
965 <!-- add KVP binding in 10.1 -->
966 <ows:Get xlink:href="' . $this->config['protocol'] . '://' . $this->config['baseUrls'][0] . '/wmts?">
967 <ows:Constraint name="GetEncoding">
968 <ows:AllowedValues>
969 <ows:Value>KVP</ows:Value>
970 </ows:AllowedValues>
971 </ows:Constraint>
972 </ows:Get>
973 </ows:HTTP>
974 </ows:DCP>
975 </ows:Operation>
976 <ows:Operation name="GetTile">
977 <ows:DCP>
978 <ows:HTTP>
979 <ows:Get xlink:href="' . $this->config['protocol'] . '://' . $this->config['baseUrls'][0] . '/wmts/">
980 <ows:Constraint name="GetEncoding">
981 <ows:AllowedValues>
982 <ows:Value>RESTful</ows:Value>
983 </ows:AllowedValues>
984 </ows:Constraint>
985 </ows:Get>
986 <ows:Get xlink:href="' . $this->config['protocol'] . '://' . $this->config['baseUrls'][0] . '/wmts?">
987 <ows:Constraint name="GetEncoding">
988 <ows:AllowedValues>
989 <ows:Value>KVP</ows:Value>
990 </ows:AllowedValues>
991 </ows:Constraint>
992 </ows:Get>
993 </ows:HTTP>
994 </ows:DCP>
995 </ows:Operation>
996 </ows:OperationsMetadata>
997 <Contents>';
998
999 $customtileMatrixSets = '';
1000 $maxMercatorZoom = 18;
1001
1002 //layers
1003 foreach ($layers as $m) {
1004
1005 $basename = $m['basename'];
1006 $title = (array_key_exists('name', $m)) ? $m['name'] : $basename;
1007 $profile = $m['profile'];
1008 $bounds = $m['bounds'];
1009 $format = $m['format'] == 'hybrid' ? 'jpgpng' : $m['format'];
1010 $mime = ($format == 'jpg') ? 'image/jpeg' : 'image/' . $format;
1011
1012 if ($profile == 'geodetic') {
1013 $tileMatrixSet = 'WGS84';
1014 }elseif ($m['profile'] == 'custom') {
1015 $crs = explode(':', $m['crs']);
1016 $tileMatrixSet = 'custom' . $crs[1] . $m['basename'];
1017 $customtileMatrixSets .= $this->getTileMatrixSet(
1018 $tileMatrixSet,
1019 $m['tile_matrix'],
1020 $m['crs']
1021 );
1022 } else {
1023 $tileMatrixSet = 'GoogleMapsCompatible';
1024 $maxMercatorZoom = max($maxMercatorZoom, $m['maxzoom']);
1025 }
1026
1027 $wmtsHost = substr($m['tiles'][0], 0, strpos($m['tiles'][0], $m['basename']));
1028 $resourceUrlTemplate = $wmtsHost . $basename
1029 . '/{TileMatrix}/{TileCol}/{TileRow}';
1030 if(strlen($format) <= 4){
1031 $resourceUrlTemplate .= '.' . $format;
1032 }
1033
1034 echo'
1035 <Layer>
1036 <ows:Title>' . $title . '</ows:Title>
1037 <ows:Identifier>' . $basename . '</ows:Identifier>
1038 <ows:WGS84BoundingBox crs="urn:ogc:def:crs:OGC:2:84">
1039 <ows:LowerCorner>' . $bounds[0] . ' ' . $bounds[1] . '</ows:LowerCorner>
1040 <ows:UpperCorner>' . $bounds[2] . ' ' . $bounds[3] . '</ows:UpperCorner>
1041 </ows:WGS84BoundingBox>
1042 <Style isDefault="true">
1043 <ows:Identifier>default</ows:Identifier>
1044 </Style>
1045 <Format>' . $mime . '</Format>
1046 <TileMatrixSetLink>
1047 <TileMatrixSet>' . $tileMatrixSet . '</TileMatrixSet>
1048 </TileMatrixSetLink>
1049 <ResourceURL format="' . $mime . '" resourceType="tile" template="' . $resourceUrlTemplate . '"/>
1050 </Layer>';
1051 }
1052
1053 // Print custom TileMatrixSets
1054 if (strlen($customtileMatrixSets) > 0) {
1055 echo $customtileMatrixSets;
1056 }
1057
1058 // Print PseudoMercator TileMatrixSet
1059 echo $this->getMercatorTileMatrixSet($maxMercatorZoom);
1060
1061 // Print WGS84 TileMatrixSet
1062 echo $this->getWGS84TileMatrixSet();
1063
1064 echo '</Contents>
1065 <ServiceMetadataURL xlink:href="' . $this->config['protocol'] . '://' . $this->config['baseUrls'][0] . '/wmts/1.0.0/WMTSCapabilities.xml"/>
1066</Capabilities>';
1067 }
1068
1069 /**
1070 * Returns tile via WMTS specification
1071 */
1072 public function getTile() {
1073 $request = $this->getGlobal('Request');
1074 if ($request) {
1075 if (strpos('/', $_GET['Format']) !== FALSE) {
1076 $format = explode('/', $_GET['Format']);
1077 $format = $format[1];
1078 } else {
1079 $format = $this->getGlobal('Format');
1080 }
1081 parent::renderTile(
1082 $this->getGlobal('Layer'),
1083 $this->getGlobal('TileMatrix'),
1084 $this->getGlobal('TileRow'),
1085 $this->getGlobal('TileCol'),
1086 $format
1087 );
1088 } else {
1089 parent::renderTile($this->layer, $this->z, $this->y, $this->x, $this->ext);
1090 }
1091 }
1092
1093}
1094
1095/**
1096 * Tile map service
1097 */
1098class Tms extends Server {
1099
1100 /**
1101 * @param array $params
1102 */
1103 public $layer;
1104
1105 /**
1106 * @var integer
1107 */
1108 public $z;
1109
1110 /**
1111 * @var integer
1112 */
1113 public $y;
1114
1115 /**
1116 * @var integer
1117 */
1118 public $x;
1119
1120 /**
1121 * @var string
1122 */
1123 public $ext;
1124
1125 /**
1126 *
1127 * @param array $params
1128 */
1129 public function __construct($params) {
1130 parent::__construct();
1131 parent::setParams($params);
1132 }
1133
1134 /**
1135 * Returns getCapabilities metadata request
1136 */
1137 public function getCapabilities() {
1138 parent::setDatasets();
1139 $maps = array_merge($this->fileLayer, $this->dbLayer);
1140 header('Content-type: application/xml');
1141 echo'<TileMapService version="1.0.0"><TileMaps>';
1142 foreach ($maps as $m) {
1143 $basename = $m['basename'];
1144 $title = (array_key_exists('name', $m) ) ? $m['name'] : $basename;
1145 $profile = $m['profile'];
1146 if ($profile == 'geodetic') {
1147 $srs = 'EPSG:4326';
1148 } else {
1149 $srs = 'EPSG:3857';
1150 }
1151 $url = $this->config['protocol'] . '://' . $this->config['baseUrls'][0]
1152 . '/tms/' . $basename;
1153 echo '<TileMap title="' . $title . '" srs="' . $srs
1154 . '" type="InvertedTMS" ' . 'profile="global-' . $profile
1155 . '" href="' . $url . '" />';
1156 }
1157 echo '</TileMaps></TileMapService>';
1158 }
1159
1160 /**
1161 * Prints metadata about layer
1162 */
1163 public function getLayerCapabilities() {
1164 parent::setDatasets();
1165 $maps = array_merge($this->fileLayer, $this->dbLayer);
1166 foreach ($maps as $map) {
1167 if (strpos($map['basename'], $this->layer) !== false) {
1168 $m = $map;
1169 break;
1170 }
1171 }
1172 $title = (array_key_exists('name', $m)) ? $m['name'] : $m['basename'];
1173 $description = (array_key_exists('description', $m)) ? $m['description'] : "";
1174 $bounds = $m['bounds'];
1175 if ($m['profile'] == 'geodetic') {
1176 $srs = 'EPSG:4326';
1177 $initRes = 0.703125;
1178 } elseif ($m['profile'] == 'custom') {
1179 $srs = $m['crs'];
1180 $bounds = $m['extent'];
1181 if(isset($m['tile_matrix'][0]['pixel_size'][0])){
1182 $initRes = $m['tile_matrix'][0]['pixel_size'][0];
1183 }else{
1184 $initRes = 1;
1185 }
1186 } else {
1187 $srs = 'EPSG:3857';
1188 $bounds = array(-20037508.34,-20037508.34,20037508.34,20037508.34);
1189 $initRes = 156543.03392804062;
1190 }
1191 $mime = ($m['format'] == 'jpg') ? 'image/jpeg' : 'image/png';
1192 header("Content-type: application/xml");
1193 $serviceUrl = $this->config['protocol'] . '://' . $this->config['baseUrls'][0] . '/' . $m['basename'];
1194 echo '<TileMap version="1.0.0" tilemapservice="' . $serviceUrl . '" type="InvertedTMS">
1195 <Title>' . htmlspecialchars($title) . '</Title>
1196 <Abstract>' . htmlspecialchars($description) . '</Abstract>
1197 <SRS>' . $srs . '</SRS>
1198 <BoundingBox minx="' . $bounds[0] . '" miny="' . $bounds[1] . '" maxx="' . $bounds[2] . '" maxy="' . $bounds[3] . '" />
1199 <Origin x="' . $bounds[0] . '" y="' . $bounds[1] . '"/>
1200 <TileFormat width="256" height="256" mime-type="' . $mime . '" extension="' . $m['format'] . '"/>
1201 <TileSets profile="global-' . $m['profile'] . '">';
1202 for ($zoom = $m['minzoom']; $zoom < $m['maxzoom'] + 1; $zoom++) {
1203 $res = $initRes / pow(2, $zoom);
1204 $url = $this->config['protocol'] . '://' . $this->config['baseUrls'][0] . '/' . $m['basename'] . '/' . $zoom;
1205 echo '<TileSet href="' . $url . '" units-per-pixel="' . $res . '" order="' . $zoom . '" />';
1206 }
1207 echo'</TileSets></TileMap>';
1208 }
1209
1210 /**
1211 * Process getTile request
1212 */
1213 public function getTile() {
1214 parent::renderTile($this->layer, $this->z, $this->y, $this->x, $this->ext);
1215 }
1216}
1217
1218/**
1219 * Simple router
1220 */
1221class Router {
1222
1223 /**
1224 * @param array $routes
1225 */
1226 public static function serve($routes) {
1227 $request_method = strtolower($_SERVER['REQUEST_METHOD']);
1228 $path_info = '/';
1229 global $config;
1230 $config['protocol'] = ( isset($_SERVER["HTTPS"]) or $_SERVER['SERVER_PORT'] == '443') ? "https" : "http";
1231 if (!empty($_SERVER['PATH_INFO'])) {
1232 $path_info = $_SERVER['PATH_INFO'];
1233 } else if (!empty($_SERVER['ORIG_PATH_INFO']) && strpos($_SERVER['ORIG_PATH_INFO'], 'tileserver.php') === false) {
1234 $path_info = $_SERVER['ORIG_PATH_INFO'];
1235 } else if (!empty($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '/tileserver.php') !== false) {
1236 $path_info = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
1237 $config['baseUrls'][0] = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '?';
1238 } else {
1239 if (!empty($_SERVER['REQUEST_URI'])) {
1240 $path_info = (strpos($_SERVER['REQUEST_URI'], '?') > 0) ? strstr($_SERVER['REQUEST_URI'], '?', true) : $_SERVER['REQUEST_URI'];
1241 }
1242 }
1243 $discovered_handler = null;
1244 $regex_matches = array();
1245
1246 if ($routes) {
1247 $tokens = array(
1248 ':string' => '([a-zA-Z]+)',
1249 ':number' => '([0-9]+)',
1250 ':alpha' => '([a-zA-Z0-9-_@\.]+)'
1251 );
1252 //global $config;
1253 foreach ($routes as $pattern => $handler_name) {
1254 $pattern = strtr($pattern, $tokens);
1255 if (preg_match('#/?' . $pattern . '/?$#', $path_info, $matches)) {
1256 if (!isset($config['baseUrls'])) {
1257 $config['baseUrls'][0] = $_SERVER['HTTP_HOST'] . preg_replace('#/?' . $pattern . '/?$#', '', $path_info);
1258 }
1259 $discovered_handler = $handler_name;
1260 $regex_matches = $matches;
1261 break;
1262 }
1263 }
1264 }
1265 $handler_instance = null;
1266 if ($discovered_handler) {
1267 if (is_string($discovered_handler)) {
1268 if (strpos($discovered_handler, ':') !== false) {
1269 $discoverered_class = explode(':', $discovered_handler);
1270 $discoverered_method = explode(':', $discovered_handler);
1271 $handler_instance = new $discoverered_class[0]($regex_matches);
1272 call_user_func(array($handler_instance, $discoverered_method[1]));
1273 } else {
1274 $handler_instance = new $discovered_handler($regex_matches);
1275 }
1276 } elseif (is_callable($discovered_handler)) {
1277 $handler_instance = $discovered_handler();
1278 }
1279 } else {
1280 if (!isset($config['baseUrls'][0])) {
1281 $config['baseUrls'][0] = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
1282 }
1283 if (strpos($_SERVER['REQUEST_URI'], '=') != FALSE) {
1284 $kvp = explode('=', $_SERVER['REQUEST_URI']);
1285 $_GET['callback'] = $kvp[1];
1286 $params[0] = 'index';
1287 $handler_instance = new Json($params);
1288 $handler_instance->getJson();
1289 }
1290 $handler_instance = new Server;
1291 $handler_instance->getHtml();
1292 }
1293 }
1294
1295}
Note: See TracBrowser for help on using the repository browser.