Passed
Pull Request — master (#8)
by Mark
02:40
created

syntax_plugin_openlayersmap_olmap::convertLat()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
eloc 6
c 3
b 1
f 0
dl 0
loc 9
rs 10
cc 2
nc 2
nop 1
1
<?php
2
/*
3
 * Copyright (c) 2008-2021 Mark C. Prins <[email protected]>
4
 *
5
 * Permission to use, copy, modify, and distribute this software for any
6
 * purpose with or without fee is hereby granted, provided that the above
7
 * copyright notice and this permission notice appear in all copies.
8
 *
9
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16
 *
17
 * @phpcs:disable Squiz.Classes.ValidClassName.NotCamelCaps
18
 */
19
20
use dokuwiki\Logger;
0 ignored issues
show
Bug introduced by
The type dokuwiki\Logger was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
21
22
/**
23
 * DokuWiki Plugin openlayersmap (Syntax Component).
24
 * Provides for display of an OpenLayers based map in a wiki page.
25
 *
26
 * @author Mark Prins
27
 */
28
class syntax_plugin_openlayersmap_olmap extends DokuWiki_Syntax_Plugin
0 ignored issues
show
Bug introduced by
The type DokuWiki_Syntax_Plugin was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
29
{
30
31
    /**
32
     * defaults of the known attributes of the olmap tag.
33
     */
34
    private $dflt = array(
35
        'id'            => 'olmap',
36
        'width'         => '550px',
37
        'height'        => '450px',
38
        'lat'           => 50.0,
39
        'lon'           => 5.1,
40
        'zoom'          => 12,
41
        'autozoom'      => 1,
42
        'statusbar'     => true,
43
        'toolbar'       => true,
44
        'controls'      => true,
45
        'poihoverstyle' => false,
46
        'baselyr'       => 'OpenStreetMap',
47
        'gpxfile'       => '',
48
        'kmlfile'       => '',
49
        'geojsonfile'   => '',
50
        'summary'       => ''
51
    );
52
53
    /**
54
     *
55
     * @see DokuWiki_Syntax_Plugin::getType()
56
     */
57
    public function getType(): string
58
    {
59
        return 'substition';
60
    }
61
62
    /**
63
     *
64
     * @see DokuWiki_Syntax_Plugin::getPType()
65
     */
66
    public function getPType(): string
67
    {
68
        return 'block';
69
    }
70
71
    /**
72
     *
73
     * @see Doku_Parser_Mode::getSort()
74
     */
75
    public function getSort(): int
76
    {
77
        return 901;
78
    }
79
80
    /**
81
     *
82
     * @see Doku_Parser_Mode::connectTo()
83
     */
84
    public function connectTo($mode)
85
    {
86
        $this->Lexer->addSpecialPattern(
87
            '<olmap ?[^>\n]*>.*?</olmap>',
88
            $mode,
89
            'plugin_openlayersmap_olmap'
90
        );
91
    }
92
93
    /**
94
     *
95
     * @see DokuWiki_Syntax_Plugin::handle()
96
     */
97
    public function handle($match, $state, $pos, Doku_Handler $handler): array
0 ignored issues
show
Bug introduced by
The type Doku_Handler was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
98
    {
99
        // break matched cdata into its components
100
        list ($str_params, $str_points) = explode('>', substr($match, 7, -9), 2);
101
        // get the lat/lon for adding them to the metadata (used by geotag)
102
        preg_match('(lat[:|=]\"-?\d*\.?\d*\")', $match, $mainLat);
103
        preg_match('(lon[:|=]\"-?\d*\.?\d*\")', $match, $mainLon);
104
        $mainLat = substr($mainLat [0], 5, -1);
105
        $mainLon = substr($mainLon [0], 5, -1);
106
        if (!is_numeric($mainLat)) {
107
            $mainLat = $this->dflt ['lat'];
108
        }
109
        if (!is_numeric($mainLon)) {
110
            $mainLon = $this->dflt ['lon'];
111
        }
112
113
        $gmap          = $this->extractParams($str_params);
114
        $overlay       = $this->extractPoints($str_points);
115
        $_firstimageID = '';
116
117
        $_nocache = false;
118
        // choose maptype based on the specified tag
119
        $imgUrl = "{{";
120
        if (stripos($gmap ['baselyr'], 'google') !== false) {
121
            // Google
122
            $imgUrl .= $this->getGoogle($gmap, $overlay);
123
            $imgUrl .= "&.png";
124
        } elseif (stripos($gmap ['baselyr'], 'bing') !== false) {
125
            // Bing
126
            if (!$this->getConf('bingAPIKey')) {
127
                // in case there is no Bing api key we'll use OSM
128
                $_firstimageID = $this->getStaticOSM($gmap, $overlay);
129
                $imgUrl        .= $_firstimageID;
130
                if ($this->getConf('optionStaticMapGenerator') == 'remote') {
131
                    $imgUrl .= "&.png";
132
                }
133
            } else {
134
                // seems that Bing doesn't like the DW client, turn off caching
135
                $_nocache = true;
136
                $imgUrl   .= $this->getBing($gmap, $overlay) . "&.png";
137
            }
138
        } /* elseif (stripos ( $gmap ['baselyr'], 'mapquest' ) !== false) {
139
            // MapQuest
140
            if (! $this->getConf ( 'mapquestAPIKey' )) {
141
                // no API key for MapQuest, use OSM
142
                $_firstimageID = $this->getStaticOSM ( $gmap, $overlay );
143
                $imgUrl .= $_firstimageID;
144
                if ($this->getConf ( 'optionStaticMapGenerator' ) == 'remote') {
145
                    $imgUrl .= "&.png";
146
                }
147
            } else {
148
                $imgUrl .= $this->_getMapQuest ( $gmap, $overlay );
149
                $imgUrl .= "&.png";
150
            }
151
        } */ else {
152
            // default OSM
153
            $_firstimageID = $this->getStaticOSM($gmap, $overlay);
154
            $imgUrl        .= $_firstimageID;
155
            if ($this->getConf('optionStaticMapGenerator') == 'remote') {
156
                $imgUrl .= "&.png";
157
            }
158
        }
159
160
        // append dw p_render specific params and render
161
        $imgUrl .= "?" . str_replace("px", "", $gmap ['width']) . "x"
162
            . str_replace("px", "", $gmap ['height']);
163
        $imgUrl .= "&nolink";
164
165
        // add nocache option for selected services
166
        if ($_nocache) {
167
            $imgUrl .= "&nocache";
168
        }
169
170
        $imgUrl .= " |" . $gmap ['summary'] . " }}";
171
172
        // Logger::debug("complete image tags is:",$imgUrl);
173
174
        $mapid = $gmap ['id'];
175
        // create a javascript parameter string for the map
176
        $param = '';
177
        foreach ($gmap as $key => $val) {
178
            $param .= is_numeric($val) ? "$key: $val, " : "$key: '" . hsc($val) . "', ";
0 ignored issues
show
Bug introduced by
The function hsc was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

178
            $param .= is_numeric($val) ? "$key: $val, " : "$key: '" . /** @scrutinizer ignore-call */ hsc($val) . "', ";
Loading history...
179
        }
180
        if (!empty ($param)) {
181
            $param = substr($param, 0, -2);
182
        }
183
        unset ($gmap ['id']);
184
185
        // create a javascript serialisation of the point data
186
        $poi      = '';
187
        $poitable = '';
188
        $rowId    = 0;
189
        if (!empty ($overlay)) {
190
            foreach ($overlay as $data) {
191
                list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
192
                $rowId++;
193
                $poi .= ", {lat:$lat,lon:$lon,txt:'$text',angle:$angle,opacity:$opacity,img:'$img',rowId: $rowId}";
194
195
                if ($this->getConf('displayformat') === 'DMS') {
196
                    $lat = $this->convertLat($lat);
197
                    $lon = $this->convertLon($lon);
198
                } else {
199
                    $lat .= 'º';
200
                    $lon .= 'º';
201
                }
202
203
                $poitable .= '
204
                    <tr>
205
                    <td class="rowId">' . $rowId . '</td>
206
                    <td class="icon"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/icons/' . $img . '" alt="'
0 ignored issues
show
Bug introduced by
The constant DOKU_BASE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
207
                    . substr($img, 0, -4) . $this->getlang('alt_legend_poi') . '" /></td>
208
                    <td class="lat" title="' . $this->getLang('olmapPOIlatTitle') . '">' . $lat . '</td>
209
                    <td class="lon" title="' . $this->getLang('olmapPOIlonTitle') . '">' . $lon . '</td>
210
                    <td class="txt">' . $text . '</td>
211
                    </tr>';
212
            }
213
            $poi = substr($poi, 2);
214
        }
215
        if (!empty ($gmap ['kmlfile'])) {
216
            $poitable .= '
217
                    <tr>
218
                    <td class="rowId"><img src="' . DOKU_BASE
219
                . 'lib/plugins/openlayersmap/toolbar/kml_file.png" alt="KML file" /></td>
220
                    <td class="icon"><img src="' . DOKU_BASE . 'lib/plugins/openlayersmap/toolbar/kml_line.png" alt="'
221
                . $this->getlang('alt_legend_kml') . '" /></td>
222
                    <td class="txt" colspan="3">KML track: ' . $this->getFileName($gmap ['kmlfile']) . '</td>
223
                    </tr>';
224
        }
225
        if (!empty ($gmap ['gpxfile'])) {
226
            $poitable .= '
227
                    <tr>
228
                    <td class="rowId"><img src="' . DOKU_BASE
229
                . 'lib/plugins/openlayersmap/toolbar/gpx_file.png" alt="GPX file" /></td>
230
                    <td class="icon"><img src="' . DOKU_BASE
231
                . 'lib/plugins/openlayersmap/toolbar/gpx_line.png" alt="'
232
                . $this->getlang('alt_legend_gpx') . '" /></td>
233
                    <td class="txt" colspan="3">GPX track: ' . $this->getFileName($gmap ['gpxfile']) . '</td>
234
                    </tr>';
235
        }
236
        if (!empty ($gmap ['geojsonfile'])) {
237
            $poitable .= '
238
                    <tr>
239
                    <td class="rowId"><img src="' . DOKU_BASE
240
                . 'lib/plugins/openlayersmap/toolbar/geojson_file.png" alt="GeoJSON file" /></td>
241
                    <td class="icon"><img src="' . DOKU_BASE
242
                . 'lib/plugins/openlayersmap/toolbar/geojson_line.png" alt="'
243
                . $this->getlang('alt_legend_geojson') . '" /></td>
244
                    <td class="txt" colspan="3">GeoJSON track: ' . $this->getFileName($gmap ['geojsonfile']) . '</td>
245
                    </tr>';
246
        }
247
248
        $autozoom = empty ($gmap ['autozoom']) ? $this->getConf('autoZoomMap') : $gmap ['autozoom'];
249
        $js       = "{mapOpts: {" . $param . ", displayformat: '" . $this->getConf('displayformat')
250
            . "', autozoom: " . $autozoom . "}, poi: [$poi]};";
251
        // unescape the json
252
        $poitable = stripslashes($poitable);
253
254
        return array(
255
            $mapid,
256
            $js,
257
            $mainLat,
258
            $mainLon,
259
            $poitable,
260
            $gmap ['summary'],
261
            $imgUrl,
262
            $_firstimageID
263
        );
264
    }
265
266
    /**
267
     * extract parameters for the map from the parameter string
268
     *
269
     * @param string $str_params
270
     *            string of key="value" pairs
271
     * @return array associative array of parameters key=>value
272
     */
273
    private function extractParams(string $str_params): array
274
    {
275
        $param = array();
276
        preg_match_all('/(\w*)="(.*?)"/us', $str_params, $param, PREG_SET_ORDER);
277
        // parse match for instructions, break into key value pairs
278
        $gmap = $this->dflt;
279
        foreach ($gmap as $key => &$value) {
280
            $defval = $this->getConf('default_' . $key);
281
            if ($defval !== '') {
282
                $value = $defval;
283
            }
284
        }
285
        unset ($value);
286
        foreach ($param as $kvpair) {
287
            list ($match, $key, $val) = $kvpair;
288
            $key = strtolower($key);
289
            if (isset ($gmap [$key])) {
290
                if ($key == 'summary') {
291
                    // preserve case for summary field
292
                    $gmap [$key] = $val;
293
                } elseif ($key == 'id') {
294
                    // preserve case for id field
295
                    $gmap [$key] = $val;
296
                } else {
297
                    $gmap [$key] = strtolower($val);
298
                }
299
            }
300
        }
301
        return $gmap;
302
    }
303
304
    /**
305
     * extract overlay points for the map from the wiki syntax data
306
     *
307
     * @param string $str_points
308
     *            multi-line string of lat,lon,text triplets
309
     * @return array multi-dimensional array of lat,lon,text triplets
310
     */
311
    private function extractPoints(string $str_points): array
312
    {
313
        $point = array();
314
        // preg_match_all('/^([+-]?[0-9].*?),\s*([+-]?[0-9].*?),(.*?),(.*?),(.*?),(.*)$/um',
315
        //      $str_points, $point, PREG_SET_ORDER);
316
        /*
317
         * group 1: ([+-]?[0-9]+(?:\.[0-9]*)?)
318
         * group 2: ([+-]?[0-9]+(?:\.[0-9]*)?)
319
         * group 3: (.*?)
320
         * group 4: (.*?)
321
         * group 5: (.*?)
322
         * group 6: (.*)
323
         */
324
        preg_match_all(
325
            '/^([+-]?[0-9]+(?:\.[0-9]*)?),\s*([+-]?[0-9]+(?:\.[0-9]*)?),(.*?),(.*?),(.*?),(.*)$/um',
326
            $str_points,
327
            $point,
328
            PREG_SET_ORDER
329
        );
330
        // create poi array
331
        $overlay = array();
332
        foreach ($point as $pt) {
333
            list ($match, $lat, $lon, $angle, $opacity, $img, $text) = $pt;
334
            $lat     = is_numeric($lat) ? $lat : 0;
335
            $lon     = is_numeric($lon) ? $lon : 0;
336
            $angle   = is_numeric($angle) ? $angle : 0;
337
            $opacity = is_numeric($opacity) ? $opacity : 0.8;
338
            // TODO validate using exist & set up default img?
339
            $img  = trim($img);
340
            $text = p_get_instructions($text);
0 ignored issues
show
Bug introduced by
The function p_get_instructions was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

340
            $text = /** @scrutinizer ignore-call */ p_get_instructions($text);
Loading history...
341
            // dbg ( $text );
342
            $text = p_render("xhtml", $text, $info);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $info seems to be never defined.
Loading history...
Bug introduced by
The function p_render was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

342
            $text = /** @scrutinizer ignore-call */ p_render("xhtml", $text, $info);
Loading history...
343
            // dbg ( $text );
344
            $text       = addslashes(str_replace("\n", "", $text));
345
            $overlay [] = array(
346
                $lat,
347
                $lon,
348
                $text,
349
                $angle,
350
                $opacity,
351
                $img
352
            );
353
        }
354
        return $overlay;
355
    }
356
357
    /**
358
     * Create a Google maps static image url w/ the poi.
359
     *
360
     * @param array $gmap
361
     * @param array $overlay
362
     * @return string
363
     */
364
    private function getGoogle(array $gmap, array $overlay): string
365
    {
366
        $sUrl = $this->getConf('iconUrlOverload');
367
        if (!$sUrl) {
368
            $sUrl = DOKU_URL;
0 ignored issues
show
Bug introduced by
The constant DOKU_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
369
        }
370
        switch ($gmap ['baselyr']) {
371
            case 'google hybrid' :
372
                $maptype = 'hybrid';
373
                break;
374
            case 'google sat' :
375
                $maptype = 'satellite';
376
                break;
377
            case 'terrain' :
378
            case 'google relief' :
379
                $maptype = 'terrain';
380
                break;
381
            case 'google road' :
382
            default :
383
                $maptype = 'roadmap';
384
                break;
385
        }
386
        // TODO maybe use viewport / visible instead of center/zoom,
387
        // see: https://developers.google.com/maps/documentation/staticmaps/index#Viewports
388
        // http://maps.google.com/maps/api/staticmap?center=51.565690,5.456756&zoom=16&size=600x400&markers=icon:http://wild-water.nl/dokuwiki/lib/plugins/openlayersmap/icons/marker.png|label:1|51.565690,5.456756&markers=icon:http://wild-water.nl/dokuwiki/lib/plugins/openlayersmap/icons/marker-blue.png|51.566197,5.458966|label:2&markers=icon:http://wild-water.nl/dokuwiki/lib/plugins/openlayersmap/icons/parking.png|51.567177,5.457909|label:3&markers=icon:http://wild-water.nl/dokuwiki/lib/plugins/openlayersmap/icons/parking.png|51.566283,5.457330|label:4&markers=icon:http://wild-water.nl/dokuwiki/lib/plugins/openlayersmap/icons/parking.png|51.565630,5.457695|label:5&sensor=false&format=png&maptype=roadmap
389
        $imgUrl = "https://maps.googleapis.com/maps/api/staticmap?";
390
        $imgUrl .= "&size=" . str_replace("px", "", $gmap ['width']) . "x"
391
            . str_replace("px", "", $gmap ['height']);
392
        //if (!$this->getConf( 'autoZoomMap')) { // no need for center & zoom params }
393
        $imgUrl .= "&center=" . $gmap ['lat'] . "," . $gmap ['lon'];
394
        // max is 21 (== building scale), but that's overkill..
395
        if ($gmap ['zoom'] > 17) {
396
            $imgUrl .= "&zoom=17";
397
        } else {
398
            $imgUrl .= "&zoom=" . $gmap ['zoom'];
399
        }
400
        if (!empty ($overlay)) {
401
            $rowId = 0;
402
            foreach ($overlay as $data) {
403
                list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
404
                $imgUrl .= "&markers=icon%3a" . $sUrl . "lib/plugins/openlayersmap/icons/" . $img . "%7c"
405
                    . $lat . "," . $lon . "%7clabel%3a" . ++$rowId;
406
            }
407
        }
408
        $imgUrl .= "&format=png&maptype=" . $maptype;
409
        global $conf;
410
        $imgUrl .= "&language=" . $conf ['lang'];
411
        if ($this->getConf('googleAPIkey')) {
412
            $imgUrl .= "&key=" . $this->getConf('googleAPIkey');
413
        }
414
        // Logger::debug('syntax_plugin_openlayersmap_olmap::getGoogle: Google image url is:',$imgUrl);
415
        return $imgUrl;
416
    }
417
418
    /**
419
     * Create a MapQuest static map API image url.
420
     *
421
     * @param array $gmap
422
     * @param array $overlay
423
     */
424
    /*
425
   private function _getMapQuest($gmap, $overlay) {
426
       $sUrl = $this->getConf ( 'iconUrlOverload' );
427
       if (! $sUrl) {
428
           $sUrl = DOKU_URL;
429
       }
430
       switch ($gmap ['baselyr']) {
431
           case 'mapquest hybrid' :
432
               $maptype = 'hyb';
433
               break;
434
           case 'mapquest sat' :
435
               // because sat coverage is very limited use 'hyb' instead of 'sat' so we don't get a blank map
436
               $maptype = 'hyb';
437
               break;
438
           case 'mapquest road' :
439
           default :
440
               $maptype = 'map';
441
               break;
442
       }
443
       $imgUrl = "http://open.mapquestapi.com/staticmap/v4/getmap?declutter=true&";
444
       if (count ( $overlay ) < 1) {
445
           $imgUrl .= "?center=" . $gmap ['lat'] . "," . $gmap ['lon'];
446
           // max level for mapquest is 16
447
           if ($gmap ['zoom'] > 16) {
448
               $imgUrl .= "&zoom=16";
449
           } else {
450
               $imgUrl .= "&zoom=" . $gmap ['zoom'];
451
           }
452
       }
453
       // use bestfit instead of center/zoom, needs upperleft/lowerright corners
454
       // $bbox=$this->calcBBOX($overlay, $gmap['lat'], $gmap['lon']);
455
       // $imgUrl .= "bestfit=".$bbox['minlat'].",".$bbox['maxlon'].",".$bbox['maxlat'].",".$bbox['minlon'];
456
457
       // TODO declutter option works well for square maps but not for rectangular, maybe compensate for that
458
       //       or compensate the mbr..
459
460
       $imgUrl .= "&size=" . str_replace ( "px", "", $gmap ['width'] ) . "," . str_replace ("px","",$gmap['height']);
461
462
       // TODO mapquest allows using one image url with a multiplier $NUMBER eg:
463
       // $NUMBER = 2
464
       // $imgUrl .= DOKU_URL."/".DOKU_PLUGIN."/".getPluginName()."/icons/".$img.",$NUMBER,C,"
465
        //  .$lat1.",".$lon1.",0,0,0,0,C,".$lat2.",".$lon2.",0,0,0,0";
466
       if (! empty ( $overlay )) {
467
           $imgUrl .= "&xis=";
468
           foreach ( $overlay as $data ) {
469
               list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
470
               // $imgUrl .= $sUrl."lib/plugins/openlayersmap/icons/".$img.",1,C,".$lat.",".$lon.",0,0,0,0,";
471
               $imgUrl .= $sUrl . "lib/plugins/openlayersmap/icons/" . $img . ",1,C," . $lat . "," . $lon . ",";
472
           }
473
           $imgUrl = substr ( $imgUrl, 0, - 1 );
474
       }
475
       $imgUrl .= "&imageType=png&type=" . $maptype;
476
       $imgUrl .= "&key=".$this->getConf ( 'mapquestAPIKey' );
477
       // Logger::debug('syntax_plugin_openlayersmap_olmap::_getMapQuest: MapQuest image url is:',$imgUrl);
478
       return $imgUrl;
479
   }
480
   */
481
482
    /**
483
     * Create a static OSM map image url w/ the poi from http://staticmap.openstreetmap.de (staticMapLite)
484
     * use http://staticmap.openstreetmap.de "staticMapLite" or a local version
485
     *
486
     * @param array $gmap
487
     * @param array $overlay
488
     *
489
     * @return false|string
490
     * @todo implementation for http://ojw.dev.openstreetmap.org/StaticMapDev/
491
     */
492
    private function getStaticOSM(array $gmap, array $overlay)
493
    {
494
        if ($this->getConf('optionStaticMapGenerator') == 'local') {
495
            // using local basemap composer
496
            if (!$myMap = plugin_load('helper', 'openlayersmap_staticmap')) {
0 ignored issues
show
Bug introduced by
The function plugin_load was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

496
            if (!$myMap = /** @scrutinizer ignore-call */ plugin_load('helper', 'openlayersmap_staticmap')) {
Loading history...
497
                Logger::error(
498
                    'openlayersmap_staticmap plugin is not available for use.',
499
                    $myMap
500
                );
501
            }
502
            if (!$geophp = plugin_load('helper', 'geophp')) {
503
                Logger::debug('geophp plugin is not available for use.', $geophp);
504
            }
505
            $size = str_replace("px", "", $gmap ['width']) . "x"
506
                . str_replace("px", "", $gmap ['height']);
507
508
            $markers = array();
509
            if (!empty ($overlay)) {
510
                foreach ($overlay as $data) {
511
                    list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
512
                    $iconStyle  = substr($img, 0, strlen($img) - 4);
513
                    $markers [] = array(
514
                        'lat'  => $lat,
515
                        'lon'  => $lon,
516
                        'type' => $iconStyle
517
                    );
518
                }
519
            }
520
521
            $apikey = '';
522
            switch ($gmap ['baselyr']) {
523
                case 'mapnik' :
524
                case 'openstreetmap' :
525
                    $maptype = 'openstreetmap';
526
                    break;
527
                case 'transport' :
528
                    $maptype = 'transport';
529
                    $apikey  = '?apikey=' . $this->getConf('tfApiKey');
530
                    break;
531
                case 'landscape' :
532
                    $maptype = 'landscape';
533
                    $apikey  = '?apikey=' . $this->getConf('tfApiKey');
534
                    break;
535
                case 'outdoors' :
536
                    $maptype = 'outdoors';
537
                    $apikey  = '?apikey=' . $this->getConf('tfApiKey');
538
                    break;
539
                case 'cycle map' :
540
                    $maptype = 'cycle';
541
                    $apikey  = '?apikey=' . $this->getConf('tfApiKey');
542
                    break;
543
                case 'hike and bike map' :
544
                    $maptype = 'hikeandbike';
545
                    break;
546
                case 'mapquest hybrid' :
547
                case 'mapquest road' :
548
                case 'mapquest sat' :
549
                    $maptype = 'mapquest';
550
                    break;
551
                default :
552
                    $maptype = '';
553
                    break;
554
            }
555
556
            $result = $myMap->getMap(
557
                $gmap ['lat'],
558
                $gmap ['lon'],
559
                $gmap ['zoom'],
560
                $size,
561
                $maptype,
562
                $markers,
563
                $gmap ['gpxfile'],
564
                $gmap ['kmlfile'],
565
                $gmap ['geojsonfile'],
566
                $apikey
567
            );
568
        } else {
569
            // using external basemap composer
570
571
            // https://staticmap.openstreetmap.de/staticmap.php?center=47.000622235634,10
572
            //.117187497601&zoom=5&size=500x350
573
            // &markers=48.999812532766,8.3593749976708,lightblue1|43.154850037315,17.499999997306,
574
            //  lightblue1|49.487527053077,10.820312497573,ltblu-pushpin|47.951071133739,15.917968747369,
575
            //  ol-marker|47.921629720114,18.027343747285,ol-marker-gold|47.951071133739,19.257812497236,
576
            //  ol-marker-blue|47.180141361692,19.257812497236,ol-marker-green
577
            $imgUrl = "https://staticmap.openstreetmap.de/staticmap.php";
578
            $imgUrl .= "?center=" . $gmap ['lat'] . "," . $gmap ['lon'];
579
            $imgUrl .= "&size=" . str_replace("px", "", $gmap ['width']) . "x"
580
                . str_replace("px", "", $gmap ['height']);
581
582
            if ($gmap ['zoom'] > 16) {
583
                // actually this could even be 18, but that seems overkill
584
                $imgUrl .= "&zoom=16";
585
            } else {
586
                $imgUrl .= "&zoom=" . $gmap ['zoom'];
587
            }
588
589
            if (!empty ($overlay)) {
590
                $rowId  = 0;
591
                $imgUrl .= "&markers=";
592
                foreach ($overlay as $data) {
593
                    list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
594
                    $rowId++;
595
                    $iconStyle = "lightblue$rowId";
596
                    $imgUrl    .= "$lat,$lon,$iconStyle%7c";
597
                }
598
                $imgUrl = substr($imgUrl, 0, -3);
599
            }
600
601
            $result = $imgUrl;
602
        }
603
        // Logger::debug('syntax_plugin_openlayersmap_olmap::getStaticOSM: osm image url is:',$result);
604
        return $result;
605
    }
606
607
    /**
608
     * Create a Bing maps static image url w/ the poi.
609
     *
610
     * @param array $gmap
611
     * @param array $overlay
612
     * @return string
613
     */
614
    private function getBing(array $gmap, array $overlay): string
615
    {
616
        switch ($gmap ['baselyr']) {
617
            case 've hybrid' :
618
            case 'bing hybrid' :
619
                $maptype = 'AerialWithLabels';
620
                break;
621
            case 've sat' :
622
            case 'bing sat' :
623
                $maptype = 'Aerial';
624
                break;
625
            case 've normal' :
626
            case 've road' :
627
            case 've' :
628
            case 'bing road' :
629
            default :
630
                $maptype = 'Road';
631
                break;
632
        }
633
        $imgUrl = "https://dev.virtualearth.net/REST/v1/Imagery/Map/" . $maptype;// . "/";
634
        if ($this->getConf('autoZoomMap')) {
635
            $bbox = $this->calcBBOX($overlay, $gmap ['lat'], $gmap ['lon']);
636
            //$imgUrl .= "?ma=" . $bbox ['minlat'] . "," . $bbox ['minlon'] . ","
637
            //          . $bbox ['maxlat'] . "," . $bbox ['maxlon'];
638
            $imgUrl .= "?ma=" . $bbox ['minlat'] . "%2C" . $bbox ['minlon'] . "%2C" . $bbox ['maxlat']
639
                . "%2C" . $bbox ['maxlon'];
640
            $imgUrl .= "&dcl=1";
641
        }
642
        if (strpos($imgUrl, "?") === false) {
643
            $imgUrl .= "?";
644
        }
645
646
        //$imgUrl .= "&ms=" . str_replace ( "px", "", $gmap ['width'] ) . ","
647
        //          . str_replace ( "px", "", $gmap ['height'] );
648
        $imgUrl .= "&ms=" . str_replace("px", "", $gmap ['width']) . "%2C"
649
            . str_replace("px", "", $gmap ['height']);
650
        $imgUrl .= "&key=" . $this->getConf('bingAPIKey');
651
        if (!empty ($overlay)) {
652
            $rowId = 0;
653
            foreach ($overlay as $data) {
654
                list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
655
                // TODO icon style lookup, see: http://msdn.microsoft.com/en-us/library/ff701719.aspx for iconStyle
656
                $iconStyle = 32;
657
                $rowId++;
658
                // NOTE: the max number of pushpins is 18! or we have to use POST
659
                //  (http://msdn.microsoft.com/en-us/library/ff701724.aspx)
660
                if ($rowId == 18) {
661
                    break;
662
                }
663
                //$imgUrl .= "&pp=$lat,$lon;$iconStyle;$rowId";
664
                $imgUrl .= "&pp=$lat%2C$lon%3B$iconStyle%3B$rowId";
665
            }
666
        }
667
        global $conf;
668
        $imgUrl .= "&fmt=png";
669
        $imgUrl .= "&c=" . $conf ['lang'];
670
        // Logger::debug('syntax_plugin_openlayersmap_olmap::getBing: bing image url is:',$imgUrl);
671
        return $imgUrl;
672
    }
673
674
    /**
675
     * Calculate the minimum bbox for a start location + poi.
676
     *
677
     * @param array $overlay
678
     *            multi-dimensional array of array($lat, $lon, $text, $angle, $opacity, $img)
679
     * @param float $lat
680
     *            latitude for map center
681
     * @param float $lon
682
     *            longitude for map center
683
     * @return array :float array describing the mbr and center point
684
     */
685
    private function calcBBOX(array $overlay, float $lat, float $lon): array
686
    {
687
        $lats = array($lat);
688
        $lons = array($lon);
689
        foreach ($overlay as $data) {
690
            list ($lat, $lon, $text, $angle, $opacity, $img) = $data;
691
            $lats [] = $lat;
692
            $lons [] = $lon;
693
        }
694
        sort($lats);
695
        sort($lons);
696
        // TODO: make edge/wrap around cases work
697
        $centerlat = $lats [0] + ($lats [count($lats) - 1] - $lats [0]);
698
        $centerlon = $lons [0] + ($lons [count($lats) - 1] - $lons [0]);
699
        return array(
700
            'minlat'    => $lats [0],
701
            'minlon'    => $lons [0],
702
            'maxlat'    => $lats [count($lats) - 1],
703
            'maxlon'    => $lons [count($lats) - 1],
704
            'centerlat' => $centerlat,
705
            'centerlon' => $centerlon
706
        );
707
    }
708
709
    /**
710
     * convert latitude in decimal degrees to DMS+hemisphere.
711
     *
712
     * @param float $decimaldegrees
713
     * @return string
714
     * @todo move this into a shared library
715
     */
716
    private function convertLat(float $decimaldegrees): string
717
    {
718
        if (strpos($decimaldegrees, '-') !== false) {
719
            $latPos = "S";
720
        } else {
721
            $latPos = "N";
722
        }
723
        $dms = $this->convertDDtoDMS(abs($decimaldegrees));
724
        return hsc($dms . $latPos);
0 ignored issues
show
Bug introduced by
The function hsc was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

724
        return /** @scrutinizer ignore-call */ hsc($dms . $latPos);
Loading history...
725
    }
726
727
    /**
728
     * Convert decimal degrees to degrees, minutes, seconds format
729
     *
730
     * @param float $decimaldegrees
731
     * @return string dms
732
     * @todo move this into a shared library
733
     */
734
    private function convertDDtoDMS(float $decimaldegrees): string
735
    {
736
        $dms  = floor($decimaldegrees);
737
        $secs = ($decimaldegrees - $dms) * 3600;
738
        $min  = floor($secs / 60);
739
        $sec  = round($secs - ($min * 60), 3);
740
        $dms  .= 'º' . $min . '\'' . $sec . '"';
741
        return $dms;
742
    }
743
744
    /**
745
     * convert longitude in decimal degrees to DMS+hemisphere.
746
     *
747
     * @param float $decimaldegrees
748
     * @return string
749
     * @todo move this into a shared library
750
     */
751
    private function convertLon(float $decimaldegrees): string
752
    {
753
        if (strpos($decimaldegrees, '-') !== false) {
754
            $lonPos = "W";
755
        } else {
756
            $lonPos = "E";
757
        }
758
        $dms = $this->convertDDtoDMS(abs($decimaldegrees));
759
        return hsc($dms . $lonPos);
0 ignored issues
show
Bug introduced by
The function hsc was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

759
        return /** @scrutinizer ignore-call */ hsc($dms . $lonPos);
Loading history...
760
    }
761
762
    /**
763
     * Figures out the base filename of a media path.
764
     *
765
     * @param string $mediaLink
766
     * @return string
767
     */
768
    private function getFileName(string $mediaLink): string
769
    {
770
        $mediaLink = str_replace('[[', '', $mediaLink);
771
        $mediaLink = str_replace(']]', '', $mediaLink);
772
        $mediaLink = substr($mediaLink, 0, -4);
773
        $parts     = explode(':', $mediaLink);
774
        $mediaLink = end($parts);
775
        return str_replace('_', ' ', $mediaLink);
776
    }
777
778
    /**
779
     *
780
     * @see DokuWiki_Syntax_Plugin::render()
781
     */
782
    public function render($format, Doku_Renderer $renderer, $data): bool
0 ignored issues
show
Bug introduced by
The type Doku_Renderer was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
783
    {
784
        // set to true after external scripts tags are written
785
        static $initialised = false;
786
        // incremented for each map tag in the page source so we can keep track of each map in this page
787
        static $mapnumber = 0;
788
789
        // Logger::debug('olmap::render() data.',$data);
790
        list ($mapid, $param, $mainLat, $mainLon, $poitable, $poitabledesc, $staticImgUrl, $_firstimage) = $data;
791
792
        if ($format == 'xhtml') {
793
            $olscript     = '';
794
            $stamenEnable = $this->getConf('enableStamen');
795
            $osmEnable    = $this->getConf('enableOSM');
796
            $enableBing   = $this->getConf('enableBing');
797
798
            $scriptEnable = '';
799
            if (!$initialised) {
800
                $initialised = true;
801
                // render necessary script tags only once
802
                $olscript = '<script defer="defer" src="' . DOKU_BASE . 'lib/plugins/openlayersmap/ol6/ol.js"></script>
0 ignored issues
show
Bug introduced by
The constant DOKU_BASE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
803
<script defer="defer" src="' . DOKU_BASE . 'lib/plugins/openlayersmap/ol6/ol-layerswitcher.js"></script>';
804
805
                $scriptEnable = '<script defer="defer" src="data:text/javascript;base64,';
806
                $scriptSrc    = $olscript ? 'const olEnable=true;' : 'const olEnable=false;';
807
                $scriptSrc    .= 'const osmEnable=' . ($osmEnable ? 'true' : 'false') . ';';
808
                $scriptSrc    .= 'const stamenEnable=' . ($stamenEnable ? 'true' : 'false') . ';';
809
                $scriptSrc    .= 'const bEnable=' . ($enableBing ? 'true' : 'false') . ';';
810
                $scriptSrc    .= 'const bApiKey="' . $this->getConf('bingAPIKey') . '";';
811
                $scriptSrc    .= 'const tfApiKey="' . $this->getConf('tfApiKey') . '";';
812
                $scriptSrc    .= 'const gApiKey="' . $this->getConf('googleAPIkey') . '";';
813
                $scriptSrc    .= 'olMapData = []; let olMaps = {}; let olMapOverlays = {};';
814
                $scriptEnable .= base64_encode($scriptSrc);
815
                $scriptEnable .= '"></script>';
816
            }
817
            $renderer->doc .= "$olscript\n$scriptEnable";
818
            $renderer->doc .= '<div class="olMapHelp">' . $this->locale_xhtml("help") . '</div>';
819
            if ($this->getConf('enableA11y')) {
820
                $renderer->doc .= '<div id="' . $mapid . '-static" class="olStaticMap">'
821
                    . p_render($format, p_get_instructions($staticImgUrl), $info) . '</div>';
0 ignored issues
show
Bug introduced by
The function p_get_instructions was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

821
                    . p_render($format, /** @scrutinizer ignore-call */ p_get_instructions($staticImgUrl), $info) . '</div>';
Loading history...
Bug introduced by
The function p_render was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

821
                    . /** @scrutinizer ignore-call */ p_render($format, p_get_instructions($staticImgUrl), $info) . '</div>';
Loading history...
Comprehensibility Best Practice introduced by
The variable $info seems to be never defined.
Loading history...
822
            }
823
            $renderer->doc .= '<div id="' . $mapid . '-clearer" class="clearer"><p>&nbsp;</p></div>';
824
            if ($this->getConf('enableA11y')) {
825
                // render a table of the POI for the print and a11y presentation, it is hidden using javascript
826
                $renderer->doc .= '
827
                <div class="olPOItableSpan" id="' . $mapid . '-table-span">
828
                    <table class="olPOItable" id="' . $mapid . '-table">
829
                    <caption class="olPOITblCaption">' . $this->getLang('olmapPOItitle') . '</caption>
830
                    <thead class="olPOITblHeader">
831
                    <tr>
832
                    <th class="rowId" scope="col">id</th>
833
                    <th class="icon" scope="col">' . $this->getLang('olmapPOIicon') . '</th>
834
                    <th class="lat" scope="col" title="' . $this->getLang('olmapPOIlatTitle') . '">'
835
                    . $this->getLang('olmapPOIlat') . '</th>
836
                    <th class="lon" scope="col" title="' . $this->getLang('olmapPOIlonTitle') . '">'
837
                    . $this->getLang('olmapPOIlon') . '</th>
838
                    <th class="txt" scope="col">' . $this->getLang('olmapPOItxt') . '</th>
839
                    </tr>
840
                    </thead>';
841
                if ($poitabledesc != '') {
842
                    $renderer->doc .= '<tfoot class="olPOITblFooter"><tr><td colspan="5">' . $poitabledesc
843
                        . '</td></tr></tfoot>';
844
                }
845
                $renderer->doc .= '<tbody class="olPOITblBody">' . $poitable . '</tbody>
846
                    </table>
847
                </div>';
848
                $renderer->doc .= "\n";
849
            }
850
            // render inline mapscript parts
851
            $renderer->doc .= '<script defer="defer" src="data:text/javascript;base64,';
852
            $renderer->doc .= base64_encode("olMapData[$mapnumber] = $param");
853
            $renderer->doc .= '"></script>';
854
            $mapnumber++;
855
            return true;
856
        } elseif ($format == 'metadata') {
857
            if (!(($this->dflt ['lat'] == $mainLat) && ($this->dflt ['lon'] == $mainLon))) {
858
                // render geo metadata, unless they are the default
859
                $renderer->meta ['geo'] ['lat'] = $mainLat;
860
                $renderer->meta ['geo'] ['lon'] = $mainLon;
861
                if ($geophp = plugin_load('helper', 'geophp')) {
0 ignored issues
show
Bug introduced by
The function plugin_load was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

861
                if ($geophp = /** @scrutinizer ignore-call */ plugin_load('helper', 'geophp')) {
Loading history...
Unused Code introduced by
The assignment to $geophp is dead and can be removed.
Loading history...
862
                    // if we have the geoPHP helper, add the geohash
863
                    try {
864
                        $renderer->meta['geo']['geohash'] = (new Point($mainLon, $mainLat))->out('geohash');
865
                    } catch (Exception $e) {
866
                        Logger::error("Failed to create geohash for: $mainLat, $mainLon");
867
                    }
868
                }
869
            }
870
871
            if (($this->getConf('enableA11y')) && (!empty ($_firstimage))) {
872
                // add map local image into relation/firstimage if not already filled and when it is a local image
873
874
                global $ID;
875
                $rel = p_get_metadata($ID, 'relation');
0 ignored issues
show
Bug introduced by
The function p_get_metadata was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

875
                $rel = /** @scrutinizer ignore-call */ p_get_metadata($ID, 'relation');
Loading history...
876
                $img = $rel ['firstimage'];
877
                if (empty ($img) /* || $img == $_firstimage*/) {
878
                    //Logger::debug(
879
                    // 'olmap::render#rendering image relation metadata for _firstimage as $img was empty or same.',
880
                    // $_firstimage);
881
882
                    // This seems to never work; the firstimage entry in the .meta file is empty
883
                    // $renderer->meta['relation']['firstimage'] = $_firstimage;
884
885
                    // ... and neither does this; the firstimage entry in the .meta file is empty
886
                    // $relation = array('relation'=>array('firstimage'=>$_firstimage));
887
                    // p_set_metadata($ID, $relation, false, false);
888
889
                    // ... this works
890
                    $renderer->internalmedia($_firstimage, $poitabledesc);
891
                }
892
            }
893
            return true;
894
        }
895
        return false;
896
    }
897
}
898