Passed
Pull Request — master (#5)
by Mark
02:49
created
StaticMap.php 3 patches
Indentation   +834 added lines, -834 removed lines patch added patch discarded remove patch
@@ -31,838 +31,838 @@
 block discarded – undo
31 31
  */
32 32
 class StaticMap {
33 33
 
34
-    // the final output
35
-    private $tileSize = 256;
36
-    private $tileInfo = array(
37
-        // OSM sources
38
-        'openstreetmap' => array(
39
-            'txt'  => '(c) OpenStreetMap data/ODbl',
40
-            'logo' => 'osm_logo.png',
41
-            'url'  => 'https://tile.openstreetmap.org/{Z}/{X}/{Y}.png'
42
-        ),
43
-        // OCM sources
44
-        'cycle'         => array(
45
-            'txt'  => '(c) Thunderforest maps',
46
-            'logo' => 'tf_logo.png',
47
-            'url'  => 'https://tile.thunderforest.com/cycle/{Z}/{X}/{Y}.png'
48
-        ),
49
-        'transport'     => array(
50
-            'txt'  => '(c) Thunderforest maps',
51
-            'logo' => 'tf_logo.png',
52
-            'url'  => 'https://tile.thunderforest.com/transport/{Z}/{X}/{Y}.png'
53
-        ),
54
-        'landscape'     => array(
55
-            'txt'  => '(c) Thunderforest maps',
56
-            'logo' => 'tf_logo.png',
57
-            'url'  => 'https://tile.thunderforest.com/landscape/{Z}/{X}/{Y}.png'
58
-        ),
59
-        'outdoors'      => array(
60
-            'txt'  => '(c) Thunderforest maps',
61
-            'logo' => 'tf_logo.png',
62
-            'url'  => 'https://tile.thunderforest.com/outdoors/{Z}/{X}/{Y}.png'
63
-        ),
64
-        'toner-lite'    => array(
65
-            'txt'  => 'Stamen tiles',
66
-            'logo' => 'stamen.png',
67
-            'url'  => 'http://tile.stamen.com/toner-lite/{Z}/{X}/{Y}.png'
68
-        ),
69
-        'terrain'       => array(
70
-            'txt'  => 'Stamen tiles',
71
-            'logo' => 'stamen.png',
72
-            'url'  => 'http://tile.stamen.com/terrain/{Z}/{X}/{Y}.png'
73
-        )
74
-        //,
75
-        // 'piste'=>array(
76
-        // 'txt'=>'OpenPisteMap tiles',
77
-        // 'logo'=>'piste_logo.png',
78
-        // 'url'=>''),
79
-        // 'sea'=>array(
80
-        // 'txt'=>'OpenSeaMap tiles',
81
-        // 'logo'=>'sea_logo.png',
82
-        // 'url'=>''),
83
-        // H&B sources
84
-        //          'hikeandbike' => array (
85
-        //                  'txt' => 'Hike & Bike Map',
86
-        //                  'logo' => 'hnb_logo.png',
87
-        //                  //'url' => 'http://toolserver.org/tiles/hikebike/{Z}/{X}/{Y}.png'
88
-        //                  //moved to: https://www.toolserver.org/tiles/hikebike/12/2105/1388.png
89
-        //                  'url' => 'http://c.tiles.wmflabs.org/hikebike/{Z}/{X}/{Y}.png'
90
-        //          )
91
-    );
92
-    private $tileDefaultSrc = 'openstreetmap';
93
-
94
-    // set up markers
95
-    private $markerPrototypes = array(
96
-        // found at http://www.mapito.net/map-marker-icons.html
97
-        // these are 17x19 px with a pointer at the bottom left
98
-        'lightblue' => array(
99
-            'regex'        => '/^lightblue([0-9]+)$/',
100
-            'extension'    => '.png',
101
-            'shadow'       => false,
102
-            'offsetImage'  => '0,-19',
103
-            'offsetShadow' => false
104
-        ),
105
-        // openlayers std markers are 21x25px with shadow
106
-        'ol-marker' => array(
107
-            'regex'        => '/^marker(|-blue|-gold|-green|-red)+$/',
108
-            'extension'    => '.png',
109
-            'shadow'       => 'marker_shadow.png',
110
-            'offsetImage'  => '-10,-25',
111
-            'offsetShadow' => '-1,-13'
112
-        ),
113
-        // these are 16x16 px
114
-        'ww_icon'   => array(
115
-            'regex'        => '/ww_\S+$/',
116
-            'extension'    => '.png',
117
-            'shadow'       => false,
118
-            'offsetImage'  => '-8,-8',
119
-            'offsetShadow' => false
120
-        ),
121
-        // assume these are 16x16 px
122
-        'rest'      => array(
123
-            'regex'        => '/^(?!lightblue([0-9]+)$)(?!(ww_\S+$))(?!marker(|-blue|-gold|-green|-red)+$)(.*)/',
124
-            'extension'    => '.png',
125
-            'shadow'       => 'marker_shadow.png',
126
-            'offsetImage'  => '-8,-8',
127
-            'offsetShadow' => '-1,-1'
128
-        )
129
-    );
130
-    private $centerX;
131
-    private $centerY;
132
-    private $offsetX;
133
-    private $offsetY;
134
-    private $image;
135
-    private $zoom;
136
-    private $lat;
137
-    private $lon;
138
-    private $width;
139
-    private $height;
140
-    private $markers;
141
-    private $maptype;
142
-    private $kmlFileName;
143
-    private $gpxFileName;
144
-    private $geojsonFileName;
145
-    private $autoZoomExtent;
146
-    private $apikey;
147
-    private $tileCacheBaseDir;
148
-    private $mapCacheBaseDir;
149
-    private $mediaBaseDir;
150
-    private $useTileCache;
151
-    private $mapCacheID = '';
152
-    private $mapCacheFile = '';
153
-    private $mapCacheExtension = 'png';
154
-
155
-    /**
156
-     * Constructor.
157
-     *
158
-     * @param float  $lat
159
-     *            Latitude (x) of center of map
160
-     * @param float  $lon
161
-     *            Longitude (y) of center of map
162
-     * @param int    $zoom
163
-     *            Zoomlevel
164
-     * @param int    $width
165
-     *            Width in pixels
166
-     * @param int    $height
167
-     *            Height in pixels
168
-     * @param string $maptype
169
-     *            Name of the map
170
-     * @param array  $markers
171
-     *            array of markers
172
-     * @param string $gpx
173
-     *            GPX filename
174
-     * @param string $kml
175
-     *            KML filename
176
-     * @param string $geojson
177
-     * @param string $mediaDir
178
-     *            Directory to store/cache maps
179
-     * @param string $tileCacheBaseDir
180
-     *            Directory to cache map tiles
181
-     * @param bool   $autoZoomExtent
182
-     *            Wheter or not to override zoom/lat/lon and zoom to the extent of gpx/kml and markers
183
-     * @param string $apikey
184
-     */
185
-    public function __construct(
186
-        float $lat,
187
-        float $lon,
188
-        int $zoom,
189
-        int $width,
190
-        int $height,
191
-        string $maptype,
192
-        array $markers,
193
-        string $gpx,
194
-        string $kml,
195
-        string $geojson,
196
-        string $mediaDir,
197
-        string $tileCacheBaseDir,
198
-        bool $autoZoomExtent = true,
199
-        string $apikey = ''
200
-    ) {
201
-        $this->zoom   = $zoom;
202
-        $this->lat    = $lat;
203
-        $this->lon    = $lon;
204
-        $this->width  = $width;
205
-        $this->height = $height;
206
-        // validate + set maptype
207
-        $this->maptype = $this->tileDefaultSrc;
208
-        if(array_key_exists($maptype, $this->tileInfo)) {
209
-            $this->maptype = $maptype;
210
-        }
211
-        $this->markers          = $markers;
212
-        $this->kmlFileName      = $kml;
213
-        $this->gpxFileName      = $gpx;
214
-        $this->geojsonFileName  = $geojson;
215
-        $this->mediaBaseDir     = $mediaDir;
216
-        $this->tileCacheBaseDir = $tileCacheBaseDir . '/olmaptiles';
217
-        $this->useTileCache     = $this->tileCacheBaseDir !== '';
218
-        $this->mapCacheBaseDir  = $mediaDir . '/olmapmaps';
219
-        $this->autoZoomExtent   = $autoZoomExtent;
220
-        $this->apikey           = $apikey;
221
-    }
222
-
223
-    /**
224
-     * get the map, this may return a reference to a cached copy.
225
-     *
226
-     * @return string url relative to media dir
227
-     */
228
-    public function getMap(): string {
229
-        try {
230
-            if($this->autoZoomExtent) {
231
-                $this->autoZoom();
232
-            }
233
-        } catch(Exception $e) {
234
-            dbglog($e);
235
-        }
236
-
237
-        // use map cache, so check cache for map
238
-        if(!$this->checkMapCache()) {
239
-            // map is not in cache, needs to be build
240
-            $this->makeMap();
241
-            $this->mkdirRecursive(dirname($this->mapCacheIDToFilename()), 0777);
242
-            imagepng($this->image, $this->mapCacheIDToFilename(), 9);
243
-        }
244
-        $doc = $this->mapCacheIDToFilename();
245
-        // make url relative to media dir
246
-        return str_replace($this->mediaBaseDir, '', $doc);
247
-    }
248
-
249
-    /**
250
-     * Calculate the lat/lon/zoom values to make sure that all of the markers and gpx/kml are on the map.
251
-     * can throw an error like
252
-     * "Fatal error: Uncaught Exception: Cannot create a collection with non-geometries in
253
-     * D:\www\wild-water.nl\www\dokuwiki\lib\plugins\geophp\geoPHP\lib\geometry\Collection.class.php:29"
254
-     *
255
-     * @param float $paddingFactor
256
-     *            buffer constant to enlarge (>1.0) the zoom level
257
-     * @throws Exception
258
-     */
259
-    private function autoZoom(float $paddingFactor = 1.0): void {
260
-        $geoms    = array();
261
-        $geoms [] = new Point ($this->lon, $this->lat);
262
-        if(!empty ($this->markers)) {
263
-            foreach($this->markers as $marker) {
264
-                $geoms [] = new Point ($marker ['lon'], $marker ['lat']);
265
-            }
266
-        }
267
-        if(file_exists($this->kmlFileName)) {
268
-            $g = geoPHP::load(file_get_contents($this->kmlFileName), 'kml');
269
-            if($g !== false) {
270
-                $geoms [] = $g;
271
-            }
272
-        }
273
-        if(file_exists($this->gpxFileName)) {
274
-            $g = geoPHP::load(file_get_contents($this->gpxFileName), 'gpx');
275
-            if($g !== false) {
276
-                $geoms [] = $g;
277
-            }
278
-        }
279
-        if(file_exists($this->geojsonFileName)) {
280
-            $g = geoPHP::load(file_get_contents($this->geojsonFileName), 'geojson');
281
-            if($g !== false) {
282
-                $geoms [] = $g;
283
-            }
284
-        }
285
-
286
-        if(count($geoms) <= 1) {
287
-            dbglog($geoms, "StaticMap::autoZoom: Skip setting autozoom options");
288
-            return;
289
-        }
290
-
291
-        $geom     = new GeometryCollection ($geoms);
292
-        $centroid = $geom->centroid();
293
-        $bbox     = $geom->getBBox();
294
-
295
-        // determine vertical resolution, this depends on the distance from the equator
296
-        // $vy00 = log(tan(M_PI*(0.25 + $centroid->getY()/360)));
297
-        $vy0 = log(tan(M_PI * (0.25 + $bbox ['miny'] / 360)));
298
-        $vy1 = log(tan(M_PI * (0.25 + $bbox ['maxy'] / 360)));
299
-        dbglog("StaticMap::autoZoom: vertical resolution: $vy0, $vy1");
300
-        $zoomFactorPowered  = ($this->height / 2) / (40.7436654315252 * ($vy1 - $vy0));
301
-        $resolutionVertical = 360 / ($zoomFactorPowered * $this->tileSize);
302
-        // determine horizontal resolution
303
-        $resolutionHorizontal = ($bbox ['maxx'] - $bbox ['minx']) / $this->width;
304
-        $resolution           = max($resolutionHorizontal, $resolutionVertical) * $paddingFactor;
305
-        $zoom                 = log(360 / ($resolution * $this->tileSize), 2);
306
-
307
-        if(is_finite($zoom) && $zoom < 15 && $zoom > 2) {
308
-            $this->zoom = floor($zoom);
309
-        }
310
-        $this->lon = $centroid->getX();
311
-        $this->lat = $centroid->getY();
312
-        dbglog("StaticMap::autoZoom: Set autozoom options to: z: $this->zoom, lon: $this->lon, lat: $this->lat");
313
-    }
314
-
315
-    public function checkMapCache(): bool {
316
-        // side effect: set the mapCacheID
317
-        $this->mapCacheID = md5($this->serializeParams());
318
-        $filename         = $this->mapCacheIDToFilename();
319
-        return file_exists($filename);
320
-    }
321
-
322
-    public function serializeParams(): string {
323
-        return join(
324
-            "&", array(
325
-                   $this->zoom,
326
-                   $this->lat,
327
-                   $this->lon,
328
-                   $this->width,
329
-                   $this->height,
330
-                   serialize($this->markers),
331
-                   $this->maptype,
332
-                   $this->kmlFileName,
333
-                   $this->gpxFileName,
334
-                   $this->geojsonFileName
335
-               )
336
-        );
337
-    }
338
-
339
-    public function mapCacheIDToFilename(): string {
340
-        if(!$this->mapCacheFile) {
341
-            $this->mapCacheFile = $this->mapCacheBaseDir . "/" . $this->maptype . "/" . $this->zoom . "/cache_"
342
-                . substr($this->mapCacheID, 0, 2) . "/" . substr($this->mapCacheID, 2, 2)
343
-                . "/" . substr($this->mapCacheID, 4);
344
-        }
345
-        return $this->mapCacheFile . "." . $this->mapCacheExtension;
346
-    }
347
-
348
-    /**
349
-     * make the map.
350
-     */
351
-    public function makeMap(): void {
352
-        $this->initCoords();
353
-        $this->createBaseMap();
354
-        if(!empty ($this->markers))
355
-            $this->placeMarkers();
356
-        if(file_exists($this->kmlFileName))
357
-            $this->drawKML();
358
-        if(file_exists($this->gpxFileName))
359
-            $this->drawGPX();
360
-        if(file_exists($this->geojsonFileName))
361
-            $this->drawGeojson();
362
-
363
-        $this->drawCopyright();
364
-    }
365
-
366
-    /**
367
-     */
368
-    public function initCoords(): void {
369
-        $this->centerX = $this->lonToTile($this->lon, $this->zoom);
370
-        $this->centerY = $this->latToTile($this->lat, $this->zoom);
371
-        $this->offsetX = floor((floor($this->centerX) - $this->centerX) * $this->tileSize);
372
-        $this->offsetY = floor((floor($this->centerY) - $this->centerY) * $this->tileSize);
373
-    }
374
-
375
-    /**
376
-     *
377
-     * @param float $long
378
-     * @param int   $zoom
379
-     * @return float|int
380
-     */
381
-    public function lonToTile(float $long, int $zoom) {
382
-        return (($long + 180) / 360) * pow(2, $zoom);
383
-    }
384
-
385
-    /**
386
-     *
387
-     * @param float $lat
388
-     * @param int   $zoom
389
-     * @return float|int
390
-     */
391
-    public function latToTile(float $lat, int $zoom) {
392
-        return (1 - log(tan($lat * pi() / 180) + 1 / cos($lat * M_PI / 180)) / M_PI) / 2 * pow(2, $zoom);
393
-    }
394
-
395
-    /**
396
-     * make basemap image.
397
-     */
398
-    public function createBaseMap(): void {
399
-        $this->image   = imagecreatetruecolor($this->width, $this->height);
400
-        $startX        = floor($this->centerX - ($this->width / $this->tileSize) / 2);
401
-        $startY        = floor($this->centerY - ($this->height / $this->tileSize) / 2);
402
-        $endX          = ceil($this->centerX + ($this->width / $this->tileSize) / 2);
403
-        $endY          = ceil($this->centerY + ($this->height / $this->tileSize) / 2);
404
-        $this->offsetX = -floor(($this->centerX - floor($this->centerX)) * $this->tileSize);
405
-        $this->offsetY = -floor(($this->centerY - floor($this->centerY)) * $this->tileSize);
406
-        $this->offsetX += floor($this->width / 2);
407
-        $this->offsetY += floor($this->height / 2);
408
-        $this->offsetX += floor($startX - floor($this->centerX)) * $this->tileSize;
409
-        $this->offsetY += floor($startY - floor($this->centerY)) * $this->tileSize;
410
-
411
-        for($x = $startX; $x <= $endX; $x++) {
412
-            for($y = $startY; $y <= $endY; $y++) {
413
-                $url = str_replace(
414
-                    array(
415
-                        '{Z}',
416
-                        '{X}',
417
-                        '{Y}'
418
-                    ), array(
419
-                        $this->zoom,
420
-                        $x,
421
-                        $y
422
-                    ), $this->tileInfo [$this->maptype] ['url']
423
-                );
424
-
425
-                $tileData = $this->fetchTile($url);
426
-                if($tileData) {
427
-                    $tileImage = imagecreatefromstring($tileData);
428
-                } else {
429
-                    $tileImage = imagecreate($this->tileSize, $this->tileSize);
430
-                    $color     = imagecolorallocate($tileImage, 255, 255, 255);
431
-                    @imagestring($tileImage, 1, 127, 127, 'err', $color);
432
-                }
433
-                $destX = ($x - $startX) * $this->tileSize + $this->offsetX;
434
-                $destY = ($y - $startY) * $this->tileSize + $this->offsetY;
435
-                dbglog($this->tileSize, "imagecopy tile into image: $destX, $destY");
436
-                imagecopy(
437
-                    $this->image, $tileImage, $destX, $destY, 0, 0, $this->tileSize,
438
-                    $this->tileSize
439
-                );
440
-            }
441
-        }
442
-    }
443
-
444
-    /**
445
-     * Fetch a tile and (if configured) store it in the cache.
446
-     * @param string $url
447
-     * @return bool|string
448
-     * @todo refactor this to use dokuwiki\HTTP\HTTPClient or dokuwiki\HTTP\DokuHTTPClient
449
-     *          for better proxy handling...
450
-     */
451
-    public function fetchTile(string $url) {
452
-        if($this->useTileCache && ($cached = $this->checkTileCache($url)))
453
-            return $cached;
454
-
455
-        $_UA = 'Mozilla/4.0 (compatible; DokuWikiSpatial HTTP Client; ' . PHP_OS . ')';
456
-        if(function_exists("curl_init")) {
457
-            // use cUrl
458
-            $ch = curl_init();
459
-            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
460
-            curl_setopt($ch, CURLOPT_USERAGENT, $_UA);
461
-            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
462
-            curl_setopt($ch, CURLOPT_URL, $url . $this->apikey);
463
-            dbglog("StaticMap::fetchTile: getting: $url using curl_exec");
464
-            $tile = curl_exec($ch);
465
-            curl_close($ch);
466
-        } else {
467
-            // use file_get_contents
468
-            global $conf;
469
-            $opts = array(
470
-                'http' => array(
471
-                    'method'          => "GET",
472
-                    'header'          => "Accept-language: en\r\n" . "User-Agent: $_UA\r\n" . "accept: image/png\r\n",
473
-                    'request_fulluri' => true
474
-                )
475
-            );
476
-            if(isset($conf['proxy']['host'], $conf['proxy']['port']) && $conf['proxy']['host'] !== '' && $conf['proxy']['port'] !== '') {
477
-                $opts['http'] += ['proxy' => "tcp://" . $conf['proxy']['host'] . ":" . $conf['proxy']['port']];
478
-            }
479
-
480
-            $context = stream_context_create($opts);
481
-            dbglog("StaticMap::fetchTile: getting: $url . $this->apikey using file_get_contents and options $opts");
482
-            $tile = file_get_contents($url . $this->apikey, false, $context);
483
-        }
484
-        if($tile && $this->useTileCache) {
485
-            $this->writeTileToCache($url, $tile);
486
-        }
487
-        return $tile;
488
-    }
489
-
490
-    /**
491
-     *
492
-     * @param string $url
493
-     * @return string|false
494
-     */
495
-    public function checkTileCache(string $url) {
496
-        $filename = $this->tileUrlToFilename($url);
497
-        if(file_exists($filename)) {
498
-            return file_get_contents($filename);
499
-        }
500
-        return false;
501
-    }
502
-
503
-    /**
504
-     *
505
-     * @param string $url
506
-     * @return string
507
-     */
508
-    public function tileUrlToFilename(string $url): string {
509
-        return $this->tileCacheBaseDir . "/" . substr($url, strpos($url, '/') + 1);
510
-    }
511
-
512
-    /**
513
-     * Write a tile into the cache.
514
-     *
515
-     * @param string $url
516
-     * @param mixed  $data
517
-     */
518
-    public function writeTileToCache($url, $data): void {
519
-        $filename = $this->tileUrlToFilename($url);
520
-        $this->mkdirRecursive(dirname($filename), 0777);
521
-        file_put_contents($filename, $data);
522
-    }
523
-
524
-    /**
525
-     * Recursively create the directory.
526
-     *
527
-     * @param string $pathname
528
-     *            The directory path.
529
-     * @param int    $mode
530
-     *            File access mode. For more information on modes, read the details on the chmod manpage.
531
-     */
532
-    public function mkdirRecursive(string $pathname, int $mode): bool {
533
-        is_dir(dirname($pathname)) || $this->mkdirRecursive(dirname($pathname), $mode);
534
-        return is_dir($pathname) || mkdir($pathname, $mode) || is_dir($pathname);
535
-    }
536
-
537
-    /**
538
-     * Place markers on the map and number them in the same order as they are listed in the html.
539
-     */
540
-    public function placeMarkers(): void {
541
-        $count         = 0;
542
-        $color         = imagecolorallocate($this->image, 0, 0, 0);
543
-        $bgcolor       = imagecolorallocate($this->image, 200, 200, 200);
544
-        $markerBaseDir = __DIR__ . '/icons';
545
-        // loop thru marker array
546
-        foreach($this->markers as $marker) {
547
-            // set some local variables
548
-            $markerLat  = $marker ['lat'];
549
-            $markerLon  = $marker ['lon'];
550
-            $markerType = $marker ['type'];
551
-            // clear variables from previous loops
552
-            $markerFilename = '';
553
-            $markerShadow   = '';
554
-            $matches        = false;
555
-            // check for marker type, get settings from markerPrototypes
556
-            if($markerType) {
557
-                foreach($this->markerPrototypes as $markerPrototype) {
558
-                    if(preg_match($markerPrototype ['regex'], $markerType, $matches)) {
559
-                        $markerFilename = $matches [0] . $markerPrototype ['extension'];
560
-                        if($markerPrototype ['offsetImage']) {
561
-                            list ($markerImageOffsetX, $markerImageOffsetY) = explode(
562
-                                ",",
563
-                                $markerPrototype ['offsetImage']
564
-                            );
565
-                        }
566
-                        $markerShadow = $markerPrototype ['shadow'];
567
-                        if($markerShadow) {
568
-                            list ($markerShadowOffsetX, $markerShadowOffsetY) = explode(
569
-                                ",",
570
-                                $markerPrototype ['offsetShadow']
571
-                            );
572
-                        }
573
-                    }
574
-                }
575
-            }
576
-            // create img resource
577
-            if(file_exists($markerBaseDir . '/' . $markerFilename)) {
578
-                $markerImg = imagecreatefrompng($markerBaseDir . '/' . $markerFilename);
579
-            } else {
580
-                $markerImg = imagecreatefrompng($markerBaseDir . '/marker.png');
581
-            }
582
-            // check for shadow + create shadow recource
583
-            if($markerShadow && file_exists($markerBaseDir . '/' . $markerShadow)) {
584
-                $markerShadowImg = imagecreatefrompng($markerBaseDir . '/' . $markerShadow);
585
-            }
586
-            // calc position
587
-            $destX = floor(
588
-                ($this->width / 2) -
589
-                $this->tileSize * ($this->centerX - $this->lonToTile($markerLon, $this->zoom))
590
-            );
591
-            $destY = floor(
592
-                ($this->height / 2) -
593
-                $this->tileSize * ($this->centerY - $this->latToTile($markerLat, $this->zoom))
594
-            );
595
-            // copy shadow on basemap
596
-            if($markerShadow && $markerShadowImg) {
597
-                imagecopy(
598
-                    $this->image,
599
-                    $markerShadowImg,
600
-                    $destX + (int) $markerShadowOffsetX,
601
-                    $destY + (int) $markerShadowOffsetY,
602
-                    0,
603
-                    0,
604
-                    imagesx($markerShadowImg),
605
-                    imagesy($markerShadowImg)
606
-                );
607
-            }
608
-            // copy marker on basemap above shadow
609
-            imagecopy(
610
-                $this->image,
611
-                $markerImg,
612
-                $destX + (int) $markerImageOffsetX,
613
-                $destY + (int) $markerImageOffsetY,
614
-                0,
615
-                0,
616
-                imagesx($markerImg),
617
-                imagesy($markerImg)
618
-            );
619
-            // add label
620
-            imagestring(
621
-                $this->image,
622
-                3,
623
-                $destX - imagesx($markerImg) + 1,
624
-                $destY + (int) $markerImageOffsetY + 1,
625
-                ++$count,
626
-                $bgcolor
627
-            );
628
-            imagestring(
629
-                $this->image,
630
-                3,
631
-                $destX - imagesx($markerImg),
632
-                $destY + (int) $markerImageOffsetY,
633
-                $count,
634
-                $color
635
-            );
636
-        }
637
-    }
638
-
639
-    /**
640
-     * Draw kml trace on the map.
641
-     */
642
-    public function drawKML(): void {
643
-        // TODO get colour from kml node (not currently supported in geoPHP)
644
-        $col     = imagecolorallocatealpha($this->image, 255, 0, 0, .4 * 127);
645
-        $kmlgeom = geoPHP::load(file_get_contents($this->kmlFileName), 'kml');
646
-        $this->drawGeometry($kmlgeom, $col);
647
-    }
648
-
649
-    /**
650
-     * Draw geometry or geometry collection on the map.
651
-     *
652
-     * @param Geometry $geom
653
-     * @param int      $colour
654
-     *            drawing colour
655
-     */
656
-    private function drawGeometry(Geometry $geom, int $colour): void {
657
-        if(empty($geom)) {
658
-            return;
659
-        }
660
-
661
-        switch($geom->geometryType()) {
662
-            case 'GeometryCollection' :
663
-                // recursively draw part of the collection
664
-                for($i = 1; $i < $geom->numGeometries() + 1; $i++) {
665
-                    $_geom = $geom->geometryN($i);
666
-                    $this->drawGeometry($_geom, $colour);
667
-                }
668
-                break;
669
-            case 'MultiPolygon' :
670
-            case 'MultiLineString' :
671
-            case 'MultiPoint' :
672
-                // TODO implement / do nothing
673
-                break;
674
-            case 'Polygon' :
675
-                $this->drawPolygon($geom, $colour);
676
-                break;
677
-            case 'LineString' :
678
-                $this->drawLineString($geom, $colour);
679
-                break;
680
-            case 'Point' :
681
-                $this->drawPoint($geom, $colour);
682
-                break;
683
-            default :
684
-                // draw nothing
685
-                break;
686
-        }
687
-    }
688
-
689
-    /**
690
-     * Draw a polygon on the map.
691
-     *
692
-     * @param Polygon $polygon
693
-     * @param int     $colour
694
-     *            drawing colour
695
-     */
696
-    private function drawPolygon($polygon, int $colour) {
697
-        // TODO implementation of drawing holes,
698
-        // maybe draw the polygon to an in-memory image and use imagecopy, draw polygon in col., draw holes in bgcol?
699
-
700
-        // print_r('Polygon:<br />');
701
-        // print_r($polygon);
702
-        $extPoints = array();
703
-        // extring is a linestring actually..
704
-        $extRing = $polygon->exteriorRing();
705
-
706
-        for($i = 1; $i < $extRing->numGeometries(); $i++) {
707
-            $p1           = $extRing->geometryN($i);
708
-            $x            = floor(
709
-                ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile($p1->x(), $this->zoom))
710
-            );
711
-            $y            = floor(
712
-                ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile($p1->y(), $this->zoom))
713
-            );
714
-            $extPoints [] = $x;
715
-            $extPoints [] = $y;
716
-        }
717
-        // print_r('points:('.($i-1).')<br />');
718
-        // print_r($extPoints);
719
-        // imagepolygon ($this->image, $extPoints, $i-1, $colour );
720
-        imagefilledpolygon($this->image, $extPoints, $i - 1, $colour);
721
-    }
722
-
723
-    /**
724
-     * Draw a line on the map.
725
-     *
726
-     * @param LineString $line
727
-     * @param int        $colour
728
-     *            drawing colour
729
-     */
730
-    private function drawLineString($line, $colour) {
731
-        imagesetthickness($this->image, 2);
732
-        for($p = 1; $p < $line->numGeometries(); $p++) {
733
-            // get first pair of points
734
-            $p1 = $line->geometryN($p);
735
-            $p2 = $line->geometryN($p + 1);
736
-            // translate to paper space
737
-            $x1 = floor(
738
-                ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile($p1->x(), $this->zoom))
739
-            );
740
-            $y1 = floor(
741
-                ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile($p1->y(), $this->zoom))
742
-            );
743
-            $x2 = floor(
744
-                ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile($p2->x(), $this->zoom))
745
-            );
746
-            $y2 = floor(
747
-                ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile($p2->y(), $this->zoom))
748
-            );
749
-            // draw to image
750
-            imageline($this->image, $x1, $y1, $x2, $y2, $colour);
751
-        }
752
-        imagesetthickness($this->image, 1);
753
-    }
754
-
755
-    /**
756
-     * Draw a point on the map.
757
-     *
758
-     * @param Point $point
759
-     * @param int   $colour
760
-     *            drawing colour
761
-     */
762
-    private function drawPoint($point, $colour) {
763
-        imagesetthickness($this->image, 2);
764
-        // translate to paper space
765
-        $cx = floor(
766
-            ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile($point->x(), $this->zoom))
767
-        );
768
-        $cy = floor(
769
-            ($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile($point->y(), $this->zoom))
770
-        );
771
-        $r  = 5;
772
-        // draw to image
773
-        // imageellipse($this->image, $cx, $cy,$r, $r, $colour);
774
-        imagefilledellipse($this->image, $cx, $cy, $r, $r, $colour);
775
-        // don't use imageellipse because the imagesetthickness function has
776
-        // no effect. So the better workaround is to use imagearc.
777
-        imagearc($this->image, $cx, $cy, $r, $r, 0, 359, $colour);
778
-        imagesetthickness($this->image, 1);
779
-    }
780
-
781
-    /**
782
-     * Draw gpx trace on the map.
783
-     */
784
-    public function drawGPX() {
785
-        $col     = imagecolorallocatealpha($this->image, 0, 0, 255, .4 * 127);
786
-        $gpxgeom = geoPHP::load(file_get_contents($this->gpxFileName), 'gpx');
787
-        $this->drawGeometry($gpxgeom, $col);
788
-    }
789
-
790
-    /**
791
-     * Draw geojson on the map.
792
-     */
793
-    public function drawGeojson() {
794
-        $col     = imagecolorallocatealpha($this->image, 255, 0, 255, .4 * 127);
795
-        $gpxgeom = geoPHP::load(file_get_contents($this->geojsonFileName), 'json');
796
-        $this->drawGeometry($gpxgeom, $col);
797
-    }
798
-
799
-    /**
800
-     * add copyright and origin notice and icons to the map.
801
-     */
802
-    public function drawCopyright() {
803
-        $logoBaseDir = dirname(__FILE__) . '/' . 'logo/';
804
-        $logoImg     = imagecreatefrompng($logoBaseDir . $this->tileInfo ['openstreetmap'] ['logo']);
805
-        $textcolor   = imagecolorallocate($this->image, 0, 0, 0);
806
-        $bgcolor     = imagecolorallocate($this->image, 200, 200, 200);
807
-
808
-        imagecopy(
809
-            $this->image,
810
-            $logoImg,
811
-            0,
812
-            imagesy($this->image) - imagesy($logoImg),
813
-            0,
814
-            0,
815
-            imagesx($logoImg),
816
-            imagesy($logoImg)
817
-        );
818
-        imagestring(
819
-            $this->image,
820
-            1,
821
-            imagesx($logoImg) + 2,
822
-            imagesy($this->image) - imagesy($logoImg) + 1,
823
-            $this->tileInfo ['openstreetmap'] ['txt'],
824
-            $bgcolor
825
-        );
826
-        imagestring(
827
-            $this->image,
828
-            1,
829
-            imagesx($logoImg) + 1,
830
-            imagesy($this->image) - imagesy($logoImg),
831
-            $this->tileInfo ['openstreetmap'] ['txt'],
832
-            $textcolor
833
-        );
834
-
835
-        // additional tile source info, ie. who created/hosted the tiles
836
-        $xIconOffset = 0;
837
-        if($this->maptype === 'openstreetmap') {
838
-            $mapAuthor = "(c) OpenStreetMap maps/CC BY-SA";
839
-        } else {
840
-            $mapAuthor   = $this->tileInfo [$this->maptype] ['txt'];
841
-            $iconImg     = imagecreatefrompng($logoBaseDir . $this->tileInfo [$this->maptype] ['logo']);
842
-            $xIconOffset = imagesx($iconImg);
843
-            imagecopy(
844
-                $this->image,
845
-                $iconImg, imagesx($logoImg) + 1,
846
-                imagesy($this->image) - imagesy($iconImg),
847
-                0,
848
-                0,
849
-                imagesx($iconImg), imagesy($iconImg)
850
-            );
851
-        }
852
-        imagestring(
853
-            $this->image,
854
-            1, imagesx($logoImg) + $xIconOffset + 4,
855
-            imagesy($this->image) - ceil(imagesy($logoImg) / 2) + 1,
856
-            $mapAuthor,
857
-            $bgcolor
858
-        );
859
-        imagestring(
860
-            $this->image,
861
-            1, imagesx($logoImg) + $xIconOffset + 3,
862
-            imagesy($this->image) - ceil(imagesy($logoImg) / 2),
863
-            $mapAuthor,
864
-            $textcolor
865
-        );
866
-
867
-    }
34
+	// the final output
35
+	private $tileSize = 256;
36
+	private $tileInfo = array(
37
+		// OSM sources
38
+		'openstreetmap' => array(
39
+			'txt'  => '(c) OpenStreetMap data/ODbl',
40
+			'logo' => 'osm_logo.png',
41
+			'url'  => 'https://tile.openstreetmap.org/{Z}/{X}/{Y}.png'
42
+		),
43
+		// OCM sources
44
+		'cycle'         => array(
45
+			'txt'  => '(c) Thunderforest maps',
46
+			'logo' => 'tf_logo.png',
47
+			'url'  => 'https://tile.thunderforest.com/cycle/{Z}/{X}/{Y}.png'
48
+		),
49
+		'transport'     => array(
50
+			'txt'  => '(c) Thunderforest maps',
51
+			'logo' => 'tf_logo.png',
52
+			'url'  => 'https://tile.thunderforest.com/transport/{Z}/{X}/{Y}.png'
53
+		),
54
+		'landscape'     => array(
55
+			'txt'  => '(c) Thunderforest maps',
56
+			'logo' => 'tf_logo.png',
57
+			'url'  => 'https://tile.thunderforest.com/landscape/{Z}/{X}/{Y}.png'
58
+		),
59
+		'outdoors'      => array(
60
+			'txt'  => '(c) Thunderforest maps',
61
+			'logo' => 'tf_logo.png',
62
+			'url'  => 'https://tile.thunderforest.com/outdoors/{Z}/{X}/{Y}.png'
63
+		),
64
+		'toner-lite'    => array(
65
+			'txt'  => 'Stamen tiles',
66
+			'logo' => 'stamen.png',
67
+			'url'  => 'http://tile.stamen.com/toner-lite/{Z}/{X}/{Y}.png'
68
+		),
69
+		'terrain'       => array(
70
+			'txt'  => 'Stamen tiles',
71
+			'logo' => 'stamen.png',
72
+			'url'  => 'http://tile.stamen.com/terrain/{Z}/{X}/{Y}.png'
73
+		)
74
+		//,
75
+		// 'piste'=>array(
76
+		// 'txt'=>'OpenPisteMap tiles',
77
+		// 'logo'=>'piste_logo.png',
78
+		// 'url'=>''),
79
+		// 'sea'=>array(
80
+		// 'txt'=>'OpenSeaMap tiles',
81
+		// 'logo'=>'sea_logo.png',
82
+		// 'url'=>''),
83
+		// H&B sources
84
+		//          'hikeandbike' => array (
85
+		//                  'txt' => 'Hike & Bike Map',
86
+		//                  'logo' => 'hnb_logo.png',
87
+		//                  //'url' => 'http://toolserver.org/tiles/hikebike/{Z}/{X}/{Y}.png'
88
+		//                  //moved to: https://www.toolserver.org/tiles/hikebike/12/2105/1388.png
89
+		//                  'url' => 'http://c.tiles.wmflabs.org/hikebike/{Z}/{X}/{Y}.png'
90
+		//          )
91
+	);
92
+	private $tileDefaultSrc = 'openstreetmap';
93
+
94
+	// set up markers
95
+	private $markerPrototypes = array(
96
+		// found at http://www.mapito.net/map-marker-icons.html
97
+		// these are 17x19 px with a pointer at the bottom left
98
+		'lightblue' => array(
99
+			'regex'        => '/^lightblue([0-9]+)$/',
100
+			'extension'    => '.png',
101
+			'shadow'       => false,
102
+			'offsetImage'  => '0,-19',
103
+			'offsetShadow' => false
104
+		),
105
+		// openlayers std markers are 21x25px with shadow
106
+		'ol-marker' => array(
107
+			'regex'        => '/^marker(|-blue|-gold|-green|-red)+$/',
108
+			'extension'    => '.png',
109
+			'shadow'       => 'marker_shadow.png',
110
+			'offsetImage'  => '-10,-25',
111
+			'offsetShadow' => '-1,-13'
112
+		),
113
+		// these are 16x16 px
114
+		'ww_icon'   => array(
115
+			'regex'        => '/ww_\S+$/',
116
+			'extension'    => '.png',
117
+			'shadow'       => false,
118
+			'offsetImage'  => '-8,-8',
119
+			'offsetShadow' => false
120
+		),
121
+		// assume these are 16x16 px
122
+		'rest'      => array(
123
+			'regex'        => '/^(?!lightblue([0-9]+)$)(?!(ww_\S+$))(?!marker(|-blue|-gold|-green|-red)+$)(.*)/',
124
+			'extension'    => '.png',
125
+			'shadow'       => 'marker_shadow.png',
126
+			'offsetImage'  => '-8,-8',
127
+			'offsetShadow' => '-1,-1'
128
+		)
129
+	);
130
+	private $centerX;
131
+	private $centerY;
132
+	private $offsetX;
133
+	private $offsetY;
134
+	private $image;
135
+	private $zoom;
136
+	private $lat;
137
+	private $lon;
138
+	private $width;
139
+	private $height;
140
+	private $markers;
141
+	private $maptype;
142
+	private $kmlFileName;
143
+	private $gpxFileName;
144
+	private $geojsonFileName;
145
+	private $autoZoomExtent;
146
+	private $apikey;
147
+	private $tileCacheBaseDir;
148
+	private $mapCacheBaseDir;
149
+	private $mediaBaseDir;
150
+	private $useTileCache;
151
+	private $mapCacheID = '';
152
+	private $mapCacheFile = '';
153
+	private $mapCacheExtension = 'png';
154
+
155
+	/**
156
+	 * Constructor.
157
+	 *
158
+	 * @param float  $lat
159
+	 *            Latitude (x) of center of map
160
+	 * @param float  $lon
161
+	 *            Longitude (y) of center of map
162
+	 * @param int    $zoom
163
+	 *            Zoomlevel
164
+	 * @param int    $width
165
+	 *            Width in pixels
166
+	 * @param int    $height
167
+	 *            Height in pixels
168
+	 * @param string $maptype
169
+	 *            Name of the map
170
+	 * @param array  $markers
171
+	 *            array of markers
172
+	 * @param string $gpx
173
+	 *            GPX filename
174
+	 * @param string $kml
175
+	 *            KML filename
176
+	 * @param string $geojson
177
+	 * @param string $mediaDir
178
+	 *            Directory to store/cache maps
179
+	 * @param string $tileCacheBaseDir
180
+	 *            Directory to cache map tiles
181
+	 * @param bool   $autoZoomExtent
182
+	 *            Wheter or not to override zoom/lat/lon and zoom to the extent of gpx/kml and markers
183
+	 * @param string $apikey
184
+	 */
185
+	public function __construct(
186
+		float $lat,
187
+		float $lon,
188
+		int $zoom,
189
+		int $width,
190
+		int $height,
191
+		string $maptype,
192
+		array $markers,
193
+		string $gpx,
194
+		string $kml,
195
+		string $geojson,
196
+		string $mediaDir,
197
+		string $tileCacheBaseDir,
198
+		bool $autoZoomExtent = true,
199
+		string $apikey = ''
200
+	) {
201
+		$this->zoom   = $zoom;
202
+		$this->lat    = $lat;
203
+		$this->lon    = $lon;
204
+		$this->width  = $width;
205
+		$this->height = $height;
206
+		// validate + set maptype
207
+		$this->maptype = $this->tileDefaultSrc;
208
+		if(array_key_exists($maptype, $this->tileInfo)) {
209
+			$this->maptype = $maptype;
210
+		}
211
+		$this->markers          = $markers;
212
+		$this->kmlFileName      = $kml;
213
+		$this->gpxFileName      = $gpx;
214
+		$this->geojsonFileName  = $geojson;
215
+		$this->mediaBaseDir     = $mediaDir;
216
+		$this->tileCacheBaseDir = $tileCacheBaseDir . '/olmaptiles';
217
+		$this->useTileCache     = $this->tileCacheBaseDir !== '';
218
+		$this->mapCacheBaseDir  = $mediaDir . '/olmapmaps';
219
+		$this->autoZoomExtent   = $autoZoomExtent;
220
+		$this->apikey           = $apikey;
221
+	}
222
+
223
+	/**
224
+	 * get the map, this may return a reference to a cached copy.
225
+	 *
226
+	 * @return string url relative to media dir
227
+	 */
228
+	public function getMap(): string {
229
+		try {
230
+			if($this->autoZoomExtent) {
231
+				$this->autoZoom();
232
+			}
233
+		} catch(Exception $e) {
234
+			dbglog($e);
235
+		}
236
+
237
+		// use map cache, so check cache for map
238
+		if(!$this->checkMapCache()) {
239
+			// map is not in cache, needs to be build
240
+			$this->makeMap();
241
+			$this->mkdirRecursive(dirname($this->mapCacheIDToFilename()), 0777);
242
+			imagepng($this->image, $this->mapCacheIDToFilename(), 9);
243
+		}
244
+		$doc = $this->mapCacheIDToFilename();
245
+		// make url relative to media dir
246
+		return str_replace($this->mediaBaseDir, '', $doc);
247
+	}
248
+
249
+	/**
250
+	 * Calculate the lat/lon/zoom values to make sure that all of the markers and gpx/kml are on the map.
251
+	 * can throw an error like
252
+	 * "Fatal error: Uncaught Exception: Cannot create a collection with non-geometries in
253
+	 * D:\www\wild-water.nl\www\dokuwiki\lib\plugins\geophp\geoPHP\lib\geometry\Collection.class.php:29"
254
+	 *
255
+	 * @param float $paddingFactor
256
+	 *            buffer constant to enlarge (>1.0) the zoom level
257
+	 * @throws Exception
258
+	 */
259
+	private function autoZoom(float $paddingFactor = 1.0): void {
260
+		$geoms    = array();
261
+		$geoms [] = new Point ($this->lon, $this->lat);
262
+		if(!empty ($this->markers)) {
263
+			foreach($this->markers as $marker) {
264
+				$geoms [] = new Point ($marker ['lon'], $marker ['lat']);
265
+			}
266
+		}
267
+		if(file_exists($this->kmlFileName)) {
268
+			$g = geoPHP::load(file_get_contents($this->kmlFileName), 'kml');
269
+			if($g !== false) {
270
+				$geoms [] = $g;
271
+			}
272
+		}
273
+		if(file_exists($this->gpxFileName)) {
274
+			$g = geoPHP::load(file_get_contents($this->gpxFileName), 'gpx');
275
+			if($g !== false) {
276
+				$geoms [] = $g;
277
+			}
278
+		}
279
+		if(file_exists($this->geojsonFileName)) {
280
+			$g = geoPHP::load(file_get_contents($this->geojsonFileName), 'geojson');
281
+			if($g !== false) {
282
+				$geoms [] = $g;
283
+			}
284
+		}
285
+
286
+		if(count($geoms) <= 1) {
287
+			dbglog($geoms, "StaticMap::autoZoom: Skip setting autozoom options");
288
+			return;
289
+		}
290
+
291
+		$geom     = new GeometryCollection ($geoms);
292
+		$centroid = $geom->centroid();
293
+		$bbox     = $geom->getBBox();
294
+
295
+		// determine vertical resolution, this depends on the distance from the equator
296
+		// $vy00 = log(tan(M_PI*(0.25 + $centroid->getY()/360)));
297
+		$vy0 = log(tan(M_PI * (0.25 + $bbox ['miny'] / 360)));
298
+		$vy1 = log(tan(M_PI * (0.25 + $bbox ['maxy'] / 360)));
299
+		dbglog("StaticMap::autoZoom: vertical resolution: $vy0, $vy1");
300
+		$zoomFactorPowered  = ($this->height / 2) / (40.7436654315252 * ($vy1 - $vy0));
301
+		$resolutionVertical = 360 / ($zoomFactorPowered * $this->tileSize);
302
+		// determine horizontal resolution
303
+		$resolutionHorizontal = ($bbox ['maxx'] - $bbox ['minx']) / $this->width;
304
+		$resolution           = max($resolutionHorizontal, $resolutionVertical) * $paddingFactor;
305
+		$zoom                 = log(360 / ($resolution * $this->tileSize), 2);
306
+
307
+		if(is_finite($zoom) && $zoom < 15 && $zoom > 2) {
308
+			$this->zoom = floor($zoom);
309
+		}
310
+		$this->lon = $centroid->getX();
311
+		$this->lat = $centroid->getY();
312
+		dbglog("StaticMap::autoZoom: Set autozoom options to: z: $this->zoom, lon: $this->lon, lat: $this->lat");
313
+	}
314
+
315
+	public function checkMapCache(): bool {
316
+		// side effect: set the mapCacheID
317
+		$this->mapCacheID = md5($this->serializeParams());
318
+		$filename         = $this->mapCacheIDToFilename();
319
+		return file_exists($filename);
320
+	}
321
+
322
+	public function serializeParams(): string {
323
+		return join(
324
+			"&", array(
325
+				   $this->zoom,
326
+				   $this->lat,
327
+				   $this->lon,
328
+				   $this->width,
329
+				   $this->height,
330
+				   serialize($this->markers),
331
+				   $this->maptype,
332
+				   $this->kmlFileName,
333
+				   $this->gpxFileName,
334
+				   $this->geojsonFileName
335
+			   )
336
+		);
337
+	}
338
+
339
+	public function mapCacheIDToFilename(): string {
340
+		if(!$this->mapCacheFile) {
341
+			$this->mapCacheFile = $this->mapCacheBaseDir . "/" . $this->maptype . "/" . $this->zoom . "/cache_"
342
+				. substr($this->mapCacheID, 0, 2) . "/" . substr($this->mapCacheID, 2, 2)
343
+				. "/" . substr($this->mapCacheID, 4);
344
+		}
345
+		return $this->mapCacheFile . "." . $this->mapCacheExtension;
346
+	}
347
+
348
+	/**
349
+	 * make the map.
350
+	 */
351
+	public function makeMap(): void {
352
+		$this->initCoords();
353
+		$this->createBaseMap();
354
+		if(!empty ($this->markers))
355
+			$this->placeMarkers();
356
+		if(file_exists($this->kmlFileName))
357
+			$this->drawKML();
358
+		if(file_exists($this->gpxFileName))
359
+			$this->drawGPX();
360
+		if(file_exists($this->geojsonFileName))
361
+			$this->drawGeojson();
362
+
363
+		$this->drawCopyright();
364
+	}
365
+
366
+	/**
367
+	 */
368
+	public function initCoords(): void {
369
+		$this->centerX = $this->lonToTile($this->lon, $this->zoom);
370
+		$this->centerY = $this->latToTile($this->lat, $this->zoom);
371
+		$this->offsetX = floor((floor($this->centerX) - $this->centerX) * $this->tileSize);
372
+		$this->offsetY = floor((floor($this->centerY) - $this->centerY) * $this->tileSize);
373
+	}
374
+
375
+	/**
376
+	 *
377
+	 * @param float $long
378
+	 * @param int   $zoom
379
+	 * @return float|int
380
+	 */
381
+	public function lonToTile(float $long, int $zoom) {
382
+		return (($long + 180) / 360) * pow(2, $zoom);
383
+	}
384
+
385
+	/**
386
+	 *
387
+	 * @param float $lat
388
+	 * @param int   $zoom
389
+	 * @return float|int
390
+	 */
391
+	public function latToTile(float $lat, int $zoom) {
392
+		return (1 - log(tan($lat * pi() / 180) + 1 / cos($lat * M_PI / 180)) / M_PI) / 2 * pow(2, $zoom);
393
+	}
394
+
395
+	/**
396
+	 * make basemap image.
397
+	 */
398
+	public function createBaseMap(): void {
399
+		$this->image   = imagecreatetruecolor($this->width, $this->height);
400
+		$startX        = floor($this->centerX - ($this->width / $this->tileSize) / 2);
401
+		$startY        = floor($this->centerY - ($this->height / $this->tileSize) / 2);
402
+		$endX          = ceil($this->centerX + ($this->width / $this->tileSize) / 2);
403
+		$endY          = ceil($this->centerY + ($this->height / $this->tileSize) / 2);
404
+		$this->offsetX = -floor(($this->centerX - floor($this->centerX)) * $this->tileSize);
405
+		$this->offsetY = -floor(($this->centerY - floor($this->centerY)) * $this->tileSize);
406
+		$this->offsetX += floor($this->width / 2);
407
+		$this->offsetY += floor($this->height / 2);
408
+		$this->offsetX += floor($startX - floor($this->centerX)) * $this->tileSize;
409
+		$this->offsetY += floor($startY - floor($this->centerY)) * $this->tileSize;
410
+
411
+		for($x = $startX; $x <= $endX; $x++) {
412
+			for($y = $startY; $y <= $endY; $y++) {
413
+				$url = str_replace(
414
+					array(
415
+						'{Z}',
416
+						'{X}',
417
+						'{Y}'
418
+					), array(
419
+						$this->zoom,
420
+						$x,
421
+						$y
422
+					), $this->tileInfo [$this->maptype] ['url']
423
+				);
424
+
425
+				$tileData = $this->fetchTile($url);
426
+				if($tileData) {
427
+					$tileImage = imagecreatefromstring($tileData);
428
+				} else {
429
+					$tileImage = imagecreate($this->tileSize, $this->tileSize);
430
+					$color     = imagecolorallocate($tileImage, 255, 255, 255);
431
+					@imagestring($tileImage, 1, 127, 127, 'err', $color);
432
+				}
433
+				$destX = ($x - $startX) * $this->tileSize + $this->offsetX;
434
+				$destY = ($y - $startY) * $this->tileSize + $this->offsetY;
435
+				dbglog($this->tileSize, "imagecopy tile into image: $destX, $destY");
436
+				imagecopy(
437
+					$this->image, $tileImage, $destX, $destY, 0, 0, $this->tileSize,
438
+					$this->tileSize
439
+				);
440
+			}
441
+		}
442
+	}
443
+
444
+	/**
445
+	 * Fetch a tile and (if configured) store it in the cache.
446
+	 * @param string $url
447
+	 * @return bool|string
448
+	 * @todo refactor this to use dokuwiki\HTTP\HTTPClient or dokuwiki\HTTP\DokuHTTPClient
449
+	 *          for better proxy handling...
450
+	 */
451
+	public function fetchTile(string $url) {
452
+		if($this->useTileCache && ($cached = $this->checkTileCache($url)))
453
+			return $cached;
454
+
455
+		$_UA = 'Mozilla/4.0 (compatible; DokuWikiSpatial HTTP Client; ' . PHP_OS . ')';
456
+		if(function_exists("curl_init")) {
457
+			// use cUrl
458
+			$ch = curl_init();
459
+			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
460
+			curl_setopt($ch, CURLOPT_USERAGENT, $_UA);
461
+			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
462
+			curl_setopt($ch, CURLOPT_URL, $url . $this->apikey);
463
+			dbglog("StaticMap::fetchTile: getting: $url using curl_exec");
464
+			$tile = curl_exec($ch);
465
+			curl_close($ch);
466
+		} else {
467
+			// use file_get_contents
468
+			global $conf;
469
+			$opts = array(
470
+				'http' => array(
471
+					'method'          => "GET",
472
+					'header'          => "Accept-language: en\r\n" . "User-Agent: $_UA\r\n" . "accept: image/png\r\n",
473
+					'request_fulluri' => true
474
+				)
475
+			);
476
+			if(isset($conf['proxy']['host'], $conf['proxy']['port']) && $conf['proxy']['host'] !== '' && $conf['proxy']['port'] !== '') {
477
+				$opts['http'] += ['proxy' => "tcp://" . $conf['proxy']['host'] . ":" . $conf['proxy']['port']];
478
+			}
479
+
480
+			$context = stream_context_create($opts);
481
+			dbglog("StaticMap::fetchTile: getting: $url . $this->apikey using file_get_contents and options $opts");
482
+			$tile = file_get_contents($url . $this->apikey, false, $context);
483
+		}
484
+		if($tile && $this->useTileCache) {
485
+			$this->writeTileToCache($url, $tile);
486
+		}
487
+		return $tile;
488
+	}
489
+
490
+	/**
491
+	 *
492
+	 * @param string $url
493
+	 * @return string|false
494
+	 */
495
+	public function checkTileCache(string $url) {
496
+		$filename = $this->tileUrlToFilename($url);
497
+		if(file_exists($filename)) {
498
+			return file_get_contents($filename);
499
+		}
500
+		return false;
501
+	}
502
+
503
+	/**
504
+	 *
505
+	 * @param string $url
506
+	 * @return string
507
+	 */
508
+	public function tileUrlToFilename(string $url): string {
509
+		return $this->tileCacheBaseDir . "/" . substr($url, strpos($url, '/') + 1);
510
+	}
511
+
512
+	/**
513
+	 * Write a tile into the cache.
514
+	 *
515
+	 * @param string $url
516
+	 * @param mixed  $data
517
+	 */
518
+	public function writeTileToCache($url, $data): void {
519
+		$filename = $this->tileUrlToFilename($url);
520
+		$this->mkdirRecursive(dirname($filename), 0777);
521
+		file_put_contents($filename, $data);
522
+	}
523
+
524
+	/**
525
+	 * Recursively create the directory.
526
+	 *
527
+	 * @param string $pathname
528
+	 *            The directory path.
529
+	 * @param int    $mode
530
+	 *            File access mode. For more information on modes, read the details on the chmod manpage.
531
+	 */
532
+	public function mkdirRecursive(string $pathname, int $mode): bool {
533
+		is_dir(dirname($pathname)) || $this->mkdirRecursive(dirname($pathname), $mode);
534
+		return is_dir($pathname) || mkdir($pathname, $mode) || is_dir($pathname);
535
+	}
536
+
537
+	/**
538
+	 * Place markers on the map and number them in the same order as they are listed in the html.
539
+	 */
540
+	public function placeMarkers(): void {
541
+		$count         = 0;
542
+		$color         = imagecolorallocate($this->image, 0, 0, 0);
543
+		$bgcolor       = imagecolorallocate($this->image, 200, 200, 200);
544
+		$markerBaseDir = __DIR__ . '/icons';
545
+		// loop thru marker array
546
+		foreach($this->markers as $marker) {
547
+			// set some local variables
548
+			$markerLat  = $marker ['lat'];
549
+			$markerLon  = $marker ['lon'];
550
+			$markerType = $marker ['type'];
551
+			// clear variables from previous loops
552
+			$markerFilename = '';
553
+			$markerShadow   = '';
554
+			$matches        = false;
555
+			// check for marker type, get settings from markerPrototypes
556
+			if($markerType) {
557
+				foreach($this->markerPrototypes as $markerPrototype) {
558
+					if(preg_match($markerPrototype ['regex'], $markerType, $matches)) {
559
+						$markerFilename = $matches [0] . $markerPrototype ['extension'];
560
+						if($markerPrototype ['offsetImage']) {
561
+							list ($markerImageOffsetX, $markerImageOffsetY) = explode(
562
+								",",
563
+								$markerPrototype ['offsetImage']
564
+							);
565
+						}
566
+						$markerShadow = $markerPrototype ['shadow'];
567
+						if($markerShadow) {
568
+							list ($markerShadowOffsetX, $markerShadowOffsetY) = explode(
569
+								",",
570
+								$markerPrototype ['offsetShadow']
571
+							);
572
+						}
573
+					}
574
+				}
575
+			}
576
+			// create img resource
577
+			if(file_exists($markerBaseDir . '/' . $markerFilename)) {
578
+				$markerImg = imagecreatefrompng($markerBaseDir . '/' . $markerFilename);
579
+			} else {
580
+				$markerImg = imagecreatefrompng($markerBaseDir . '/marker.png');
581
+			}
582
+			// check for shadow + create shadow recource
583
+			if($markerShadow && file_exists($markerBaseDir . '/' . $markerShadow)) {
584
+				$markerShadowImg = imagecreatefrompng($markerBaseDir . '/' . $markerShadow);
585
+			}
586
+			// calc position
587
+			$destX = floor(
588
+				($this->width / 2) -
589
+				$this->tileSize * ($this->centerX - $this->lonToTile($markerLon, $this->zoom))
590
+			);
591
+			$destY = floor(
592
+				($this->height / 2) -
593
+				$this->tileSize * ($this->centerY - $this->latToTile($markerLat, $this->zoom))
594
+			);
595
+			// copy shadow on basemap
596
+			if($markerShadow && $markerShadowImg) {
597
+				imagecopy(
598
+					$this->image,
599
+					$markerShadowImg,
600
+					$destX + (int) $markerShadowOffsetX,
601
+					$destY + (int) $markerShadowOffsetY,
602
+					0,
603
+					0,
604
+					imagesx($markerShadowImg),
605
+					imagesy($markerShadowImg)
606
+				);
607
+			}
608
+			// copy marker on basemap above shadow
609
+			imagecopy(
610
+				$this->image,
611
+				$markerImg,
612
+				$destX + (int) $markerImageOffsetX,
613
+				$destY + (int) $markerImageOffsetY,
614
+				0,
615
+				0,
616
+				imagesx($markerImg),
617
+				imagesy($markerImg)
618
+			);
619
+			// add label
620
+			imagestring(
621
+				$this->image,
622
+				3,
623
+				$destX - imagesx($markerImg) + 1,
624
+				$destY + (int) $markerImageOffsetY + 1,
625
+				++$count,
626
+				$bgcolor
627
+			);
628
+			imagestring(
629
+				$this->image,
630
+				3,
631
+				$destX - imagesx($markerImg),
632
+				$destY + (int) $markerImageOffsetY,
633
+				$count,
634
+				$color
635
+			);
636
+		}
637
+	}
638
+
639
+	/**
640
+	 * Draw kml trace on the map.
641
+	 */
642
+	public function drawKML(): void {
643
+		// TODO get colour from kml node (not currently supported in geoPHP)
644
+		$col     = imagecolorallocatealpha($this->image, 255, 0, 0, .4 * 127);
645
+		$kmlgeom = geoPHP::load(file_get_contents($this->kmlFileName), 'kml');
646
+		$this->drawGeometry($kmlgeom, $col);
647
+	}
648
+
649
+	/**
650
+	 * Draw geometry or geometry collection on the map.
651
+	 *
652
+	 * @param Geometry $geom
653
+	 * @param int      $colour
654
+	 *            drawing colour
655
+	 */
656
+	private function drawGeometry(Geometry $geom, int $colour): void {
657
+		if(empty($geom)) {
658
+			return;
659
+		}
660
+
661
+		switch($geom->geometryType()) {
662
+			case 'GeometryCollection' :
663
+				// recursively draw part of the collection
664
+				for($i = 1; $i < $geom->numGeometries() + 1; $i++) {
665
+					$_geom = $geom->geometryN($i);
666
+					$this->drawGeometry($_geom, $colour);
667
+				}
668
+				break;
669
+			case 'MultiPolygon' :
670
+			case 'MultiLineString' :
671
+			case 'MultiPoint' :
672
+				// TODO implement / do nothing
673
+				break;
674
+			case 'Polygon' :
675
+				$this->drawPolygon($geom, $colour);
676
+				break;
677
+			case 'LineString' :
678
+				$this->drawLineString($geom, $colour);
679
+				break;
680
+			case 'Point' :
681
+				$this->drawPoint($geom, $colour);
682
+				break;
683
+			default :
684
+				// draw nothing
685
+				break;
686
+		}
687
+	}
688
+
689
+	/**
690
+	 * Draw a polygon on the map.
691
+	 *
692
+	 * @param Polygon $polygon
693
+	 * @param int     $colour
694
+	 *            drawing colour
695
+	 */
696
+	private function drawPolygon($polygon, int $colour) {
697
+		// TODO implementation of drawing holes,
698
+		// maybe draw the polygon to an in-memory image and use imagecopy, draw polygon in col., draw holes in bgcol?
699
+
700
+		// print_r('Polygon:<br />');
701
+		// print_r($polygon);
702
+		$extPoints = array();
703
+		// extring is a linestring actually..
704
+		$extRing = $polygon->exteriorRing();
705
+
706
+		for($i = 1; $i < $extRing->numGeometries(); $i++) {
707
+			$p1           = $extRing->geometryN($i);
708
+			$x            = floor(
709
+				($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile($p1->x(), $this->zoom))
710
+			);
711
+			$y            = floor(
712
+				($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile($p1->y(), $this->zoom))
713
+			);
714
+			$extPoints [] = $x;
715
+			$extPoints [] = $y;
716
+		}
717
+		// print_r('points:('.($i-1).')<br />');
718
+		// print_r($extPoints);
719
+		// imagepolygon ($this->image, $extPoints, $i-1, $colour );
720
+		imagefilledpolygon($this->image, $extPoints, $i - 1, $colour);
721
+	}
722
+
723
+	/**
724
+	 * Draw a line on the map.
725
+	 *
726
+	 * @param LineString $line
727
+	 * @param int        $colour
728
+	 *            drawing colour
729
+	 */
730
+	private function drawLineString($line, $colour) {
731
+		imagesetthickness($this->image, 2);
732
+		for($p = 1; $p < $line->numGeometries(); $p++) {
733
+			// get first pair of points
734
+			$p1 = $line->geometryN($p);
735
+			$p2 = $line->geometryN($p + 1);
736
+			// translate to paper space
737
+			$x1 = floor(
738
+				($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile($p1->x(), $this->zoom))
739
+			);
740
+			$y1 = floor(
741
+				($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile($p1->y(), $this->zoom))
742
+			);
743
+			$x2 = floor(
744
+				($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile($p2->x(), $this->zoom))
745
+			);
746
+			$y2 = floor(
747
+				($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile($p2->y(), $this->zoom))
748
+			);
749
+			// draw to image
750
+			imageline($this->image, $x1, $y1, $x2, $y2, $colour);
751
+		}
752
+		imagesetthickness($this->image, 1);
753
+	}
754
+
755
+	/**
756
+	 * Draw a point on the map.
757
+	 *
758
+	 * @param Point $point
759
+	 * @param int   $colour
760
+	 *            drawing colour
761
+	 */
762
+	private function drawPoint($point, $colour) {
763
+		imagesetthickness($this->image, 2);
764
+		// translate to paper space
765
+		$cx = floor(
766
+			($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile($point->x(), $this->zoom))
767
+		);
768
+		$cy = floor(
769
+			($this->height / 2) - $this->tileSize * ($this->centerY - $this->latToTile($point->y(), $this->zoom))
770
+		);
771
+		$r  = 5;
772
+		// draw to image
773
+		// imageellipse($this->image, $cx, $cy,$r, $r, $colour);
774
+		imagefilledellipse($this->image, $cx, $cy, $r, $r, $colour);
775
+		// don't use imageellipse because the imagesetthickness function has
776
+		// no effect. So the better workaround is to use imagearc.
777
+		imagearc($this->image, $cx, $cy, $r, $r, 0, 359, $colour);
778
+		imagesetthickness($this->image, 1);
779
+	}
780
+
781
+	/**
782
+	 * Draw gpx trace on the map.
783
+	 */
784
+	public function drawGPX() {
785
+		$col     = imagecolorallocatealpha($this->image, 0, 0, 255, .4 * 127);
786
+		$gpxgeom = geoPHP::load(file_get_contents($this->gpxFileName), 'gpx');
787
+		$this->drawGeometry($gpxgeom, $col);
788
+	}
789
+
790
+	/**
791
+	 * Draw geojson on the map.
792
+	 */
793
+	public function drawGeojson() {
794
+		$col     = imagecolorallocatealpha($this->image, 255, 0, 255, .4 * 127);
795
+		$gpxgeom = geoPHP::load(file_get_contents($this->geojsonFileName), 'json');
796
+		$this->drawGeometry($gpxgeom, $col);
797
+	}
798
+
799
+	/**
800
+	 * add copyright and origin notice and icons to the map.
801
+	 */
802
+	public function drawCopyright() {
803
+		$logoBaseDir = dirname(__FILE__) . '/' . 'logo/';
804
+		$logoImg     = imagecreatefrompng($logoBaseDir . $this->tileInfo ['openstreetmap'] ['logo']);
805
+		$textcolor   = imagecolorallocate($this->image, 0, 0, 0);
806
+		$bgcolor     = imagecolorallocate($this->image, 200, 200, 200);
807
+
808
+		imagecopy(
809
+			$this->image,
810
+			$logoImg,
811
+			0,
812
+			imagesy($this->image) - imagesy($logoImg),
813
+			0,
814
+			0,
815
+			imagesx($logoImg),
816
+			imagesy($logoImg)
817
+		);
818
+		imagestring(
819
+			$this->image,
820
+			1,
821
+			imagesx($logoImg) + 2,
822
+			imagesy($this->image) - imagesy($logoImg) + 1,
823
+			$this->tileInfo ['openstreetmap'] ['txt'],
824
+			$bgcolor
825
+		);
826
+		imagestring(
827
+			$this->image,
828
+			1,
829
+			imagesx($logoImg) + 1,
830
+			imagesy($this->image) - imagesy($logoImg),
831
+			$this->tileInfo ['openstreetmap'] ['txt'],
832
+			$textcolor
833
+		);
834
+
835
+		// additional tile source info, ie. who created/hosted the tiles
836
+		$xIconOffset = 0;
837
+		if($this->maptype === 'openstreetmap') {
838
+			$mapAuthor = "(c) OpenStreetMap maps/CC BY-SA";
839
+		} else {
840
+			$mapAuthor   = $this->tileInfo [$this->maptype] ['txt'];
841
+			$iconImg     = imagecreatefrompng($logoBaseDir . $this->tileInfo [$this->maptype] ['logo']);
842
+			$xIconOffset = imagesx($iconImg);
843
+			imagecopy(
844
+				$this->image,
845
+				$iconImg, imagesx($logoImg) + 1,
846
+				imagesy($this->image) - imagesy($iconImg),
847
+				0,
848
+				0,
849
+				imagesx($iconImg), imagesy($iconImg)
850
+			);
851
+		}
852
+		imagestring(
853
+			$this->image,
854
+			1, imagesx($logoImg) + $xIconOffset + 4,
855
+			imagesy($this->image) - ceil(imagesy($logoImg) / 2) + 1,
856
+			$mapAuthor,
857
+			$bgcolor
858
+		);
859
+		imagestring(
860
+			$this->image,
861
+			1, imagesx($logoImg) + $xIconOffset + 3,
862
+			imagesy($this->image) - ceil(imagesy($logoImg) / 2),
863
+			$mapAuthor,
864
+			$textcolor
865
+		);
866
+
867
+	}
868 868
 }
Please login to merge, or discard this patch.
Spacing   +66 added lines, -66 removed lines patch added patch discarded remove patch
@@ -21,7 +21,7 @@  discard block
 block discarded – undo
21 21
 
22 22
 // phpcs:disable PSR1.Files.SideEffects
23 23
 // TODO resolve side effect
24
-include_once(realpath(__DIR__) . '/../geophp/geoPHP/geoPHP.inc');
24
+include_once(realpath(__DIR__).'/../geophp/geoPHP/geoPHP.inc');
25 25
 
26 26
 /**
27 27
  *
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
         $this->height = $height;
206 206
         // validate + set maptype
207 207
         $this->maptype = $this->tileDefaultSrc;
208
-        if(array_key_exists($maptype, $this->tileInfo)) {
208
+        if (array_key_exists($maptype, $this->tileInfo)) {
209 209
             $this->maptype = $maptype;
210 210
         }
211 211
         $this->markers          = $markers;
@@ -213,9 +213,9 @@  discard block
 block discarded – undo
213 213
         $this->gpxFileName      = $gpx;
214 214
         $this->geojsonFileName  = $geojson;
215 215
         $this->mediaBaseDir     = $mediaDir;
216
-        $this->tileCacheBaseDir = $tileCacheBaseDir . '/olmaptiles';
216
+        $this->tileCacheBaseDir = $tileCacheBaseDir.'/olmaptiles';
217 217
         $this->useTileCache     = $this->tileCacheBaseDir !== '';
218
-        $this->mapCacheBaseDir  = $mediaDir . '/olmapmaps';
218
+        $this->mapCacheBaseDir  = $mediaDir.'/olmapmaps';
219 219
         $this->autoZoomExtent   = $autoZoomExtent;
220 220
         $this->apikey           = $apikey;
221 221
     }
@@ -227,15 +227,15 @@  discard block
 block discarded – undo
227 227
      */
228 228
     public function getMap(): string {
229 229
         try {
230
-            if($this->autoZoomExtent) {
230
+            if ($this->autoZoomExtent) {
231 231
                 $this->autoZoom();
232 232
             }
233
-        } catch(Exception $e) {
233
+        } catch (Exception $e) {
234 234
             dbglog($e);
235 235
         }
236 236
 
237 237
         // use map cache, so check cache for map
238
-        if(!$this->checkMapCache()) {
238
+        if (!$this->checkMapCache()) {
239 239
             // map is not in cache, needs to be build
240 240
             $this->makeMap();
241 241
             $this->mkdirRecursive(dirname($this->mapCacheIDToFilename()), 0777);
@@ -258,37 +258,37 @@  discard block
 block discarded – undo
258 258
      */
259 259
     private function autoZoom(float $paddingFactor = 1.0): void {
260 260
         $geoms    = array();
261
-        $geoms [] = new Point ($this->lon, $this->lat);
262
-        if(!empty ($this->markers)) {
263
-            foreach($this->markers as $marker) {
264
-                $geoms [] = new Point ($marker ['lon'], $marker ['lat']);
261
+        $geoms [] = new Point($this->lon, $this->lat);
262
+        if (!empty ($this->markers)) {
263
+            foreach ($this->markers as $marker) {
264
+                $geoms [] = new Point($marker ['lon'], $marker ['lat']);
265 265
             }
266 266
         }
267
-        if(file_exists($this->kmlFileName)) {
267
+        if (file_exists($this->kmlFileName)) {
268 268
             $g = geoPHP::load(file_get_contents($this->kmlFileName), 'kml');
269
-            if($g !== false) {
269
+            if ($g !== false) {
270 270
                 $geoms [] = $g;
271 271
             }
272 272
         }
273
-        if(file_exists($this->gpxFileName)) {
273
+        if (file_exists($this->gpxFileName)) {
274 274
             $g = geoPHP::load(file_get_contents($this->gpxFileName), 'gpx');
275
-            if($g !== false) {
275
+            if ($g !== false) {
276 276
                 $geoms [] = $g;
277 277
             }
278 278
         }
279
-        if(file_exists($this->geojsonFileName)) {
279
+        if (file_exists($this->geojsonFileName)) {
280 280
             $g = geoPHP::load(file_get_contents($this->geojsonFileName), 'geojson');
281
-            if($g !== false) {
281
+            if ($g !== false) {
282 282
                 $geoms [] = $g;
283 283
             }
284 284
         }
285 285
 
286
-        if(count($geoms) <= 1) {
286
+        if (count($geoms) <= 1) {
287 287
             dbglog($geoms, "StaticMap::autoZoom: Skip setting autozoom options");
288 288
             return;
289 289
         }
290 290
 
291
-        $geom     = new GeometryCollection ($geoms);
291
+        $geom     = new GeometryCollection($geoms);
292 292
         $centroid = $geom->centroid();
293 293
         $bbox     = $geom->getBBox();
294 294
 
@@ -304,7 +304,7 @@  discard block
 block discarded – undo
304 304
         $resolution           = max($resolutionHorizontal, $resolutionVertical) * $paddingFactor;
305 305
         $zoom                 = log(360 / ($resolution * $this->tileSize), 2);
306 306
 
307
-        if(is_finite($zoom) && $zoom < 15 && $zoom > 2) {
307
+        if (is_finite($zoom) && $zoom < 15 && $zoom > 2) {
308 308
             $this->zoom = floor($zoom);
309 309
         }
310 310
         $this->lon = $centroid->getX();
@@ -337,12 +337,12 @@  discard block
 block discarded – undo
337 337
     }
338 338
 
339 339
     public function mapCacheIDToFilename(): string {
340
-        if(!$this->mapCacheFile) {
341
-            $this->mapCacheFile = $this->mapCacheBaseDir . "/" . $this->maptype . "/" . $this->zoom . "/cache_"
342
-                . substr($this->mapCacheID, 0, 2) . "/" . substr($this->mapCacheID, 2, 2)
343
-                . "/" . substr($this->mapCacheID, 4);
340
+        if (!$this->mapCacheFile) {
341
+            $this->mapCacheFile = $this->mapCacheBaseDir."/".$this->maptype."/".$this->zoom."/cache_"
342
+                . substr($this->mapCacheID, 0, 2)."/".substr($this->mapCacheID, 2, 2)
343
+                . "/".substr($this->mapCacheID, 4);
344 344
         }
345
-        return $this->mapCacheFile . "." . $this->mapCacheExtension;
345
+        return $this->mapCacheFile.".".$this->mapCacheExtension;
346 346
     }
347 347
 
348 348
     /**
@@ -351,13 +351,13 @@  discard block
 block discarded – undo
351 351
     public function makeMap(): void {
352 352
         $this->initCoords();
353 353
         $this->createBaseMap();
354
-        if(!empty ($this->markers))
354
+        if (!empty ($this->markers))
355 355
             $this->placeMarkers();
356
-        if(file_exists($this->kmlFileName))
356
+        if (file_exists($this->kmlFileName))
357 357
             $this->drawKML();
358
-        if(file_exists($this->gpxFileName))
358
+        if (file_exists($this->gpxFileName))
359 359
             $this->drawGPX();
360
-        if(file_exists($this->geojsonFileName))
360
+        if (file_exists($this->geojsonFileName))
361 361
             $this->drawGeojson();
362 362
 
363 363
         $this->drawCopyright();
@@ -408,8 +408,8 @@  discard block
 block discarded – undo
408 408
         $this->offsetX += floor($startX - floor($this->centerX)) * $this->tileSize;
409 409
         $this->offsetY += floor($startY - floor($this->centerY)) * $this->tileSize;
410 410
 
411
-        for($x = $startX; $x <= $endX; $x++) {
412
-            for($y = $startY; $y <= $endY; $y++) {
411
+        for ($x = $startX; $x <= $endX; $x++) {
412
+            for ($y = $startY; $y <= $endY; $y++) {
413 413
                 $url = str_replace(
414 414
                     array(
415 415
                         '{Z}',
@@ -423,7 +423,7 @@  discard block
 block discarded – undo
423 423
                 );
424 424
 
425 425
                 $tileData = $this->fetchTile($url);
426
-                if($tileData) {
426
+                if ($tileData) {
427 427
                     $tileImage = imagecreatefromstring($tileData);
428 428
                 } else {
429 429
                     $tileImage = imagecreate($this->tileSize, $this->tileSize);
@@ -449,17 +449,17 @@  discard block
 block discarded – undo
449 449
      *          for better proxy handling...
450 450
      */
451 451
     public function fetchTile(string $url) {
452
-        if($this->useTileCache && ($cached = $this->checkTileCache($url)))
452
+        if ($this->useTileCache && ($cached = $this->checkTileCache($url)))
453 453
             return $cached;
454 454
 
455
-        $_UA = 'Mozilla/4.0 (compatible; DokuWikiSpatial HTTP Client; ' . PHP_OS . ')';
456
-        if(function_exists("curl_init")) {
455
+        $_UA = 'Mozilla/4.0 (compatible; DokuWikiSpatial HTTP Client; '.PHP_OS.')';
456
+        if (function_exists("curl_init")) {
457 457
             // use cUrl
458 458
             $ch = curl_init();
459 459
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
460 460
             curl_setopt($ch, CURLOPT_USERAGENT, $_UA);
461 461
             curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
462
-            curl_setopt($ch, CURLOPT_URL, $url . $this->apikey);
462
+            curl_setopt($ch, CURLOPT_URL, $url.$this->apikey);
463 463
             dbglog("StaticMap::fetchTile: getting: $url using curl_exec");
464 464
             $tile = curl_exec($ch);
465 465
             curl_close($ch);
@@ -469,19 +469,19 @@  discard block
 block discarded – undo
469 469
             $opts = array(
470 470
                 'http' => array(
471 471
                     'method'          => "GET",
472
-                    'header'          => "Accept-language: en\r\n" . "User-Agent: $_UA\r\n" . "accept: image/png\r\n",
472
+                    'header'          => "Accept-language: en\r\n"."User-Agent: $_UA\r\n"."accept: image/png\r\n",
473 473
                     'request_fulluri' => true
474 474
                 )
475 475
             );
476
-            if(isset($conf['proxy']['host'], $conf['proxy']['port']) && $conf['proxy']['host'] !== '' && $conf['proxy']['port'] !== '') {
477
-                $opts['http'] += ['proxy' => "tcp://" . $conf['proxy']['host'] . ":" . $conf['proxy']['port']];
476
+            if (isset($conf['proxy']['host'], $conf['proxy']['port']) && $conf['proxy']['host'] !== '' && $conf['proxy']['port'] !== '') {
477
+                $opts['http'] += ['proxy' => "tcp://".$conf['proxy']['host'].":".$conf['proxy']['port']];
478 478
             }
479 479
 
480 480
             $context = stream_context_create($opts);
481 481
             dbglog("StaticMap::fetchTile: getting: $url . $this->apikey using file_get_contents and options $opts");
482
-            $tile = file_get_contents($url . $this->apikey, false, $context);
482
+            $tile = file_get_contents($url.$this->apikey, false, $context);
483 483
         }
484
-        if($tile && $this->useTileCache) {
484
+        if ($tile && $this->useTileCache) {
485 485
             $this->writeTileToCache($url, $tile);
486 486
         }
487 487
         return $tile;
@@ -494,7 +494,7 @@  discard block
 block discarded – undo
494 494
      */
495 495
     public function checkTileCache(string $url) {
496 496
         $filename = $this->tileUrlToFilename($url);
497
-        if(file_exists($filename)) {
497
+        if (file_exists($filename)) {
498 498
             return file_get_contents($filename);
499 499
         }
500 500
         return false;
@@ -506,7 +506,7 @@  discard block
 block discarded – undo
506 506
      * @return string
507 507
      */
508 508
     public function tileUrlToFilename(string $url): string {
509
-        return $this->tileCacheBaseDir . "/" . substr($url, strpos($url, '/') + 1);
509
+        return $this->tileCacheBaseDir."/".substr($url, strpos($url, '/') + 1);
510 510
     }
511 511
 
512 512
     /**
@@ -541,9 +541,9 @@  discard block
 block discarded – undo
541 541
         $count         = 0;
542 542
         $color         = imagecolorallocate($this->image, 0, 0, 0);
543 543
         $bgcolor       = imagecolorallocate($this->image, 200, 200, 200);
544
-        $markerBaseDir = __DIR__ . '/icons';
544
+        $markerBaseDir = __DIR__.'/icons';
545 545
         // loop thru marker array
546
-        foreach($this->markers as $marker) {
546
+        foreach ($this->markers as $marker) {
547 547
             // set some local variables
548 548
             $markerLat  = $marker ['lat'];
549 549
             $markerLon  = $marker ['lon'];
@@ -553,18 +553,18 @@  discard block
 block discarded – undo
553 553
             $markerShadow   = '';
554 554
             $matches        = false;
555 555
             // check for marker type, get settings from markerPrototypes
556
-            if($markerType) {
557
-                foreach($this->markerPrototypes as $markerPrototype) {
558
-                    if(preg_match($markerPrototype ['regex'], $markerType, $matches)) {
559
-                        $markerFilename = $matches [0] . $markerPrototype ['extension'];
560
-                        if($markerPrototype ['offsetImage']) {
556
+            if ($markerType) {
557
+                foreach ($this->markerPrototypes as $markerPrototype) {
558
+                    if (preg_match($markerPrototype ['regex'], $markerType, $matches)) {
559
+                        $markerFilename = $matches [0].$markerPrototype ['extension'];
560
+                        if ($markerPrototype ['offsetImage']) {
561 561
                             list ($markerImageOffsetX, $markerImageOffsetY) = explode(
562 562
                                 ",",
563 563
                                 $markerPrototype ['offsetImage']
564 564
                             );
565 565
                         }
566 566
                         $markerShadow = $markerPrototype ['shadow'];
567
-                        if($markerShadow) {
567
+                        if ($markerShadow) {
568 568
                             list ($markerShadowOffsetX, $markerShadowOffsetY) = explode(
569 569
                                 ",",
570 570
                                 $markerPrototype ['offsetShadow']
@@ -574,14 +574,14 @@  discard block
 block discarded – undo
574 574
                 }
575 575
             }
576 576
             // create img resource
577
-            if(file_exists($markerBaseDir . '/' . $markerFilename)) {
578
-                $markerImg = imagecreatefrompng($markerBaseDir . '/' . $markerFilename);
577
+            if (file_exists($markerBaseDir.'/'.$markerFilename)) {
578
+                $markerImg = imagecreatefrompng($markerBaseDir.'/'.$markerFilename);
579 579
             } else {
580
-                $markerImg = imagecreatefrompng($markerBaseDir . '/marker.png');
580
+                $markerImg = imagecreatefrompng($markerBaseDir.'/marker.png');
581 581
             }
582 582
             // check for shadow + create shadow recource
583
-            if($markerShadow && file_exists($markerBaseDir . '/' . $markerShadow)) {
584
-                $markerShadowImg = imagecreatefrompng($markerBaseDir . '/' . $markerShadow);
583
+            if ($markerShadow && file_exists($markerBaseDir.'/'.$markerShadow)) {
584
+                $markerShadowImg = imagecreatefrompng($markerBaseDir.'/'.$markerShadow);
585 585
             }
586 586
             // calc position
587 587
             $destX = floor(
@@ -593,7 +593,7 @@  discard block
 block discarded – undo
593 593
                 $this->tileSize * ($this->centerY - $this->latToTile($markerLat, $this->zoom))
594 594
             );
595 595
             // copy shadow on basemap
596
-            if($markerShadow && $markerShadowImg) {
596
+            if ($markerShadow && $markerShadowImg) {
597 597
                 imagecopy(
598 598
                     $this->image,
599 599
                     $markerShadowImg,
@@ -654,14 +654,14 @@  discard block
 block discarded – undo
654 654
      *            drawing colour
655 655
      */
656 656
     private function drawGeometry(Geometry $geom, int $colour): void {
657
-        if(empty($geom)) {
657
+        if (empty($geom)) {
658 658
             return;
659 659
         }
660 660
 
661
-        switch($geom->geometryType()) {
661
+        switch ($geom->geometryType()) {
662 662
             case 'GeometryCollection' :
663 663
                 // recursively draw part of the collection
664
-                for($i = 1; $i < $geom->numGeometries() + 1; $i++) {
664
+                for ($i = 1; $i < $geom->numGeometries() + 1; $i++) {
665 665
                     $_geom = $geom->geometryN($i);
666 666
                     $this->drawGeometry($_geom, $colour);
667 667
                 }
@@ -703,7 +703,7 @@  discard block
 block discarded – undo
703 703
         // extring is a linestring actually..
704 704
         $extRing = $polygon->exteriorRing();
705 705
 
706
-        for($i = 1; $i < $extRing->numGeometries(); $i++) {
706
+        for ($i = 1; $i < $extRing->numGeometries(); $i++) {
707 707
             $p1           = $extRing->geometryN($i);
708 708
             $x            = floor(
709 709
                 ($this->width / 2) - $this->tileSize * ($this->centerX - $this->lonToTile($p1->x(), $this->zoom))
@@ -729,7 +729,7 @@  discard block
 block discarded – undo
729 729
      */
730 730
     private function drawLineString($line, $colour) {
731 731
         imagesetthickness($this->image, 2);
732
-        for($p = 1; $p < $line->numGeometries(); $p++) {
732
+        for ($p = 1; $p < $line->numGeometries(); $p++) {
733 733
             // get first pair of points
734 734
             $p1 = $line->geometryN($p);
735 735
             $p2 = $line->geometryN($p + 1);
@@ -800,8 +800,8 @@  discard block
 block discarded – undo
800 800
      * add copyright and origin notice and icons to the map.
801 801
      */
802 802
     public function drawCopyright() {
803
-        $logoBaseDir = dirname(__FILE__) . '/' . 'logo/';
804
-        $logoImg     = imagecreatefrompng($logoBaseDir . $this->tileInfo ['openstreetmap'] ['logo']);
803
+        $logoBaseDir = dirname(__FILE__).'/'.'logo/';
804
+        $logoImg     = imagecreatefrompng($logoBaseDir.$this->tileInfo ['openstreetmap'] ['logo']);
805 805
         $textcolor   = imagecolorallocate($this->image, 0, 0, 0);
806 806
         $bgcolor     = imagecolorallocate($this->image, 200, 200, 200);
807 807
 
@@ -834,11 +834,11 @@  discard block
 block discarded – undo
834 834
 
835 835
         // additional tile source info, ie. who created/hosted the tiles
836 836
         $xIconOffset = 0;
837
-        if($this->maptype === 'openstreetmap') {
837
+        if ($this->maptype === 'openstreetmap') {
838 838
             $mapAuthor = "(c) OpenStreetMap maps/CC BY-SA";
839 839
         } else {
840 840
             $mapAuthor   = $this->tileInfo [$this->maptype] ['txt'];
841
-            $iconImg     = imagecreatefrompng($logoBaseDir . $this->tileInfo [$this->maptype] ['logo']);
841
+            $iconImg     = imagecreatefrompng($logoBaseDir.$this->tileInfo [$this->maptype] ['logo']);
842 842
             $xIconOffset = imagesx($iconImg);
843 843
             imagecopy(
844 844
                 $this->image,
Please login to merge, or discard this patch.
Braces   +15 added lines, -10 removed lines patch added patch discarded remove patch
@@ -351,14 +351,18 @@  discard block
 block discarded – undo
351 351
     public function makeMap(): void {
352 352
         $this->initCoords();
353 353
         $this->createBaseMap();
354
-        if(!empty ($this->markers))
355
-            $this->placeMarkers();
356
-        if(file_exists($this->kmlFileName))
357
-            $this->drawKML();
358
-        if(file_exists($this->gpxFileName))
359
-            $this->drawGPX();
360
-        if(file_exists($this->geojsonFileName))
361
-            $this->drawGeojson();
354
+        if(!empty ($this->markers)) {
355
+                    $this->placeMarkers();
356
+        }
357
+        if(file_exists($this->kmlFileName)) {
358
+                    $this->drawKML();
359
+        }
360
+        if(file_exists($this->gpxFileName)) {
361
+                    $this->drawGPX();
362
+        }
363
+        if(file_exists($this->geojsonFileName)) {
364
+                    $this->drawGeojson();
365
+        }
362 366
 
363 367
         $this->drawCopyright();
364 368
     }
@@ -449,8 +453,9 @@  discard block
 block discarded – undo
449 453
      *          for better proxy handling...
450 454
      */
451 455
     public function fetchTile(string $url) {
452
-        if($this->useTileCache && ($cached = $this->checkTileCache($url)))
453
-            return $cached;
456
+        if($this->useTileCache && ($cached = $this->checkTileCache($url))) {
457
+                    return $cached;
458
+        }
454 459
 
455 460
         $_UA = 'Mozilla/4.0 (compatible; DokuWikiSpatial HTTP Client; ' . PHP_OS . ')';
456 461
         if(function_exists("curl_init")) {
Please login to merge, or discard this patch.