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

syntax_plugin_openlayersmap_olmap::extractPoints()   A

Complexity

Conditions 6
Paths 17

Size

Total Lines 37
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 6
eloc 19
c 1
b 1
f 0
nc 17
nop 1
dl 0
loc 37
rs 9.0111
1
<?php
2
3
/*
4
 * Copyright (c) 2008-2023 Mark C. Prins <[email protected]>
5
 *
6
 * Permission to use, copy, modify, and distribute this software for any
7
 * purpose with or without fee is hereby granted, provided that the above
8
 * copyright notice and this permission notice appear in all copies.
9
 *
10
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
 *
18
 * @phpcs:disable Squiz.Classes.ValidClassName.NotCamelCaps
19
 */
20
use dokuwiki\Extension\SyntaxPlugin;
0 ignored issues
show
Bug introduced by
The type dokuwiki\Extension\SyntaxPlugin 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
use geoPHP\Geometry\Point;
0 ignored issues
show
Bug introduced by
The type geoPHP\Geometry\Point 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...
22
23
/**
24
 * DokuWiki Plugin openlayersmap (Syntax Component).
25
 * Provides for display of an OpenLayers based map in a wiki page.
26
 *
27
 * @author Mark Prins
28
 */
29
class syntax_plugin_openlayersmap_olmap extends SyntaxPlugin
30
{
31
    /**
32
     * defaults of the known attributes of the olmap tag.
33
     */
34
    private $dflt = ['id'            => 'olmap', 'width'         => '550px', 'height'        => '450px', 'lat'           => 50.0, 'lon'           => 5.1, 'zoom'          => 12, 'autozoom'      => 1, 'controls'      => true, 'baselyr'       => 'OpenStreetMap', 'gpxfile'       => '', 'kmlfile'       => '', 'geojsonfile'   => '', 'summary'       => ''];
35
36
    /**
37
     *
38
     * @see DokuWiki_Syntax_Plugin::getType()
39
     */
40
    public function getType(): string
41
    {
42
        return 'substition';
43
    }
44
45
    /**
46
     *
47
     * @see DokuWiki_Syntax_Plugin::getPType()
48
     */
49
    public function getPType(): string
50
    {
51
        return 'block';
52
    }
53
54
    /**
55
     *
56
     * @see Doku_Parser_Mode::getSort()
57
     */
58
    public function getSort(): int
59
    {
60
        return 901;
61
    }
62
63
    /**
64
     *
65
     * @see Doku_Parser_Mode::connectTo()
66
     */
67
    public function connectTo($mode)
68
    {
69
        $this->Lexer->addSpecialPattern(
70
            '<olmap ?[^>\n]*>.*?</olmap>',
71
            $mode,
72
            'plugin_openlayersmap_olmap'
73
        );
74
    }
75
76
    /**
77
     *
78
     * @see DokuWiki_Syntax_Plugin::handle()
79
     */
80
    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...
81
    {
82
        // break matched data into its components
83
        $_tag       = explode('>', substr($match, 7, -9), 2);
84
        $str_params = $_tag[0];
85
        if (array_key_exists(1, $_tag)) {
86
            $str_points = $_tag[1];
87
        } else {
88
            $str_points = '';
89
        }
90
        // get the lat/lon for adding them to the metadata (used by geotag)
91
        preg_match('(lat[:|=]\"-?\d*\.?\d*\")', $match, $mainLat);
92
        preg_match('(lon[:|=]\"-?\d*\.?\d*\")', $match, $mainLon);
93
        $mainLat = substr($mainLat [0], 5, -1);
94
        $mainLon = substr($mainLon [0], 5, -1);
95
        if (!is_numeric($mainLat)) {
96
            $mainLat = $this->dflt ['lat'];
97
        }
98
        if (!is_numeric($mainLon)) {
99
            $mainLon = $this->dflt ['lon'];
100
        }
101
102
        $gmap          = $this->extractParams($str_params);
103
        $overlay = $this->extractPoints($str_points);
104
        $_firstimageID = '';
105
106
        $_nocache = false;
107
        // choose maptype based on the specified tag
108
        $imgUrl = "{{";
109
        if (stripos($gmap ['baselyr'], 'google') !== false) {
110
            // Google
111
            $imgUrl .= $this->getGoogle($gmap, $overlay);
112
            $imgUrl .= "&.png";
113
        } elseif (stripos($gmap ['baselyr'], 'bing') !== false) {
114
            // Bing
115
            if (!$this->getConf('bingAPIKey')) {
116
                // in case there is no Bing api key we'll use OSM
117
                $_firstimageID = $this->getStaticOSM($gmap, $overlay);
118
                $imgUrl        .= $_firstimageID;
119
                if ($this->getConf('optionStaticMapGenerator') == 'remote') {
120
                    $imgUrl .= "&.png";
121
                }
122
            } else {
123
                // seems that Bing doesn't like the DW client, turn off caching
124
                $_nocache = true;
125
                $imgUrl   .= $this->getBing($gmap, $overlay) . "&.png";
126
            }
127
        } /* elseif (stripos ( $gmap ['baselyr'], 'mapquest' ) !== false) {
128
            // MapQuest
129
            if (! $this->getConf ( 'mapquestAPIKey' )) {
130
                // no API key for MapQuest, use OSM
131
                $_firstimageID = $this->getStaticOSM ( $gmap, $overlay );
132
                $imgUrl .= $_firstimageID;
133
                if ($this->getConf ( 'optionStaticMapGenerator' ) == 'remote') {
134
                    $imgUrl .= "&.png";
135
                }
136
            } else {
137
                $imgUrl .= $this->_getMapQuest ( $gmap, $overlay );
138
                $imgUrl .= "&.png";
139
            }
140
        } */ else {
141
            // default OSM
142
            $_firstimageID = $this->getStaticOSM($gmap, $overlay);
143
            $imgUrl        .= $_firstimageID;
144
            if ($this->getConf('optionStaticMapGenerator') == 'remote') {
145
                $imgUrl .= "&.png";
146
            }
147
}
148
149
        // append dw p_render specific params and render
150
        $imgUrl .= "?" . str_replace("px", "", $gmap ['width']) . "x"
151
            . str_replace("px", "", $gmap ['height']);
152
        $imgUrl .= "&nolink";
153
154
        // add nocache option for selected services
155
if ($_nocache) {
156
    $imgUrl .= "&nocache";
157
}
158
159
        $imgUrl .= " |" . $gmap ['summary'] . " }}";
160
161
        $mapid = $gmap ['id'];
162
        // create a javascript parameter string for the map
163
        $param = '';
164
foreach ($gmap as $key => $val) {
165
    $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

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

318
            $text = /** @scrutinizer ignore-call */ p_get_instructions($text);
Loading history...
319
            // dbg ( $text );
320
            $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

320
            $text = /** @scrutinizer ignore-call */ p_render("xhtml", $text, $info);
Loading history...
321
            // dbg ( $text );
322
            $text       = addslashes(str_replace("\n", "", $text));
323
            $overlay [] = [$lat, $lon, $text, $angle, $opacity, $img];
324
        }
325
        return $overlay;
326
    }
327
328
    /**
329
     * Create a Google maps static image url w/ the poi.
330
     *
331
     * @param array $gmap
332
     * @param array $overlay
333
     */
334
    private function getGoogle(array $gmap, array $overlay): string
335
    {
336
        $sUrl = $this->getConf('iconUrlOverload');
337
        if (!$sUrl) {
338
            $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...
339
        }
340
        switch ($gmap ['baselyr']) {
341
            case 'google hybrid':
342
                $maptype = 'hybrid';
343
                break;
344
            case 'google sat':
345
                $maptype = 'satellite';
346
                break;
347
            case 'terrain':
348
            case 'google relief':
349
                $maptype = 'terrain';
350
                break;
351
            case 'google road':
352
            default:
353
                $maptype = 'roadmap';
354
                break;
355
        }
356
        // TODO maybe use viewport / visible instead of center/zoom,
357
        // see: https://developers.google.com/maps/documentation/staticmaps/index#Viewports
358
        // 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
359
        $imgUrl = "https://maps.googleapis.com/maps/api/staticmap?";
360
        $imgUrl .= "&size=" . str_replace("px", "", $gmap ['width']) . "x"
361
            . str_replace("px", "", $gmap ['height']);
362
        //if (!$this->getConf( 'autoZoomMap')) { // no need for center & zoom params }
363
        $imgUrl .= "&center=" . $gmap ['lat'] . "," . $gmap ['lon'];
364
        // max is 21 (== building scale), but that's overkill..
365
        if ($gmap ['zoom'] > 17) {
366
            $imgUrl .= "&zoom=17";
367
        } else {
368
            $imgUrl .= "&zoom=" . $gmap ['zoom'];
369
        }
370
        if ($overlay !== []) {
371
            $rowId = 0;
372
            foreach ($overlay as $data) {
373
                [$lat, $lon, $text, $angle, $opacity, $img] = $data;
374
                $imgUrl .= "&markers=icon%3a" . $sUrl . "lib/plugins/openlayersmap/icons/" . $img . "%7c"
375
                    . $lat . "," . $lon . "%7clabel%3a" . ++$rowId;
376
            }
377
        }
378
        $imgUrl .= "&format=png&maptype=" . $maptype;
379
        global $conf;
380
        $imgUrl .= "&language=" . $conf ['lang'];
381
        if ($this->getConf('googleAPIkey')) {
382
            $imgUrl .= "&key=" . $this->getConf('googleAPIkey');
383
        }
384
        return $imgUrl;
385
    }
386
387
    /**
388
     * Create a MapQuest static map API image url.
389
     *
390
     * @param array $gmap
391
     * @param array $overlay
392
     */
393
    /*
394
   private function _getMapQuest($gmap, $overlay) {
395
       $sUrl = $this->getConf ( 'iconUrlOverload' );
396
       if (! $sUrl) {
397
           $sUrl = DOKU_URL;
398
       }
399
       switch ($gmap ['baselyr']) {
400
           case 'mapquest hybrid' :
401
               $maptype = 'hyb';
402
               break;
403
           case 'mapquest sat' :
404
               // because sat coverage is very limited use 'hyb' instead of 'sat' so we don't get a blank map
405
               $maptype = 'hyb';
406
               break;
407
           case 'mapquest road' :
408
           default :
409
               $maptype = 'map';
410
               break;
411
       }
412
       $imgUrl = "http://open.mapquestapi.com/staticmap/v4/getmap?declutter=true&";
413
       if (count ( $overlay ) < 1) {
414
           $imgUrl .= "?center=" . $gmap ['lat'] . "," . $gmap ['lon'];
415
           // max level for mapquest is 16
416
           if ($gmap ['zoom'] > 16) {
417
               $imgUrl .= "&zoom=16";
418
           } else {
419
               $imgUrl .= "&zoom=" . $gmap ['zoom'];
420
           }
421
       }
422
       // use bestfit instead of center/zoom, needs upperleft/lowerright corners
423
       // $bbox=$this->calcBBOX($overlay, $gmap['lat'], $gmap['lon']);
424
       // $imgUrl .= "bestfit=".$bbox['minlat'].",".$bbox['maxlon'].",".$bbox['maxlat'].",".$bbox['minlon'];
425
426
       // TODO declutter option works well for square maps but not for rectangular, maybe compensate for that
427
       //       or compensate the mbr..
428
429
       $imgUrl .= "&size=" . str_replace ( "px", "", $gmap ['width'] ) . "," . str_replace ("px","",$gmap['height']);
430
431
       // TODO mapquest allows using one image url with a multiplier $NUMBER eg:
432
       // $NUMBER = 2
433
       // $imgUrl .= DOKU_URL."/".DOKU_PLUGIN."/".getPluginName()."/icons/".$img.",$NUMBER,C,"
434
        //  .$lat1.",".$lon1.",0,0,0,0,C,".$lat2.",".$lon2.",0,0,0,0";
435
       if (! empty ( $overlay )) {
436
           $imgUrl .= "&xis=";
437
           foreach ( $overlay as $data ) {
438
               list ( $lat, $lon, $text, $angle, $opacity, $img ) = $data;
439
               // $imgUrl .= $sUrl."lib/plugins/openlayersmap/icons/".$img.",1,C,".$lat.",".$lon.",0,0,0,0,";
440
               $imgUrl .= $sUrl . "lib/plugins/openlayersmap/icons/" . $img . ",1,C," . $lat . "," . $lon . ",";
441
           }
442
           $imgUrl = substr ( $imgUrl, 0, - 1 );
443
       }
444
       $imgUrl .= "&imageType=png&type=" . $maptype;
445
       $imgUrl .= "&key=".$this->getConf ( 'mapquestAPIKey' );
446
       return $imgUrl;
447
   }
448
   */
449
450
    /**
451
     * Create a static OSM map image url w/ the poi from http://staticmap.openstreetmap.de (staticMapLite)
452
     * use http://staticmap.openstreetmap.de "staticMapLite" or a local version
453
     *
454
     * @param array $gmap
455
     * @param array $overlay
456
     *
457
     * @return false|string
458
     * @todo implementation for http://ojw.dev.openstreetmap.org/StaticMapDev/
459
     */
460
    private function getStaticOSM(array $gmap, array $overlay)
461
    {
462
        global $conf;
463
464
        if ($this->getConf('optionStaticMapGenerator') === 'local') {
465
            // using local basemap composer
466
            if (($myMap = plugin_load('helper', 'openlayersmap_staticmap')) === null) {
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

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

678
        return /** @scrutinizer ignore-call */ hsc($dms . $latPos);
Loading history...
679
    }
680
681
    /**
682
     * Convert decimal degrees to degrees, minutes, seconds format
683
     *
684
     * @param float $decimaldegrees
685
     * @return string dms
686
     * @todo move this into a shared library
687
     */
688
    private function convertDDtoDMS(float $decimaldegrees): string
689
    {
690
        $dms  = floor($decimaldegrees);
691
        $secs = ($decimaldegrees - $dms) * 3600;
692
        $min  = floor($secs / 60);
693
        $sec  = round($secs - ($min * 60), 3);
694
        $dms  .= 'º' . $min . '\'' . $sec . '"';
695
        return $dms;
696
    }
697
698
    /**
699
     * convert longitude in decimal degrees to DMS+hemisphere.
700
     *
701
     * @param float $decimaldegrees
702
     * @todo move this into a shared library
703
     */
704
    private function convertLon(float $decimaldegrees): string
705
    {
706
        if (strpos($decimaldegrees, '-') !== false) {
707
            $lonPos = "W";
708
        } else {
709
            $lonPos = "E";
710
        }
711
        $dms = $this->convertDDtoDMS(abs($decimaldegrees));
712
        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

712
        return /** @scrutinizer ignore-call */ hsc($dms . $lonPos);
Loading history...
713
    }
714
715
    /**
716
     * Figures out the base filename of a media path.
717
     *
718
     * @param string $mediaLink
719
     */
720
    private function getFileName(string $mediaLink): string
721
    {
722
        $mediaLink = str_replace('[[', '', $mediaLink);
723
        $mediaLink = str_replace(']]', '', $mediaLink);
724
        $mediaLink = substr($mediaLink, 0, -4);
725
726
        $parts     = explode(':', $mediaLink);
727
        $mediaLink = end($parts);
728
        return str_replace('_', ' ', $mediaLink);
729
    }
730
731
    /**
732
     *
733
     * @see DokuWiki_Syntax_Plugin::render()
734
     */
735
    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...
736
    {
737
        // set to true after external scripts tags are written
738
        static $initialised = false;
739
        // incremented for each map tag in the page source so we can keep track of each map in this page
740
        static $mapnumber = 0;
741
742
        [$mapid, $param, $mainLat, $mainLon, $poitable, $poitabledesc, $staticImgUrl, $_firstimage] = $data;
743
744
        if ($format === 'xhtml') {
745
            $olscript     = '';
746
            $stadiaEnable = $this->getConf('enableStadia');
747
            $osmEnable    = $this->getConf('enableOSM');
748
            $enableBing   = $this->getConf('enableBing');
749
750
            $scriptEnable = '';
751
            if (!$initialised) {
752
                $initialised = true;
753
                // render necessary script tags only once
754
                $olscript = '<script defer="defer" src="' . DOKU_BASE . 'lib/plugins/openlayersmap/ol/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...
755
<script defer="defer" src="' . DOKU_BASE . 'lib/plugins/openlayersmap/ol/ol-layerswitcher.js"></script>';
756
757
                $scriptEnable = '<script defer="defer" src="data:text/javascript;base64,';
758
                $scriptSrc    = $olscript ? 'const olEnable=true;' : 'const olEnable=false;';
759
                $scriptSrc    .= 'const osmEnable=' . ($osmEnable ? 'true' : 'false') . ';';
760
                $scriptSrc    .= 'const stadiaEnable=' . ($stadiaEnable ? 'true' : 'false') . ';';
761
                $scriptSrc    .= 'const bEnable=' . ($enableBing ? 'true' : 'false') . ';';
762
                $scriptSrc    .= 'const bApiKey="' . $this->getConf('bingAPIKey') . '";';
763
                $scriptSrc    .= 'const tfApiKey="' . $this->getConf('tfApiKey') . '";';
764
                $scriptSrc    .= 'const gApiKey="' . $this->getConf('googleAPIkey') . '";';
765
                $scriptSrc    .= 'olMapData = []; let olMaps = {}; let olMapOverlays = {};';
766
                $scriptEnable .= base64_encode($scriptSrc);
767
                $scriptEnable .= '"></script>';
768
            }
769
            $renderer->doc .= "$olscript\n$scriptEnable";
770
            $renderer->doc .= '<div class="olMapHelp">' . $this->locale_xhtml("help") . '</div>';
771
            if ($this->getConf('enableA11y')) {
772
                $renderer->doc .= '<div id="' . $mapid . '-static" class="olStaticMap">'
773
                    . p_render($format, p_get_instructions($staticImgUrl), $info) . '</div>';
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_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

773
                    . 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

773
                    . /** @scrutinizer ignore-call */ p_render($format, p_get_instructions($staticImgUrl), $info) . '</div>';
Loading history...
774
            }
775
            $renderer->doc .= '<div id="' . $mapid . '-clearer" class="clearer"><p>&nbsp;</p></div>';
776
            if ($this->getConf('enableA11y')) {
777
                // render a table of the POI for the print and a11y presentation, it is hidden using javascript
778
                $renderer->doc .= '
779
                <div id="' . $mapid . '-table-span" class="olPOItableSpan">
780
                    <table id="' . $mapid . '-table" class="olPOItable">
781
                    <caption class="olPOITblCaption">' . $this->getLang('olmapPOItitle') . '</caption>
782
                    <thead class="olPOITblHeader">
783
                    <tr>
784
                    <th class="rowId" scope="col">id</th>
785
                    <th class="icon" scope="col">' . $this->getLang('olmapPOIicon') . '</th>
786
                    <th class="lat" scope="col" title="' . $this->getLang('olmapPOIlatTitle') . '">'
787
                    . $this->getLang('olmapPOIlat') . '</th>
788
                    <th class="lon" scope="col" title="' . $this->getLang('olmapPOIlonTitle') . '">'
789
                    . $this->getLang('olmapPOIlon') . '</th>
790
                    <th class="txt" scope="col">' . $this->getLang('olmapPOItxt') . '</th>
791
                    </tr>
792
                    </thead>';
793
                if ($poitabledesc != '') {
794
                    $renderer->doc .= '<tfoot class="olPOITblFooter"><tr><td colspan="5">' . $poitabledesc
795
                        . '</td></tr></tfoot>';
796
                }
797
                $renderer->doc .= '<tbody class="olPOITblBody">' . $poitable . '</tbody>
798
                    </table>
799
                </div>';
800
                $renderer->doc .= "\n";
801
            }
802
            // render inline mapscript parts
803
            $renderer->doc .= '<script defer="defer" src="data:text/javascript;base64,';
804
            $renderer->doc .= base64_encode("olMapData[$mapnumber] = $param");
805
            $renderer->doc .= '"></script>';
806
            $mapnumber++;
807
            return true;
808
        } elseif ($format === 'metadata') {
809
            if (!(($this->dflt ['lat'] == $mainLat) && ($this->dflt ['lon'] == $mainLon))) {
810
                // render geo metadata, unless they are the default
811
                $renderer->meta ['geo'] ['lat'] = $mainLat;
812
                $renderer->meta ['geo'] ['lon'] = $mainLon;
813
                if (($geophp = plugin_load('helper', 'geophp')) !== null) {
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

813
                if (($geophp = /** @scrutinizer ignore-call */ plugin_load('helper', 'geophp')) !== null) {
Loading history...
Unused Code introduced by
The assignment to $geophp is dead and can be removed.
Loading history...
814
                    // if we have the geoPHP helper, add the geohash
815
                    try{
816
                        $renderer->meta['geo']['geohash'] = (new Point($mainLon, $mainLat))->out('geohash');
817
                    } catch (Exception $e) {
818
                        Logger::error("Failed to create geohash for: $mainLat, $mainLon");
819
                    }
820
                }
821
            }
822
823
            if (($this->getConf('enableA11y')) && (!empty($_firstimage))) {
824
                // add map local image into relation/firstimage if not already filled and when it is a local image
825
826
                global $ID;
827
                $rel = p_get_metadata($ID, 'relation', METADATA_RENDER_USING_CACHE);
0 ignored issues
show
Bug introduced by
The constant METADATA_RENDER_USING_CACHE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
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

827
                $rel = /** @scrutinizer ignore-call */ p_get_metadata($ID, 'relation', METADATA_RENDER_USING_CACHE);
Loading history...
828
                // $img = $rel ['firstimage'];
829
                if (empty($rel ['firstimage']) /* || $img == $_firstimage*/) {
830
                    //Logger::debug(
831
                    // 'olmap::render#rendering image relation metadata for _firstimage as $img was empty or same.',
832
                    // $_firstimage);
833
                    
834
                    // This seems to never work; the firstimage entry in the .meta file is empty
835
                    // $renderer->meta['relation']['firstimage'] = $_firstimage;
836
                    // ... and neither does this; the firstimage entry in the .meta file is empty
837
                    // $relation = array('relation'=>array('firstimage'=>$_firstimage));
838
                    // p_set_metadata($ID, $relation, false, false);
839
                    // ... this works
840
                    $renderer->internalmedia($_firstimage, $poitabledesc);
841
                }
842
            }
843
            return true;
844
        }
845
        return false;
846
    }
847
}
848