Completed
Pull Request — master (#25)
by Mark
01:27
created
action.php 2 patches
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -262,11 +262,11 @@
 block discarded – undo
262 262
      */
263 263
     private function printHTML(array $searchresults, bool $showMedia = true): void
264 264
     {
265
-        $pages = (array)($searchresults ['pages']);
266
-        $media = (array)$searchresults ['media'];
267
-        $lat = (float)$searchresults ['lat'];
268
-        $lon = (float)$searchresults ['lon'];
269
-        $geohash = (string)$searchresults ['geohash'];
265
+        $pages = ( array ) ($searchresults ['pages']);
266
+        $media = ( array ) $searchresults ['media'];
267
+        $lat = ( float ) $searchresults ['lat'];
268
+        $lon = ( float ) $searchresults ['lon'];
269
+        $geohash = ( string ) $searchresults ['geohash'];
270 270
 
271 271
         if (isset ($searchresults ['error'])) {
272 272
             print '<div class="level1"><p>' . hsc($searchresults ['error']) . '</p></div>';
Please login to merge, or discard this patch.
Indentation   +415 added lines, -415 removed lines patch added patch discarded remove patch
@@ -26,419 +26,419 @@
 block discarded – undo
26 26
 class action_plugin_spatialhelper extends DokuWiki_Action_Plugin
27 27
 {
28 28
 
29
-    /**
30
-     * Register for events.
31
-     *
32
-     * @param Doku_Event_Handler $controller
33
-     *          DokuWiki's event controller object. Also available as global $EVENT_HANDLER
34
-     */
35
-    public function register(Doku_Event_Handler $controller): void
36
-    {
37
-        // listen for page add / delete events
38
-        // http://www.dokuwiki.org/devel:event:indexer_page_add
39
-        $controller->register_hook('INDEXER_PAGE_ADD', 'BEFORE', $this, 'handleIndexerPageAdd');
40
-        $controller->register_hook('IO_WIKIPAGE_WRITE', 'BEFORE', $this, 'removeFromIndex');
41
-
42
-        // http://www.dokuwiki.org/devel:event:sitemap_generate
43
-        $controller->register_hook('SITEMAP_GENERATE', 'BEFORE', $this, 'handleSitemapGenerateBefore');
44
-        // using after will only trigger us if a sitemap was actually created
45
-        $controller->register_hook('SITEMAP_GENERATE', 'AFTER', $this, 'handleSitemapGenerateAfter');
46
-
47
-        // handle actions we know of
48
-        $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'handleActionActPreprocess', array());
49
-        // handle HTML eg. /dokuwiki/doku.php?id=start&do=findnearby&geohash=u15vk4
50
-        $controller->register_hook(
51
-            'TPL_ACT_UNKNOWN', 'BEFORE', $this, 'findnearby', array('format' => 'HTML')
52
-        );
53
-        // handles AJAX/json eg: jQuery.post("/dokuwiki/lib/exe/ajax.php?id=start&call=findnearby&geohash=u15vk4");
54
-        $controller->register_hook(
55
-            'AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'findnearby', array('format' => 'JSON')
56
-        );
57
-
58
-        // listen for media uploads and deletes
59
-        $controller->register_hook('MEDIA_UPLOAD_FINISH', 'BEFORE', $this, 'handleMediaUploaded', array());
60
-        $controller->register_hook('MEDIA_DELETE_FILE', 'BEFORE', $this, 'handleMediaDeleted', array());
61
-
62
-        $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'handleMetaheaderOutput');
63
-    }
64
-
65
-    /**
66
-     * Update the spatial index for the page.
67
-     *
68
-     * @param Doku_Event $event
69
-     *          event object
70
-     * @param mixed $param
71
-     *          the parameters passed to register_hook when this handler was registered
72
-     */
73
-    public function handleIndexerPageAdd(Doku_Event $event, $param): void
74
-    {
75
-        // $event→data['page'] – the page id
76
-        // $event→data['body'] – empty, can be filled by additional content to index by your plugin
77
-        // $event→data['metadata'] – the metadata that shall be indexed. This is an array where the keys are the
78
-        //    metadata indexes and the value a string or an array of strings with the values.
79
-        //    title and relation_references will already be set.
80
-        $id = $event->data ['page'];
81
-        $indexer = plugin_load('helper', 'spatialhelper_index');
82
-        $entries = $indexer->updateSpatialIndex($id);
83
-    }
84
-
85
-    /**
86
-     * Update the spatial index, removing the page.
87
-     *
88
-     * @param Doku_Event $event
89
-     *          event object
90
-     * @param mixed $param
91
-     *          the parameters passed to register_hook when this handler was registered
92
-     */
93
-    public function removeFromIndex(Doku_Event $event, $param): void
94
-    {
95
-        // event data:
96
-        // $data[0] – The raw arguments for io_saveFile as an array. Do not change file path.
97
-        // $data[0][0] – the file path.
98
-        // $data[0][1] – the content to be saved, and may be modified.
99
-        // $data[1] – ns: The colon separated namespace path minus the trailing page name. (false if root ns)
100
-        // $data[2] – page_name: The wiki page name.
101
-        // $data[3] – rev: The page revision, false for current wiki pages.
102
-
103
-        Logger::getInstance(Logger::LOG_DEBUG)->log("Event data in removeFromIndex.", $event->data);
104
-        if (@file_exists($event->data [0] [0])) {
105
-            // file not new
106
-            if (!$event->data [0] [1]) {
107
-                // file is empty, page is being deleted
108
-                if (empty ($event->data [1])) {
109
-                    // root namespace
110
-                    $id = $event->data [2];
111
-                } else {
112
-                    $id = $event->data [1] . ":" . $event->data [2];
113
-                }
114
-                $indexer = plugin_load('helper', 'spatialhelper_index');
115
-                if ($indexer) {
116
-                    $indexer->deleteFromIndex($id);
117
-                }
118
-            }
119
-        }
120
-    }
121
-
122
-    /**
123
-     * Add a new SitemapItem object that points to the KML of public geocoded pages.
124
-     *
125
-     * @param Doku_Event $event
126
-     * @param mixed $param
127
-     */
128
-    public function handleSitemapGenerateBefore(Doku_Event $event, $param): void
129
-    {
130
-        $path = mediaFN($this->getConf('media_kml'));
131
-        $lastmod = @filemtime($path);
132
-        $event->data ['items'] [] = new Item(
133
-            ml($this->getConf('media_kml'),
134
-                '',
135
-                true,
136
-                '&amp;',
137
-                true),
138
-            $lastmod
139
-        );
140
-    }
141
-
142
-    /**
143
-     * Create a spatial sitemap or attach the geo/kml map to the sitemap.
144
-     *
145
-     * @param Doku_Event $event
146
-     *          event object, not used
147
-     * @param mixed $param
148
-     *          parameter array, not used
149
-     */
150
-    public function handleSitemapGenerateAfter(Doku_Event $event, $param): bool
151
-    {
152
-        // $event→data['items']: Array of SitemapItem instances, the array of sitemap items that already
153
-        //      contains all public pages of the wiki
154
-        // $event→data['sitemap']: The path of the file the sitemap will be saved to.
155
-        if ($helper = plugin_load('helper', 'spatialhelper_sitemap')) {
156
-            $kml = $helper->createKMLSitemap($this->getConf('media_kml'));
157
-            $rss = $helper->createGeoRSSSitemap($this->getConf('media_georss'));
158
-
159
-            if (!empty ($this->getConf('sitemap_namespaces'))) {
160
-                $namespaces = array_map(
161
-                    'trim',
162
-                    explode("\n",
163
-                        $this->getConf('sitemap_namespaces'))
164
-                );
165
-                foreach ($namespaces as $namespace) {
166
-                    $kmlN = $helper->createKMLSitemap($namespace . $this->getConf('media_kml'));
167
-                    $rssN = $helper->createGeoRSSSitemap($namespace . $this->getConf('media_georss'));
168
-                    Logger::getInstance(Logger::LOG_DEBUG)->log(
169
-                        "handleSitemapGenerateAfter, created KML / GeoRSS sitemap in $namespace, succes: ",
170
-                        $kmlN && $rssN
171
-                    );
172
-                }
173
-            }
174
-            return $kml && $rss;
175
-        } else {
176
-            Logger::getInstance(Logger::LOG_DEBUG)->log("createSpatialSitemap NOT loaded helper.", $helper);
177
-        }
178
-    }
179
-
180
-    /**
181
-     * trap findnearby action.
182
-     * This addional handler is required as described at: https://www.dokuwiki.org/devel:event:tpl_act_unknown
183
-     *
184
-     * @param Doku_Event $event
185
-     *          event object
186
-     * @param mixed $param
187
-     *          not used
188
-     */
189
-    public function handleActionActPreprocess(Doku_Event $event, $param): void
190
-    {
191
-        if ($event->data !== 'findnearby') {
192
-            return;
193
-        }
194
-        $event->preventDefault();
195
-    }
196
-
197
-    /**
198
-     * handle findnearby action.
199
-     *
200
-     * @param Doku_Event $event
201
-     *          event object
202
-     * @param mixed $param
203
-     *          associative array with keys
204
-     *          'format'=> HTML | JSON
205
-     */
206
-    public function findnearby(Doku_Event $event, $param): void
207
-    {
208
-        if ($event->data !== 'findnearby') {
209
-            return;
210
-        }
211
-        $event->preventDefault();
212
-        $results = array();
213
-        global $INPUT;
214
-        if ($helper = plugin_load('helper', 'spatialhelper_search')) {
215
-            if ($INPUT->has('lat') && $INPUT->has('lon')) {
216
-                $results = $helper->findNearbyLatLon($INPUT->param('lat'), $INPUT->param('lon'));
217
-            } elseif ($INPUT->has('geohash')) {
218
-                $results = $helper->findNearby($INPUT->str('geohash'));
219
-            } else {
220
-                $results = array(
221
-                    'error' => hsc($this->getLang('invalidinput'))
222
-                );
223
-            }
224
-        }
225
-
226
-        $showMedia = $INPUT->bool('showMedia', true);
227
-
228
-        switch ($param['format']) {
229
-            case 'JSON' :
230
-                $this->printJSON($results);
231
-                break;
232
-            case 'HTML' :
233
-                // fall through to default
234
-            default :
235
-                $this->printHTML($results, $showMedia);
236
-                break;
237
-        }
238
-    }
239
-
240
-    /**
241
-     * Print seachresults as HTML lists.
242
-     *
243
-     * @param array $searchresults
244
-     */
245
-    private function printJSON(array $searchresults): void
246
-    {
247
-        require_once DOKU_INC . 'inc/JSON.php';
248
-        $json = new JSON();
249
-        header('Content-Type: application/json');
250
-        print $json->encode($searchresults);
251
-    }
252
-
253
-    /**
254
-     * Print seachresults as HTML lists.
255
-     *
256
-     * @param array $searchresults
257
-     * @param bool $showMedia
258
-     */
259
-    private function printHTML(array $searchresults, bool $showMedia = true): void
260
-    {
261
-        $pages = (array)($searchresults ['pages']);
262
-        $media = (array)$searchresults ['media'];
263
-        $lat = (float)$searchresults ['lat'];
264
-        $lon = (float)$searchresults ['lon'];
265
-        $geohash = (string)$searchresults ['geohash'];
266
-
267
-        if (isset ($searchresults ['error'])) {
268
-            print '<div class="level1"><p>' . hsc($searchresults ['error']) . '</p></div>';
269
-            return;
270
-        }
271
-
272
-        // print a HTML list
273
-        print '<h1>' . $this->getLang('results_header') . '</h1>' . DOKU_LF;
274
-        print '<div class="level1">' . DOKU_LF;
275
-        if (!empty ($pages)) {
276
-            $pagelist = '<ol>' . DOKU_LF;
277
-            foreach ($pages as $page) {
278
-                $pagelist .= '<li>' . html_wikilink(
279
-                        ':' . $page ['id'], useHeading('navigation') ? null :
280
-                        noNS($page ['id'])
281
-                    ) . ' (' . $this->getLang('results_distance_prefix')
282
-                    . $page ['distance'] . '&nbsp;m) ' . $page ['description'] . '</li>' . DOKU_LF;
283
-            }
284
-            $pagelist .= '</ol>' . DOKU_LF;
285
-
286
-            print '<h2>' . $this->getLang('results_pages') . hsc(
287
-                    ' lat;lon: ' . $lat . ';' . $lon
288
-                    . ' (geohash: ' . $geohash . ')'
289
-                ) . '</h2>';
290
-            print '<div class="level2">' . DOKU_LF;
291
-            print $pagelist;
292
-            print '</div>' . DOKU_LF;
293
-        } else {
294
-            print '<p>' . hsc($this->getLang('nothingfound')) . '</p>';
295
-        }
296
-
297
-        if (!empty ($media) && $showMedia) {
298
-            $pagelist = '<ol>' . DOKU_LF;
299
-            foreach ($media as $m) {
300
-                $opts = array();
301
-                $link = ml($m ['id'], $opts, false, '&amp;', false);
302
-                $opts ['w'] = '100';
303
-                $src = ml($m ['id'], $opts);
304
-                $pagelist .= '<li><a href="' . $link . '"><img src="' . $src . '"></a> ('
305
-                    . $this->getLang('results_distance_prefix') . $page ['distance'] . '&nbsp;m) ' . hsc($desc)
306
-                    . '</li>' . DOKU_LF;
307
-            }
308
-            $pagelist .= '</ol>' . DOKU_LF;
309
-
310
-            print '<h2>' . $this->getLang('results_media') . hsc(
311
-                    ' lat;lon: ' . $lat . ';' . $lon
312
-                    . ' (geohash: ' . $geohash . ')'
313
-                ) . '</h2>' . DOKU_LF;
314
-            print '<div class="level2">' . DOKU_LF;
315
-            print $pagelist;
316
-            print '</div>' . DOKU_LF;
317
-        }
318
-        print '<p>' . $this->getLang('results_precision') . $searchresults ['precision'] . ' m. ';
319
-        if (strlen($geohash) > 1) {
320
-            $url = wl(
321
-                getID(), array(
322
-                    'do' => 'findnearby',
323
-                    'geohash' => substr($geohash, 0, -1)
324
-                )
325
-            );
326
-            print '<a href="' . $url . '" class="findnearby">' . $this->getLang('search_largerarea') . '</a>.</p>'
327
-                . DOKU_LF;
328
-        }
329
-        print '</div>' . DOKU_LF;
330
-    }
331
-
332
-    /**
333
-     * add media to spatial index.
334
-     *
335
-     * @param Doku_Event $event
336
-     * @param mixed $param
337
-     */
338
-    public function handleMediaUploaded(Doku_Event $event, $param): void
339
-    {
340
-        // data[0] temporary file name (read from $_FILES)
341
-        // data[1] file name of the file being uploaded
342
-        // data[2] future directory id of the file being uploaded
343
-        // data[3] the mime type of the file being uploaded
344
-        // data[4] true if the uploaded file exists already
345
-        // data[5] (since 2011-02-06) the PHP function used to move the file to the correct location
346
-
347
-        Logger::getInstance(Logger::LOG_DEBUG)->log("handleMediaUploaded::event data", $event->data);
348
-
349
-        // check the list of mimetypes
350
-        // if it's a supported type call appropriate index function
351
-        if (substr_compare($event->data [3], 'image/jpeg', 0)) {
352
-            $indexer = plugin_load('helper', 'spatialhelper_index');
353
-            if ($indexer) {
354
-                $indexer->indexImage($event->data [2], $event->data [1]);
355
-            }
356
-        }
357
-        // TODO add image/tiff
358
-        // TODO kml, gpx, geojson...
359
-    }
360
-
361
-    /**
362
-     * removes the media from the index.
363
-     */
364
-    public function handleMediaDeleted(Doku_Event $event, $param): void
365
-    {
366
-        // data['id'] ID data['unl'] unlink return code
367
-        // data['del'] Namespace directory unlink return code
368
-        // data['name'] file name data['path'] full path to the file
369
-        // data['size'] file size
370
-
371
-        Logger::getInstance(Logger::LOG_DEBUG)->log("handleMediaDeleted::event data", $event->data);
372
-
373
-        // remove the media id from the index
374
-        $indexer = plugin_load('helper', 'spatialhelper_index');
375
-        if ($indexer) {
376
-            $indexer->deleteFromIndex('media__' . $event->data ['id']);
377
-        }
378
-    }
379
-
380
-    /**
381
-     * add a link to the spatial sitemap files in the header.
382
-     *
383
-     * @param Doku_Event $event
384
-     *          the DokuWiki event. $event->data is a two-dimensional
385
-     *          array of all meta headers. The keys are meta, link and script.
386
-     * @param mixed $param
387
-     *
388
-     * @see http://www.dokuwiki.org/devel:event:tpl_metaheader_output
389
-     */
390
-    public function handleMetaheaderOutput(Doku_Event $event, $param): void
391
-    {
392
-        // TODO maybe test for exist
393
-        $event->data ["link"] [] = array(
394
-            "type" => "application/atom+xml",
395
-            "rel" => "alternate",
396
-            "href" => ml($this->getConf('media_georss')),
397
-            "title" => "Spatial ATOM Feed"
398
-        );
399
-        $event->data ["link"] [] = array(
400
-            "type" => "application/vnd.google-earth.kml+xml",
401
-            "rel" => "alternate",
402
-            "href" => ml($this->getConf('media_kml')),
403
-            "title" => "KML Sitemap"
404
-        );
405
-    }
406
-
407
-    /**
408
-     * Calculate a new coordinate based on start, distance and bearing
409
-     *
410
-     * @param $start array
411
-     *               - start coordinate as decimal lat/lon pair
412
-     * @param $dist  float
413
-     *               - distance in kilometers
414
-     * @param $brng  float
415
-     *               - bearing in degrees (compass direction)
416
-     */
417
-    private function geoDestination(array $start, float $dist, float $brng): array
418
-    {
419
-        $lat1 = $this->toRad($start [0]);
420
-        $lon1 = $this->toRad($start [1]);
421
-        // http://en.wikipedia.org/wiki/Earth_radius
422
-        // average earth radius in km
423
-        $dist = $dist / 6371.01;
424
-        $brng = $this->toRad($brng);
425
-
426
-        $lon2 = $lon1 + atan2(sin($brng) * sin($dist) * cos($lat1), cos($dist) - sin($lat1) * sin($lat2));
427
-        $lon2 = fmod(($lon2 + 3 * M_PI), (2 * M_PI)) - M_PI;
428
-
429
-        return array(
430
-            $this->toDeg($lat2),
431
-            $this->toDeg($lon2)
432
-        );
433
-    }
434
-
435
-    private function toRad(float $deg): float
436
-    {
437
-        return $deg * M_PI / 180;
438
-    }
439
-
440
-    private function toDeg(float $rad): float
441
-    {
442
-        return $rad * 180 / M_PI;
443
-    }
29
+	/**
30
+	 * Register for events.
31
+	 *
32
+	 * @param Doku_Event_Handler $controller
33
+	 *          DokuWiki's event controller object. Also available as global $EVENT_HANDLER
34
+	 */
35
+	public function register(Doku_Event_Handler $controller): void
36
+	{
37
+		// listen for page add / delete events
38
+		// http://www.dokuwiki.org/devel:event:indexer_page_add
39
+		$controller->register_hook('INDEXER_PAGE_ADD', 'BEFORE', $this, 'handleIndexerPageAdd');
40
+		$controller->register_hook('IO_WIKIPAGE_WRITE', 'BEFORE', $this, 'removeFromIndex');
41
+
42
+		// http://www.dokuwiki.org/devel:event:sitemap_generate
43
+		$controller->register_hook('SITEMAP_GENERATE', 'BEFORE', $this, 'handleSitemapGenerateBefore');
44
+		// using after will only trigger us if a sitemap was actually created
45
+		$controller->register_hook('SITEMAP_GENERATE', 'AFTER', $this, 'handleSitemapGenerateAfter');
46
+
47
+		// handle actions we know of
48
+		$controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'handleActionActPreprocess', array());
49
+		// handle HTML eg. /dokuwiki/doku.php?id=start&do=findnearby&geohash=u15vk4
50
+		$controller->register_hook(
51
+			'TPL_ACT_UNKNOWN', 'BEFORE', $this, 'findnearby', array('format' => 'HTML')
52
+		);
53
+		// handles AJAX/json eg: jQuery.post("/dokuwiki/lib/exe/ajax.php?id=start&call=findnearby&geohash=u15vk4");
54
+		$controller->register_hook(
55
+			'AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'findnearby', array('format' => 'JSON')
56
+		);
57
+
58
+		// listen for media uploads and deletes
59
+		$controller->register_hook('MEDIA_UPLOAD_FINISH', 'BEFORE', $this, 'handleMediaUploaded', array());
60
+		$controller->register_hook('MEDIA_DELETE_FILE', 'BEFORE', $this, 'handleMediaDeleted', array());
61
+
62
+		$controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'handleMetaheaderOutput');
63
+	}
64
+
65
+	/**
66
+	 * Update the spatial index for the page.
67
+	 *
68
+	 * @param Doku_Event $event
69
+	 *          event object
70
+	 * @param mixed $param
71
+	 *          the parameters passed to register_hook when this handler was registered
72
+	 */
73
+	public function handleIndexerPageAdd(Doku_Event $event, $param): void
74
+	{
75
+		// $event→data['page'] – the page id
76
+		// $event→data['body'] – empty, can be filled by additional content to index by your plugin
77
+		// $event→data['metadata'] – the metadata that shall be indexed. This is an array where the keys are the
78
+		//    metadata indexes and the value a string or an array of strings with the values.
79
+		//    title and relation_references will already be set.
80
+		$id = $event->data ['page'];
81
+		$indexer = plugin_load('helper', 'spatialhelper_index');
82
+		$entries = $indexer->updateSpatialIndex($id);
83
+	}
84
+
85
+	/**
86
+	 * Update the spatial index, removing the page.
87
+	 *
88
+	 * @param Doku_Event $event
89
+	 *          event object
90
+	 * @param mixed $param
91
+	 *          the parameters passed to register_hook when this handler was registered
92
+	 */
93
+	public function removeFromIndex(Doku_Event $event, $param): void
94
+	{
95
+		// event data:
96
+		// $data[0] – The raw arguments for io_saveFile as an array. Do not change file path.
97
+		// $data[0][0] – the file path.
98
+		// $data[0][1] – the content to be saved, and may be modified.
99
+		// $data[1] – ns: The colon separated namespace path minus the trailing page name. (false if root ns)
100
+		// $data[2] – page_name: The wiki page name.
101
+		// $data[3] – rev: The page revision, false for current wiki pages.
102
+
103
+		Logger::getInstance(Logger::LOG_DEBUG)->log("Event data in removeFromIndex.", $event->data);
104
+		if (@file_exists($event->data [0] [0])) {
105
+			// file not new
106
+			if (!$event->data [0] [1]) {
107
+				// file is empty, page is being deleted
108
+				if (empty ($event->data [1])) {
109
+					// root namespace
110
+					$id = $event->data [2];
111
+				} else {
112
+					$id = $event->data [1] . ":" . $event->data [2];
113
+				}
114
+				$indexer = plugin_load('helper', 'spatialhelper_index');
115
+				if ($indexer) {
116
+					$indexer->deleteFromIndex($id);
117
+				}
118
+			}
119
+		}
120
+	}
121
+
122
+	/**
123
+	 * Add a new SitemapItem object that points to the KML of public geocoded pages.
124
+	 *
125
+	 * @param Doku_Event $event
126
+	 * @param mixed $param
127
+	 */
128
+	public function handleSitemapGenerateBefore(Doku_Event $event, $param): void
129
+	{
130
+		$path = mediaFN($this->getConf('media_kml'));
131
+		$lastmod = @filemtime($path);
132
+		$event->data ['items'] [] = new Item(
133
+			ml($this->getConf('media_kml'),
134
+				'',
135
+				true,
136
+				'&amp;',
137
+				true),
138
+			$lastmod
139
+		);
140
+	}
141
+
142
+	/**
143
+	 * Create a spatial sitemap or attach the geo/kml map to the sitemap.
144
+	 *
145
+	 * @param Doku_Event $event
146
+	 *          event object, not used
147
+	 * @param mixed $param
148
+	 *          parameter array, not used
149
+	 */
150
+	public function handleSitemapGenerateAfter(Doku_Event $event, $param): bool
151
+	{
152
+		// $event→data['items']: Array of SitemapItem instances, the array of sitemap items that already
153
+		//      contains all public pages of the wiki
154
+		// $event→data['sitemap']: The path of the file the sitemap will be saved to.
155
+		if ($helper = plugin_load('helper', 'spatialhelper_sitemap')) {
156
+			$kml = $helper->createKMLSitemap($this->getConf('media_kml'));
157
+			$rss = $helper->createGeoRSSSitemap($this->getConf('media_georss'));
158
+
159
+			if (!empty ($this->getConf('sitemap_namespaces'))) {
160
+				$namespaces = array_map(
161
+					'trim',
162
+					explode("\n",
163
+						$this->getConf('sitemap_namespaces'))
164
+				);
165
+				foreach ($namespaces as $namespace) {
166
+					$kmlN = $helper->createKMLSitemap($namespace . $this->getConf('media_kml'));
167
+					$rssN = $helper->createGeoRSSSitemap($namespace . $this->getConf('media_georss'));
168
+					Logger::getInstance(Logger::LOG_DEBUG)->log(
169
+						"handleSitemapGenerateAfter, created KML / GeoRSS sitemap in $namespace, succes: ",
170
+						$kmlN && $rssN
171
+					);
172
+				}
173
+			}
174
+			return $kml && $rss;
175
+		} else {
176
+			Logger::getInstance(Logger::LOG_DEBUG)->log("createSpatialSitemap NOT loaded helper.", $helper);
177
+		}
178
+	}
179
+
180
+	/**
181
+	 * trap findnearby action.
182
+	 * This addional handler is required as described at: https://www.dokuwiki.org/devel:event:tpl_act_unknown
183
+	 *
184
+	 * @param Doku_Event $event
185
+	 *          event object
186
+	 * @param mixed $param
187
+	 *          not used
188
+	 */
189
+	public function handleActionActPreprocess(Doku_Event $event, $param): void
190
+	{
191
+		if ($event->data !== 'findnearby') {
192
+			return;
193
+		}
194
+		$event->preventDefault();
195
+	}
196
+
197
+	/**
198
+	 * handle findnearby action.
199
+	 *
200
+	 * @param Doku_Event $event
201
+	 *          event object
202
+	 * @param mixed $param
203
+	 *          associative array with keys
204
+	 *          'format'=> HTML | JSON
205
+	 */
206
+	public function findnearby(Doku_Event $event, $param): void
207
+	{
208
+		if ($event->data !== 'findnearby') {
209
+			return;
210
+		}
211
+		$event->preventDefault();
212
+		$results = array();
213
+		global $INPUT;
214
+		if ($helper = plugin_load('helper', 'spatialhelper_search')) {
215
+			if ($INPUT->has('lat') && $INPUT->has('lon')) {
216
+				$results = $helper->findNearbyLatLon($INPUT->param('lat'), $INPUT->param('lon'));
217
+			} elseif ($INPUT->has('geohash')) {
218
+				$results = $helper->findNearby($INPUT->str('geohash'));
219
+			} else {
220
+				$results = array(
221
+					'error' => hsc($this->getLang('invalidinput'))
222
+				);
223
+			}
224
+		}
225
+
226
+		$showMedia = $INPUT->bool('showMedia', true);
227
+
228
+		switch ($param['format']) {
229
+			case 'JSON' :
230
+				$this->printJSON($results);
231
+				break;
232
+			case 'HTML' :
233
+				// fall through to default
234
+			default :
235
+				$this->printHTML($results, $showMedia);
236
+				break;
237
+		}
238
+	}
239
+
240
+	/**
241
+	 * Print seachresults as HTML lists.
242
+	 *
243
+	 * @param array $searchresults
244
+	 */
245
+	private function printJSON(array $searchresults): void
246
+	{
247
+		require_once DOKU_INC . 'inc/JSON.php';
248
+		$json = new JSON();
249
+		header('Content-Type: application/json');
250
+		print $json->encode($searchresults);
251
+	}
252
+
253
+	/**
254
+	 * Print seachresults as HTML lists.
255
+	 *
256
+	 * @param array $searchresults
257
+	 * @param bool $showMedia
258
+	 */
259
+	private function printHTML(array $searchresults, bool $showMedia = true): void
260
+	{
261
+		$pages = (array)($searchresults ['pages']);
262
+		$media = (array)$searchresults ['media'];
263
+		$lat = (float)$searchresults ['lat'];
264
+		$lon = (float)$searchresults ['lon'];
265
+		$geohash = (string)$searchresults ['geohash'];
266
+
267
+		if (isset ($searchresults ['error'])) {
268
+			print '<div class="level1"><p>' . hsc($searchresults ['error']) . '</p></div>';
269
+			return;
270
+		}
271
+
272
+		// print a HTML list
273
+		print '<h1>' . $this->getLang('results_header') . '</h1>' . DOKU_LF;
274
+		print '<div class="level1">' . DOKU_LF;
275
+		if (!empty ($pages)) {
276
+			$pagelist = '<ol>' . DOKU_LF;
277
+			foreach ($pages as $page) {
278
+				$pagelist .= '<li>' . html_wikilink(
279
+						':' . $page ['id'], useHeading('navigation') ? null :
280
+						noNS($page ['id'])
281
+					) . ' (' . $this->getLang('results_distance_prefix')
282
+					. $page ['distance'] . '&nbsp;m) ' . $page ['description'] . '</li>' . DOKU_LF;
283
+			}
284
+			$pagelist .= '</ol>' . DOKU_LF;
285
+
286
+			print '<h2>' . $this->getLang('results_pages') . hsc(
287
+					' lat;lon: ' . $lat . ';' . $lon
288
+					. ' (geohash: ' . $geohash . ')'
289
+				) . '</h2>';
290
+			print '<div class="level2">' . DOKU_LF;
291
+			print $pagelist;
292
+			print '</div>' . DOKU_LF;
293
+		} else {
294
+			print '<p>' . hsc($this->getLang('nothingfound')) . '</p>';
295
+		}
296
+
297
+		if (!empty ($media) && $showMedia) {
298
+			$pagelist = '<ol>' . DOKU_LF;
299
+			foreach ($media as $m) {
300
+				$opts = array();
301
+				$link = ml($m ['id'], $opts, false, '&amp;', false);
302
+				$opts ['w'] = '100';
303
+				$src = ml($m ['id'], $opts);
304
+				$pagelist .= '<li><a href="' . $link . '"><img src="' . $src . '"></a> ('
305
+					. $this->getLang('results_distance_prefix') . $page ['distance'] . '&nbsp;m) ' . hsc($desc)
306
+					. '</li>' . DOKU_LF;
307
+			}
308
+			$pagelist .= '</ol>' . DOKU_LF;
309
+
310
+			print '<h2>' . $this->getLang('results_media') . hsc(
311
+					' lat;lon: ' . $lat . ';' . $lon
312
+					. ' (geohash: ' . $geohash . ')'
313
+				) . '</h2>' . DOKU_LF;
314
+			print '<div class="level2">' . DOKU_LF;
315
+			print $pagelist;
316
+			print '</div>' . DOKU_LF;
317
+		}
318
+		print '<p>' . $this->getLang('results_precision') . $searchresults ['precision'] . ' m. ';
319
+		if (strlen($geohash) > 1) {
320
+			$url = wl(
321
+				getID(), array(
322
+					'do' => 'findnearby',
323
+					'geohash' => substr($geohash, 0, -1)
324
+				)
325
+			);
326
+			print '<a href="' . $url . '" class="findnearby">' . $this->getLang('search_largerarea') . '</a>.</p>'
327
+				. DOKU_LF;
328
+		}
329
+		print '</div>' . DOKU_LF;
330
+	}
331
+
332
+	/**
333
+	 * add media to spatial index.
334
+	 *
335
+	 * @param Doku_Event $event
336
+	 * @param mixed $param
337
+	 */
338
+	public function handleMediaUploaded(Doku_Event $event, $param): void
339
+	{
340
+		// data[0] temporary file name (read from $_FILES)
341
+		// data[1] file name of the file being uploaded
342
+		// data[2] future directory id of the file being uploaded
343
+		// data[3] the mime type of the file being uploaded
344
+		// data[4] true if the uploaded file exists already
345
+		// data[5] (since 2011-02-06) the PHP function used to move the file to the correct location
346
+
347
+		Logger::getInstance(Logger::LOG_DEBUG)->log("handleMediaUploaded::event data", $event->data);
348
+
349
+		// check the list of mimetypes
350
+		// if it's a supported type call appropriate index function
351
+		if (substr_compare($event->data [3], 'image/jpeg', 0)) {
352
+			$indexer = plugin_load('helper', 'spatialhelper_index');
353
+			if ($indexer) {
354
+				$indexer->indexImage($event->data [2], $event->data [1]);
355
+			}
356
+		}
357
+		// TODO add image/tiff
358
+		// TODO kml, gpx, geojson...
359
+	}
360
+
361
+	/**
362
+	 * removes the media from the index.
363
+	 */
364
+	public function handleMediaDeleted(Doku_Event $event, $param): void
365
+	{
366
+		// data['id'] ID data['unl'] unlink return code
367
+		// data['del'] Namespace directory unlink return code
368
+		// data['name'] file name data['path'] full path to the file
369
+		// data['size'] file size
370
+
371
+		Logger::getInstance(Logger::LOG_DEBUG)->log("handleMediaDeleted::event data", $event->data);
372
+
373
+		// remove the media id from the index
374
+		$indexer = plugin_load('helper', 'spatialhelper_index');
375
+		if ($indexer) {
376
+			$indexer->deleteFromIndex('media__' . $event->data ['id']);
377
+		}
378
+	}
379
+
380
+	/**
381
+	 * add a link to the spatial sitemap files in the header.
382
+	 *
383
+	 * @param Doku_Event $event
384
+	 *          the DokuWiki event. $event->data is a two-dimensional
385
+	 *          array of all meta headers. The keys are meta, link and script.
386
+	 * @param mixed $param
387
+	 *
388
+	 * @see http://www.dokuwiki.org/devel:event:tpl_metaheader_output
389
+	 */
390
+	public function handleMetaheaderOutput(Doku_Event $event, $param): void
391
+	{
392
+		// TODO maybe test for exist
393
+		$event->data ["link"] [] = array(
394
+			"type" => "application/atom+xml",
395
+			"rel" => "alternate",
396
+			"href" => ml($this->getConf('media_georss')),
397
+			"title" => "Spatial ATOM Feed"
398
+		);
399
+		$event->data ["link"] [] = array(
400
+			"type" => "application/vnd.google-earth.kml+xml",
401
+			"rel" => "alternate",
402
+			"href" => ml($this->getConf('media_kml')),
403
+			"title" => "KML Sitemap"
404
+		);
405
+	}
406
+
407
+	/**
408
+	 * Calculate a new coordinate based on start, distance and bearing
409
+	 *
410
+	 * @param $start array
411
+	 *               - start coordinate as decimal lat/lon pair
412
+	 * @param $dist  float
413
+	 *               - distance in kilometers
414
+	 * @param $brng  float
415
+	 *               - bearing in degrees (compass direction)
416
+	 */
417
+	private function geoDestination(array $start, float $dist, float $brng): array
418
+	{
419
+		$lat1 = $this->toRad($start [0]);
420
+		$lon1 = $this->toRad($start [1]);
421
+		// http://en.wikipedia.org/wiki/Earth_radius
422
+		// average earth radius in km
423
+		$dist = $dist / 6371.01;
424
+		$brng = $this->toRad($brng);
425
+
426
+		$lon2 = $lon1 + atan2(sin($brng) * sin($dist) * cos($lat1), cos($dist) - sin($lat1) * sin($lat2));
427
+		$lon2 = fmod(($lon2 + 3 * M_PI), (2 * M_PI)) - M_PI;
428
+
429
+		return array(
430
+			$this->toDeg($lat2),
431
+			$this->toDeg($lon2)
432
+		);
433
+	}
434
+
435
+	private function toRad(float $deg): float
436
+	{
437
+		return $deg * M_PI / 180;
438
+	}
439
+
440
+	private function toDeg(float $rad): float
441
+	{
442
+		return $rad * 180 / M_PI;
443
+	}
444 444
 }
Please login to merge, or discard this patch.
syntax/findnearby.php 1 patch
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -23,105 +23,105 @@
 block discarded – undo
23 23
  */
24 24
 class syntax_plugin_spatialhelper_findnearby extends DokuWiki_Syntax_Plugin
25 25
 {
26
-    /**
27
-     *
28
-     * @see DokuWiki_Syntax_Plugin::getType()
29
-     */
30
-    public function getType(): string
31
-    {
32
-        return 'substition';
33
-    }
26
+	/**
27
+	 *
28
+	 * @see DokuWiki_Syntax_Plugin::getType()
29
+	 */
30
+	public function getType(): string
31
+	{
32
+		return 'substition';
33
+	}
34 34
 
35
-    /**
36
-     * Return 'normal' so this syntax can be rendered inline.
37
-     *
38
-     * @see DokuWiki_Syntax_Plugin::getPType()
39
-     */
40
-    public function getPType(): string
41
-    {
42
-        return 'normal';
43
-    }
35
+	/**
36
+	 * Return 'normal' so this syntax can be rendered inline.
37
+	 *
38
+	 * @see DokuWiki_Syntax_Plugin::getPType()
39
+	 */
40
+	public function getPType(): string
41
+	{
42
+		return 'normal';
43
+	}
44 44
 
45
-    /**
46
-     *
47
-     * @see Doku_Parser_Mode::getSort()
48
-     */
49
-    public function getSort(): int
50
-    {
51
-        return 307;
52
-    }
45
+	/**
46
+	 *
47
+	 * @see Doku_Parser_Mode::getSort()
48
+	 */
49
+	public function getSort(): int
50
+	{
51
+		return 307;
52
+	}
53 53
 
54
-    /**
55
-     * define our special pattern: {{findnearby>Some linkt text or nothing}}.
56
-     *
57
-     * @see Doku_Parser_Mode::connectTo()
58
-     */
59
-    public function connectTo($mode): void
60
-    {
61
-        $this->Lexer->addSpecialPattern(
62
-            '\{\{findnearby>.*?\}\}',
63
-            $mode,
64
-            'plugin_spatialhelper_findnearby'
65
-        );
66
-    }
54
+	/**
55
+	 * define our special pattern: {{findnearby>Some linkt text or nothing}}.
56
+	 *
57
+	 * @see Doku_Parser_Mode::connectTo()
58
+	 */
59
+	public function connectTo($mode): void
60
+	{
61
+		$this->Lexer->addSpecialPattern(
62
+			'\{\{findnearby>.*?\}\}',
63
+			$mode,
64
+			'plugin_spatialhelper_findnearby'
65
+		);
66
+	}
67 67
 
68
-    /**
69
-     * look up the page's geo metadata and pass that on to render.
70
-     *
71
-     * @param string $match The text matched by the patterns
72
-     * @param int $state The lexer state for the match
73
-     * @param int $pos The character position of the matched text
74
-     * @param Doku_Handler $handler The Doku_Handler object
75
-     * @return  bool|array Return an array with all data you want to use in render, false don't add an instruction
76
-     *
77
-     * @see DokuWiki_Syntax_Plugin::handle()
78
-     */
79
-    public function handle($match, $state, $pos, Doku_Handler $handler)
80
-    {
81
-        $data = array();
82
-        $data [0] = trim(substr($match, strlen('{{findnearby>'), -2));
83
-        if (strlen($data [0]) < 1) {
84
-            $data [0] = $this->getLang('search_findnearby');
85
-        }
86
-        $meta = p_get_metadata(getID(), 'geo');
87
-        if ($meta) {
88
-            if ($meta ['lat'] && $meta ['lon']) {
89
-                $data [1] = array(
90
-                    'do' => 'findnearby',
91
-                    'lat' => $meta ['lat'],
92
-                    'lon' => $meta ['lon']
93
-                );
94
-            } elseif ($meta ['geohash']) {
95
-                $data [1] = array(
96
-                    'do' => 'findnearby',
97
-                    'geohash' => $meta ['geohash']
98
-                );
99
-            }
100
-            return $data;
101
-        }
102
-        return false;
103
-    }
68
+	/**
69
+	 * look up the page's geo metadata and pass that on to render.
70
+	 *
71
+	 * @param string $match The text matched by the patterns
72
+	 * @param int $state The lexer state for the match
73
+	 * @param int $pos The character position of the matched text
74
+	 * @param Doku_Handler $handler The Doku_Handler object
75
+	 * @return  bool|array Return an array with all data you want to use in render, false don't add an instruction
76
+	 *
77
+	 * @see DokuWiki_Syntax_Plugin::handle()
78
+	 */
79
+	public function handle($match, $state, $pos, Doku_Handler $handler)
80
+	{
81
+		$data = array();
82
+		$data [0] = trim(substr($match, strlen('{{findnearby>'), -2));
83
+		if (strlen($data [0]) < 1) {
84
+			$data [0] = $this->getLang('search_findnearby');
85
+		}
86
+		$meta = p_get_metadata(getID(), 'geo');
87
+		if ($meta) {
88
+			if ($meta ['lat'] && $meta ['lon']) {
89
+				$data [1] = array(
90
+					'do' => 'findnearby',
91
+					'lat' => $meta ['lat'],
92
+					'lon' => $meta ['lon']
93
+				);
94
+			} elseif ($meta ['geohash']) {
95
+				$data [1] = array(
96
+					'do' => 'findnearby',
97
+					'geohash' => $meta ['geohash']
98
+				);
99
+			}
100
+			return $data;
101
+		}
102
+		return false;
103
+	}
104 104
 
105
-    /**
106
-     * Render a link to a search page.
107
-     *
108
-     * @see DokuWiki_Syntax_Plugin::render()
109
-     */
110
-    public function render($format, Doku_Renderer $renderer, $data): bool
111
-    {
112
-        if ($data === false) {
113
-            return false;
114
-        }
105
+	/**
106
+	 * Render a link to a search page.
107
+	 *
108
+	 * @see DokuWiki_Syntax_Plugin::render()
109
+	 */
110
+	public function render($format, Doku_Renderer $renderer, $data): bool
111
+	{
112
+		if ($data === false) {
113
+			return false;
114
+		}
115 115
 
116
-        if ($format === 'xhtml') {
117
-            $renderer->doc .= '<a href="' . wl(getID(), $data [1]) . '" class="findnearby">' . hsc($data [0]) . '</a>';
118
-            return true;
119
-        } elseif ($format === 'metadata') {
120
-            return false;
121
-        } elseif ($format === 'odt') {
122
-            // don't render anything in ODT
123
-            return false;
124
-        }
125
-        return false;
126
-    }
116
+		if ($format === 'xhtml') {
117
+			$renderer->doc .= '<a href="' . wl(getID(), $data [1]) . '" class="findnearby">' . hsc($data [0]) . '</a>';
118
+			return true;
119
+		} elseif ($format === 'metadata') {
120
+			return false;
121
+		} elseif ($format === 'odt') {
122
+			// don't render anything in ODT
123
+			return false;
124
+		}
125
+		return false;
126
+	}
127 127
 }
Please login to merge, or discard this patch.
helper/search.php 2 patches
Indentation   +168 added lines, -168 removed lines patch added patch discarded remove patch
@@ -23,184 +23,184 @@
 block discarded – undo
23 23
  */
24 24
 class helper_plugin_spatialhelper_search extends DokuWiki_Plugin
25 25
 {
26
-    /**
27
-     * spatial index.
28
-     *
29
-     * @var array
30
-     */
31
-    protected $spatial_idx = array();
32
-    /**
33
-     * handle to the geoPHP plugin.
34
-     */
35
-    protected $geophp;
36
-    /**
37
-     * Precision, Distance of Adjacent Cell in Meters.
38
-     *
39
-     * @see https://stackoverflow.com/questions/13836416/geohash-and-max-distance
40
-     *
41
-     * @var float
42
-     */
43
-    private $precision = array(
44
-        5003530,
45
-        625441,
46
-        123264,
47
-        19545,
48
-        3803,
49
-        610,
50
-        118,
51
-        19,
52
-        3.7,
53
-        0.6
54
-    );
26
+	/**
27
+	 * spatial index.
28
+	 *
29
+	 * @var array
30
+	 */
31
+	protected $spatial_idx = array();
32
+	/**
33
+	 * handle to the geoPHP plugin.
34
+	 */
35
+	protected $geophp;
36
+	/**
37
+	 * Precision, Distance of Adjacent Cell in Meters.
38
+	 *
39
+	 * @see https://stackoverflow.com/questions/13836416/geohash-and-max-distance
40
+	 *
41
+	 * @var float
42
+	 */
43
+	private $precision = array(
44
+		5003530,
45
+		625441,
46
+		123264,
47
+		19545,
48
+		3803,
49
+		610,
50
+		118,
51
+		19,
52
+		3.7,
53
+		0.6
54
+	);
55 55
 
56
-    /**
57
-     * constructor; initialize/load spatial index.
58
-     */
59
-    public function __construct()
60
-    {
61
-        // parent::__construct ();
62
-        global $conf;
56
+	/**
57
+	 * constructor; initialize/load spatial index.
58
+	 */
59
+	public function __construct()
60
+	{
61
+		// parent::__construct ();
62
+		global $conf;
63 63
 
64
-        if (!$geophp = plugin_load('helper', 'geophp')) {
65
-            $message = 'helper_plugin_spatialhelper_search::spatialhelper_search: geophp plugin is not available.';
66
-            msg($message, -1);
67
-        }
64
+		if (!$geophp = plugin_load('helper', 'geophp')) {
65
+			$message = 'helper_plugin_spatialhelper_search::spatialhelper_search: geophp plugin is not available.';
66
+			msg($message, -1);
67
+		}
68 68
 
69
-        $idx_dir = $conf ['indexdir'];
70
-        if (!@file_exists($idx_dir . '/spatial.idx')) {
71
-            $indexer = plugin_load('helper', 'spatialhelper_index');
72
-        }
69
+		$idx_dir = $conf ['indexdir'];
70
+		if (!@file_exists($idx_dir . '/spatial.idx')) {
71
+			$indexer = plugin_load('helper', 'spatialhelper_index');
72
+		}
73 73
 
74
-        $this->spatial_idx = unserialize(io_readFile($fn = $idx_dir . '/spatial.idx', false));
75
-    }
74
+		$this->spatial_idx = unserialize(io_readFile($fn = $idx_dir . '/spatial.idx', false));
75
+	}
76 76
 
77
-    /**
78
-     * Find locations based on the coordinate pair.
79
-     *
80
-     * @param float $lat
81
-     *          The y coordinate (or latitude)
82
-     * @param float $lon
83
-     *          The x coordinate (or longitude)
84
-     */
85
-    public function findNearbyLatLon(float $lat, float $lon): array
86
-    {
87
-        $geometry = new Point($lon, $lat);
88
-        return $this->findNearby($geometry->out('geohash'), $geometry);
89
-    }
77
+	/**
78
+	 * Find locations based on the coordinate pair.
79
+	 *
80
+	 * @param float $lat
81
+	 *          The y coordinate (or latitude)
82
+	 * @param float $lon
83
+	 *          The x coordinate (or longitude)
84
+	 */
85
+	public function findNearbyLatLon(float $lat, float $lon): array
86
+	{
87
+		$geometry = new Point($lon, $lat);
88
+		return $this->findNearby($geometry->out('geohash'), $geometry);
89
+	}
90 90
 
91
-    /**
92
-     * finds nearby elements in the index based on the geohash.
93
-     * returns a list of documents and the bunding box.
94
-     *
95
-     * @param string $geohash
96
-     * @param Point $p
97
-     *          optional point
98
-     * @return array of ...
99
-     */
100
-    public function findNearby(string $geohash, Point $p = null): array
101
-    {
102
-        $_geohashClass = new Geohash();
103
-        if (!$p) {
104
-            $decodedPoint = $_geohashClass->read($geohash);
105
-        } else {
106
-            $decodedPoint = $p;
107
-        }
91
+	/**
92
+	 * finds nearby elements in the index based on the geohash.
93
+	 * returns a list of documents and the bunding box.
94
+	 *
95
+	 * @param string $geohash
96
+	 * @param Point $p
97
+	 *          optional point
98
+	 * @return array of ...
99
+	 */
100
+	public function findNearby(string $geohash, Point $p = null): array
101
+	{
102
+		$_geohashClass = new Geohash();
103
+		if (!$p) {
104
+			$decodedPoint = $_geohashClass->read($geohash);
105
+		} else {
106
+			$decodedPoint = $p;
107
+		}
108 108
 
109
-        // find adjacent blocks
110
-        $adjacent = array();
111
-        $adjacent ['center'] = $geohash;
112
-        $adjacent ['top'] = $_geohashClass->adjacent($adjacent ['center'], 'top');
113
-        $adjacent ['bottom'] = $_geohashClass->adjacent($adjacent ['center'], 'bottom');
114
-        $adjacent ['right'] = $_geohashClass->adjacent($adjacent ['center'], 'right');
115
-        $adjacent ['left'] = $_geohashClass->adjacent($adjacent ['center'], 'left');
116
-        $adjacent ['topleft'] = $_geohashClass->adjacent($adjacent ['left'], 'top');
117
-        $adjacent ['topright'] = $_geohashClass->adjacent($adjacent ['right'], 'top');
118
-        $adjacent ['bottomright'] = $_geohashClass->adjacent($adjacent ['right'], 'bottom');
119
-        $adjacent ['bottomleft'] = $_geohashClass->adjacent($adjacent ['left'], 'bottom');
120
-        Logger::getInstance(Logger::LOG_DEBUG)->log("adjacent geo hashes", $adjacent);
109
+		// find adjacent blocks
110
+		$adjacent = array();
111
+		$adjacent ['center'] = $geohash;
112
+		$adjacent ['top'] = $_geohashClass->adjacent($adjacent ['center'], 'top');
113
+		$adjacent ['bottom'] = $_geohashClass->adjacent($adjacent ['center'], 'bottom');
114
+		$adjacent ['right'] = $_geohashClass->adjacent($adjacent ['center'], 'right');
115
+		$adjacent ['left'] = $_geohashClass->adjacent($adjacent ['center'], 'left');
116
+		$adjacent ['topleft'] = $_geohashClass->adjacent($adjacent ['left'], 'top');
117
+		$adjacent ['topright'] = $_geohashClass->adjacent($adjacent ['right'], 'top');
118
+		$adjacent ['bottomright'] = $_geohashClass->adjacent($adjacent ['right'], 'bottom');
119
+		$adjacent ['bottomleft'] = $_geohashClass->adjacent($adjacent ['left'], 'bottom');
120
+		Logger::getInstance(Logger::LOG_DEBUG)->log("adjacent geo hashes", $adjacent);
121 121
 
122
-        // find all the pages in the index that overlap with the adjacent hashes
123
-        $docIds = array();
124
-        foreach ($adjacent as $adjHash) {
125
-            if (is_array($this->spatial_idx)) {
126
-                foreach ($this->spatial_idx as $_geohash => $_docIds) {
127
-                    if (strpos($_geohash, $adjHash) !== false) {
128
-                        // Logger::getInstance(Logger::LOG_DEBUG)
129
-                        //      ->log("Found adjacent geo hash: $adjHash in $_geohash" );
130
-                        // if $adjHash similar to geohash
131
-                        $docIds = array_merge($docIds, $_docIds);
132
-                    }
133
-                }
134
-            }
135
-        }
136
-        $docIds = array_unique($docIds);
137
-        Logger::getInstance(Logger::LOG_DEBUG)->log("found docIDs", $docIds);
122
+		// find all the pages in the index that overlap with the adjacent hashes
123
+		$docIds = array();
124
+		foreach ($adjacent as $adjHash) {
125
+			if (is_array($this->spatial_idx)) {
126
+				foreach ($this->spatial_idx as $_geohash => $_docIds) {
127
+					if (strpos($_geohash, $adjHash) !== false) {
128
+						// Logger::getInstance(Logger::LOG_DEBUG)
129
+						//      ->log("Found adjacent geo hash: $adjHash in $_geohash" );
130
+						// if $adjHash similar to geohash
131
+						$docIds = array_merge($docIds, $_docIds);
132
+					}
133
+				}
134
+			}
135
+		}
136
+		$docIds = array_unique($docIds);
137
+		Logger::getInstance(Logger::LOG_DEBUG)->log("found docIDs", $docIds);
138 138
 
139
-        // create associative array of pages + calculate distance
140
-        $pages = array();
141
-        $media = array();
142
-        $indexer = plugin_load('helper', 'spatialhelper_index');
139
+		// create associative array of pages + calculate distance
140
+		$pages = array();
141
+		$media = array();
142
+		$indexer = plugin_load('helper', 'spatialhelper_index');
143 143
 
144
-        foreach ($docIds as $id) {
145
-            if (strpos($id, 'media__', 0) === 0) {
146
-                $id = substr($id, strlen('media__'));
147
-                if (auth_quickaclcheck($id) >= /*AUTH_READ*/ 1) {
148
-                    $point = $indexer->getCoordsFromExif($id);
149
-                    $line = new LineString(
150
-                        [
151
-                            $decodedPoint,
152
-                            $point
153
-                        ]
154
-                    );
155
-                    $media [] = array(
156
-                        'id' => $id,
157
-                        'distance' => (int)($line->greatCircleLength()),
158
-                        'lat' => $point->y(),
159
-                        'lon' => $point->x()
160
-                        // optionally add other meta such as tag, description...
161
-                    );
162
-                }
163
-            } else {
164
-                if (auth_quickaclcheck($id) >= /*AUTH_READ*/ 1) {
165
-                    $geotags = p_get_metadata($id, 'geo');
166
-                    $point = new Point($geotags ['lon'], $geotags ['lat']);
167
-                    $line = new LineString(
168
-                        [
169
-                            $decodedPoint,
170
-                            $point
171
-                        ]
172
-                    );
173
-                    $pages [] = array(
174
-                        'id' => $id,
175
-                        'distance' => (int)($line->greatCircleLength()),
176
-                        'description' => p_get_metadata($id, 'description')['abstract'],
177
-                        'lat' => $geotags ['lat'],
178
-                        'lon' => $geotags ['lon']
179
-                        // optionally add other meta such as tag...
180
-                    );
181
-                }
182
-            }
183
-        }
144
+		foreach ($docIds as $id) {
145
+			if (strpos($id, 'media__', 0) === 0) {
146
+				$id = substr($id, strlen('media__'));
147
+				if (auth_quickaclcheck($id) >= /*AUTH_READ*/ 1) {
148
+					$point = $indexer->getCoordsFromExif($id);
149
+					$line = new LineString(
150
+						[
151
+							$decodedPoint,
152
+							$point
153
+						]
154
+					);
155
+					$media [] = array(
156
+						'id' => $id,
157
+						'distance' => (int)($line->greatCircleLength()),
158
+						'lat' => $point->y(),
159
+						'lon' => $point->x()
160
+						// optionally add other meta such as tag, description...
161
+					);
162
+				}
163
+			} else {
164
+				if (auth_quickaclcheck($id) >= /*AUTH_READ*/ 1) {
165
+					$geotags = p_get_metadata($id, 'geo');
166
+					$point = new Point($geotags ['lon'], $geotags ['lat']);
167
+					$line = new LineString(
168
+						[
169
+							$decodedPoint,
170
+							$point
171
+						]
172
+					);
173
+					$pages [] = array(
174
+						'id' => $id,
175
+						'distance' => (int)($line->greatCircleLength()),
176
+						'description' => p_get_metadata($id, 'description')['abstract'],
177
+						'lat' => $geotags ['lat'],
178
+						'lon' => $geotags ['lon']
179
+						// optionally add other meta such as tag...
180
+					);
181
+				}
182
+			}
183
+		}
184 184
 
185
-        // sort all the pages/media using distance
186
-        usort(
187
-            $pages, static function ($a, $b) {
188
-            return strnatcmp($a ['distance'], $b ['distance']);
189
-        }
190
-        );
191
-        usort(
192
-            $media, static function ($a, $b) {
193
-            return strnatcmp($a ['distance'], $b ['distance']);
194
-        }
195
-        );
185
+		// sort all the pages/media using distance
186
+		usort(
187
+			$pages, static function ($a, $b) {
188
+			return strnatcmp($a ['distance'], $b ['distance']);
189
+		}
190
+		);
191
+		usort(
192
+			$media, static function ($a, $b) {
193
+			return strnatcmp($a ['distance'], $b ['distance']);
194
+		}
195
+		);
196 196
 
197
-        return array(
198
-            'pages' => $pages,
199
-            'media' => $media,
200
-            'lat' => $decodedPoint->y(),
201
-            'lon' => $decodedPoint->x(),
202
-            'geohash' => $geohash,
203
-            'precision' => $this->precision [strlen($geohash)]
204
-        );
205
-    }
197
+		return array(
198
+			'pages' => $pages,
199
+			'media' => $media,
200
+			'lat' => $decodedPoint->y(),
201
+			'lon' => $decodedPoint->x(),
202
+			'geohash' => $geohash,
203
+			'precision' => $this->precision [strlen($geohash)]
204
+		);
205
+	}
206 206
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
                     );
155 155
                     $media [] = array(
156 156
                         'id' => $id,
157
-                        'distance' => (int)($line->greatCircleLength()),
157
+                        'distance' => ( int ) ($line->greatCircleLength()),
158 158
                         'lat' => $point->y(),
159 159
                         'lon' => $point->x()
160 160
                         // optionally add other meta such as tag, description...
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
                     );
173 173
                     $pages [] = array(
174 174
                         'id' => $id,
175
-                        'distance' => (int)($line->greatCircleLength()),
175
+                        'distance' => ( int ) ($line->greatCircleLength()),
176 176
                         'description' => p_get_metadata($id, 'description')['abstract'],
177 177
                         'lat' => $geotags ['lat'],
178 178
                         'lon' => $geotags ['lon']
@@ -184,12 +184,12 @@  discard block
 block discarded – undo
184 184
 
185 185
         // sort all the pages/media using distance
186 186
         usort(
187
-            $pages, static function ($a, $b) {
187
+            $pages, static function($a, $b) {
188 188
             return strnatcmp($a ['distance'], $b ['distance']);
189 189
         }
190 190
         );
191 191
         usort(
192
-            $media, static function ($a, $b) {
192
+            $media, static function($a, $b) {
193 193
             return strnatcmp($a ['distance'], $b ['distance']);
194 194
         }
195 195
         );
Please login to merge, or discard this patch.
helper/index.php 2 patches
Indentation   +279 added lines, -279 removed lines patch added patch discarded remove patch
@@ -25,304 +25,304 @@
 block discarded – undo
25 25
  */
26 26
 class helper_plugin_spatialhelper_index extends DokuWiki_Plugin
27 27
 {
28
-    /**
29
-     * directory for index files.
30
-     *
31
-     * @var string
32
-     */
33
-    protected $idx_dir = '';
28
+	/**
29
+	 * directory for index files.
30
+	 *
31
+	 * @var string
32
+	 */
33
+	protected $idx_dir = '';
34 34
 
35
-    /**
36
-     * spatial index, well lookup list/array so we can do spatial queries.
37
-     * entries should be: array("geohash" => {"id1","id3",})
38
-     *
39
-     * @var array
40
-     */
41
-    protected $spatial_idx = array();
35
+	/**
36
+	 * spatial index, well lookup list/array so we can do spatial queries.
37
+	 * entries should be: array("geohash" => {"id1","id3",})
38
+	 *
39
+	 * @var array
40
+	 */
41
+	protected $spatial_idx = array();
42 42
 
43
-    /**
44
-     * handle to the geoPHP plugin.
45
-     */
46
-    protected $geophp;
43
+	/**
44
+	 * handle to the geoPHP plugin.
45
+	 */
46
+	protected $geophp;
47 47
 
48
-    /**
49
-     * Constructor, initialises the spatial index.
50
-     */
51
-    public function __construct()
52
-    {
53
-        if (!$geophp = plugin_load('helper', 'geophp')) {
54
-            $message = 'helper_plugin_spatialhelper_index::spatialhelper_index: geophp plugin is not available.';
55
-            msg($message, -1);
56
-        }
48
+	/**
49
+	 * Constructor, initialises the spatial index.
50
+	 */
51
+	public function __construct()
52
+	{
53
+		if (!$geophp = plugin_load('helper', 'geophp')) {
54
+			$message = 'helper_plugin_spatialhelper_index::spatialhelper_index: geophp plugin is not available.';
55
+			msg($message, -1);
56
+		}
57 57
 
58
-        global $conf;
59
-        $this->idx_dir = $conf ['indexdir'];
60
-        // test if there is a spatialindex, if not build one for the wiki
61
-        if (!@file_exists($this->idx_dir . '/spatial.idx')) {
62
-            // creates and stores the index
63
-            $this->generateSpatialIndex();
64
-        } else {
65
-            $this->spatial_idx = unserialize(io_readFile($this->idx_dir . '/spatial.idx', false));
66
-            Logger::getInstance(Logger::LOG_DEBUG)->log('done loading spatial index', $this->spatial_idx);
67
-        }
68
-    }
58
+		global $conf;
59
+		$this->idx_dir = $conf ['indexdir'];
60
+		// test if there is a spatialindex, if not build one for the wiki
61
+		if (!@file_exists($this->idx_dir . '/spatial.idx')) {
62
+			// creates and stores the index
63
+			$this->generateSpatialIndex();
64
+		} else {
65
+			$this->spatial_idx = unserialize(io_readFile($this->idx_dir . '/spatial.idx', false));
66
+			Logger::getInstance(Logger::LOG_DEBUG)->log('done loading spatial index', $this->spatial_idx);
67
+		}
68
+	}
69 69
 
70
-    /**
71
-     * (re-)Generates the spatial index by running through all the pages in the wiki.
72
-     *
73
-     * @todo add an option to erase the old index
74
-     */
75
-    public function generateSpatialIndex(): bool
76
-    {
77
-        global $conf;
78
-        require_once(DOKU_INC . 'inc/search.php');
79
-        $pages = array();
80
-        search($pages, $conf ['datadir'], 'search_allpages', array());
81
-        foreach ($pages as $page) {
82
-            $this->updateSpatialIndex($page ['id']);
83
-        }
84
-        // media
85
-        $media = array();
86
-        search($media, $conf ['mediadir'], 'search_media', array());
87
-        foreach ($media as $medium) {
88
-            if ($medium ['isimg']) {
89
-                $this->indexImage($medium);
90
-            }
91
-        }
92
-        return true;
93
-    }
70
+	/**
71
+	 * (re-)Generates the spatial index by running through all the pages in the wiki.
72
+	 *
73
+	 * @todo add an option to erase the old index
74
+	 */
75
+	public function generateSpatialIndex(): bool
76
+	{
77
+		global $conf;
78
+		require_once(DOKU_INC . 'inc/search.php');
79
+		$pages = array();
80
+		search($pages, $conf ['datadir'], 'search_allpages', array());
81
+		foreach ($pages as $page) {
82
+			$this->updateSpatialIndex($page ['id']);
83
+		}
84
+		// media
85
+		$media = array();
86
+		search($media, $conf ['mediadir'], 'search_media', array());
87
+		foreach ($media as $medium) {
88
+			if ($medium ['isimg']) {
89
+				$this->indexImage($medium);
90
+			}
91
+		}
92
+		return true;
93
+	}
94 94
 
95
-    /**
96
-     * Update the spatial index for the page.
97
-     *
98
-     * @param string $id
99
-     *          the document ID
100
-     * @throws Exception
101
-     */
102
-    public function updateSpatialIndex(string $id): bool
103
-    {
104
-        $geotags = p_get_metadata($id, 'geo');
105
-        if (empty ($geotags)) {
106
-            return false;
107
-        }
108
-        if (empty ($geotags ['lon']) || empty ($geotags ['lat'])) {
109
-            return false;
110
-        }
111
-        Logger::getInstance(Logger::LOG_DEBUG)->log("Geo metadata found for page $id", $geotags);
112
-        $geometry = new Point($geotags ['lon'], $geotags ['lat']);
113
-        $geohash = $geometry->out('geohash');
114
-        Logger::getInstance(Logger::LOG_DEBUG)->log("Update index for geohash: $geohash");
115
-        return $this->addToIndex($geohash, $id);
116
-    }
95
+	/**
96
+	 * Update the spatial index for the page.
97
+	 *
98
+	 * @param string $id
99
+	 *          the document ID
100
+	 * @throws Exception
101
+	 */
102
+	public function updateSpatialIndex(string $id): bool
103
+	{
104
+		$geotags = p_get_metadata($id, 'geo');
105
+		if (empty ($geotags)) {
106
+			return false;
107
+		}
108
+		if (empty ($geotags ['lon']) || empty ($geotags ['lat'])) {
109
+			return false;
110
+		}
111
+		Logger::getInstance(Logger::LOG_DEBUG)->log("Geo metadata found for page $id", $geotags);
112
+		$geometry = new Point($geotags ['lon'], $geotags ['lat']);
113
+		$geohash = $geometry->out('geohash');
114
+		Logger::getInstance(Logger::LOG_DEBUG)->log("Update index for geohash: $geohash");
115
+		return $this->addToIndex($geohash, $id);
116
+	}
117 117
 
118
-    /**
119
-     * Store the hash/id entry in the index.
120
-     *
121
-     * @param string $geohash
122
-     * @param string $id
123
-     *          page or media id
124
-     * @return bool true when succesful
125
-     */
126
-    private function addToIndex(string $geohash, string $id): bool
127
-    {
128
-        $pageIds = array();
129
-        // check index for key/geohash
130
-        if (!array_key_exists($geohash, $this->spatial_idx)) {
131
-            Logger::getInstance(Logger::LOG_DEBUG)->log("Geohash $geohash not in index, just add $id.");
132
-            $pageIds [] = $id;
133
-        } else {
134
-            Logger::getInstance(Logger::LOG_DEBUG)->log('Geohash for document is in index, find it.');
135
-            // check the index for document
136
-            $knownHashes = $this->findHashesForId($id, $this->spatial_idx);
137
-            if (empty ($knownHashes)) {
138
-                Logger::getInstance(Logger::LOG_DEBUG)->log(
139
-                    "No index record found for document $id, just add"
140
-                );
141
-                $pageIds = $this->spatial_idx [$geohash];
142
-                $pageIds [] = $id;
143
-            }
144
-            // TODO shortcut, need to make sure there is only one element, if not the index is corrupt
145
-            $knownHash = $knownHashes [0];
118
+	/**
119
+	 * Store the hash/id entry in the index.
120
+	 *
121
+	 * @param string $geohash
122
+	 * @param string $id
123
+	 *          page or media id
124
+	 * @return bool true when succesful
125
+	 */
126
+	private function addToIndex(string $geohash, string $id): bool
127
+	{
128
+		$pageIds = array();
129
+		// check index for key/geohash
130
+		if (!array_key_exists($geohash, $this->spatial_idx)) {
131
+			Logger::getInstance(Logger::LOG_DEBUG)->log("Geohash $geohash not in index, just add $id.");
132
+			$pageIds [] = $id;
133
+		} else {
134
+			Logger::getInstance(Logger::LOG_DEBUG)->log('Geohash for document is in index, find it.');
135
+			// check the index for document
136
+			$knownHashes = $this->findHashesForId($id, $this->spatial_idx);
137
+			if (empty ($knownHashes)) {
138
+				Logger::getInstance(Logger::LOG_DEBUG)->log(
139
+					"No index record found for document $id, just add"
140
+				);
141
+				$pageIds = $this->spatial_idx [$geohash];
142
+				$pageIds [] = $id;
143
+			}
144
+			// TODO shortcut, need to make sure there is only one element, if not the index is corrupt
145
+			$knownHash = $knownHashes [0];
146 146
 
147
-            if ($knownHash === $geohash) {
148
-                Logger::getInstance(Logger::LOG_DEBUG)->log(
149
-                    "Document $id was found in index and has the same geohash, nothing to do."
150
-                );
151
-                return true;
152
-            }
147
+			if ($knownHash === $geohash) {
148
+				Logger::getInstance(Logger::LOG_DEBUG)->log(
149
+					"Document $id was found in index and has the same geohash, nothing to do."
150
+				);
151
+				return true;
152
+			}
153 153
 
154
-            if (!empty ($knownHash)) {
155
-                Logger::getInstance(Logger::LOG_DEBUG)->log(
156
-                    "Document/media $id was found in index but has different geohash (it moved)."
157
-                );
158
-                $knownIds = $this->spatial_idx [$knownHash];
159
-                Logger::getInstance(Logger::LOG_DEBUG)->log("Known id's for this hash", $knownIds);
160
-                // remove it from the old geohash element
161
-                $i = array_search($id, $knownIds);
162
-                Logger::getInstance(Logger::LOG_DEBUG)->log('Unsetting:' . $knownIds [$i]);
163
-                unset ($knownIds [$i]);
164
-                $this->spatial_idx [$knownHash] = $knownIds;
165
-                // set on new geohash element
166
-                $pageIds = $this->spatial_idx [$geohash];
167
-                $pageIds [] = $id;
168
-            }
169
-        }
170
-        // store and save
171
-        $this->spatial_idx [$geohash] = $pageIds;
172
-        return $this->saveIndex();
173
-    }
154
+			if (!empty ($knownHash)) {
155
+				Logger::getInstance(Logger::LOG_DEBUG)->log(
156
+					"Document/media $id was found in index but has different geohash (it moved)."
157
+				);
158
+				$knownIds = $this->spatial_idx [$knownHash];
159
+				Logger::getInstance(Logger::LOG_DEBUG)->log("Known id's for this hash", $knownIds);
160
+				// remove it from the old geohash element
161
+				$i = array_search($id, $knownIds);
162
+				Logger::getInstance(Logger::LOG_DEBUG)->log('Unsetting:' . $knownIds [$i]);
163
+				unset ($knownIds [$i]);
164
+				$this->spatial_idx [$knownHash] = $knownIds;
165
+				// set on new geohash element
166
+				$pageIds = $this->spatial_idx [$geohash];
167
+				$pageIds [] = $id;
168
+			}
169
+		}
170
+		// store and save
171
+		$this->spatial_idx [$geohash] = $pageIds;
172
+		return $this->saveIndex();
173
+	}
174 174
 
175
-    /**
176
-     * Looks up the geohash(es) for the document in the index.
177
-     *
178
-     * @param String $id
179
-     *          document ID
180
-     * @param array $index
181
-     *          spatial index
182
-     */
183
-    public function findHashesForId(string $id, array $index): array
184
-    {
185
-        $hashes = array();
186
-        foreach ($index as $hash => $docIds) {
187
-            if (in_array($id, $docIds, false)) {
188
-                $hashes [] = $hash;
189
-            }
190
-        }
191
-        Logger::getInstance(Logger::LOG_DEBUG)->log(
192
-            "Found the following hashes for $id (should only be 1)",
193
-            $hashes
194
-        );
195
-        return $hashes;
196
-    }
175
+	/**
176
+	 * Looks up the geohash(es) for the document in the index.
177
+	 *
178
+	 * @param String $id
179
+	 *          document ID
180
+	 * @param array $index
181
+	 *          spatial index
182
+	 */
183
+	public function findHashesForId(string $id, array $index): array
184
+	{
185
+		$hashes = array();
186
+		foreach ($index as $hash => $docIds) {
187
+			if (in_array($id, $docIds, false)) {
188
+				$hashes [] = $hash;
189
+			}
190
+		}
191
+		Logger::getInstance(Logger::LOG_DEBUG)->log(
192
+			"Found the following hashes for $id (should only be 1)",
193
+			$hashes
194
+		);
195
+		return $hashes;
196
+	}
197 197
 
198
-    /**
199
-     * Save spatial index.
200
-     */
201
-    private function saveIndex(): bool
202
-    {
203
-        return io_saveFile($this->idx_dir . '/spatial.idx', serialize($this->spatial_idx));
204
-    }
198
+	/**
199
+	 * Save spatial index.
200
+	 */
201
+	private function saveIndex(): bool
202
+	{
203
+		return io_saveFile($this->idx_dir . '/spatial.idx', serialize($this->spatial_idx));
204
+	}
205 205
 
206
-    /**
207
-     * Add an index entry for this file having EXIF / IPTC data.
208
-     *
209
-     * @param $img
210
-     *          a Dokuwiki image
211
-     * @return bool true when image was succesfully added to the index.
212
-     * @throws Exception
213
-     * @see http://www.php.net/manual/en/function.iptcparse.php
214
-     * @see http://php.net/manual/en/function.exif-read-data.php
215
-     *
216
-     */
217
-    public function indexImage($img): bool
218
-    {
219
-        // test for supported files (jpeg only)
220
-        if (
221
-            (substr($img ['file'], -strlen('.jpg')) !== '.jpg') &&
222
-            (substr($img ['file'], -strlen('.jpeg')) !== '.jpeg')) {
223
-            return false;
224
-        }
206
+	/**
207
+	 * Add an index entry for this file having EXIF / IPTC data.
208
+	 *
209
+	 * @param $img
210
+	 *          a Dokuwiki image
211
+	 * @return bool true when image was succesfully added to the index.
212
+	 * @throws Exception
213
+	 * @see http://www.php.net/manual/en/function.iptcparse.php
214
+	 * @see http://php.net/manual/en/function.exif-read-data.php
215
+	 *
216
+	 */
217
+	public function indexImage($img): bool
218
+	{
219
+		// test for supported files (jpeg only)
220
+		if (
221
+			(substr($img ['file'], -strlen('.jpg')) !== '.jpg') &&
222
+			(substr($img ['file'], -strlen('.jpeg')) !== '.jpeg')) {
223
+			return false;
224
+		}
225 225
 
226
-        $geometry = $this->getCoordsFromExif($img ['id']);
227
-        if (!$geometry) {
228
-            return false;
229
-        }
230
-        $geohash = $geometry->out('geohash');
231
-        // TODO truncate the geohash to something reasonable, otherwise they are
232
-        // useless as an indexing mechanism eg. u1h73weckdrmskdqec3c9 is far too
233
-        // precise, limit at ~9 as most GPS are not submeter accurate
234
-        return $this->addToIndex($geohash, 'media__' . $img ['id']);
235
-    }
226
+		$geometry = $this->getCoordsFromExif($img ['id']);
227
+		if (!$geometry) {
228
+			return false;
229
+		}
230
+		$geohash = $geometry->out('geohash');
231
+		// TODO truncate the geohash to something reasonable, otherwise they are
232
+		// useless as an indexing mechanism eg. u1h73weckdrmskdqec3c9 is far too
233
+		// precise, limit at ~9 as most GPS are not submeter accurate
234
+		return $this->addToIndex($geohash, 'media__' . $img ['id']);
235
+	}
236 236
 
237
-    /**
238
-     * retrieve GPS decimal coordinates from exif.
239
-     *
240
-     * @param string $id
241
-     * @return Point|false
242
-     * @throws Exception
243
-     */
244
-    public function getCoordsFromExif(string $id)
245
-    {
246
-        $exif = exif_read_data(mediaFN($id), 0, true);
247
-        if (empty ($exif ['GPS'])) {
248
-            return false;
249
-        }
237
+	/**
238
+	 * retrieve GPS decimal coordinates from exif.
239
+	 *
240
+	 * @param string $id
241
+	 * @return Point|false
242
+	 * @throws Exception
243
+	 */
244
+	public function getCoordsFromExif(string $id)
245
+	{
246
+		$exif = exif_read_data(mediaFN($id), 0, true);
247
+		if (empty ($exif ['GPS'])) {
248
+			return false;
249
+		}
250 250
 
251
-        $lat = $this->convertDMStoD(
252
-            array(
253
-                $exif ['GPS'] ['GPSLatitude'] [0],
254
-                $exif ['GPS'] ['GPSLatitude'] [1],
255
-                $exif ['GPS'] ['GPSLatitude'] [2],
256
-                $exif ['GPS'] ['GPSLatitudeRef']
257
-            )
258
-        );
251
+		$lat = $this->convertDMStoD(
252
+			array(
253
+				$exif ['GPS'] ['GPSLatitude'] [0],
254
+				$exif ['GPS'] ['GPSLatitude'] [1],
255
+				$exif ['GPS'] ['GPSLatitude'] [2],
256
+				$exif ['GPS'] ['GPSLatitudeRef']
257
+			)
258
+		);
259 259
 
260
-        $lon = $this->convertDMStoD(
261
-            array(
262
-                $exif ['GPS'] ['GPSLongitude'] [0],
263
-                $exif ['GPS'] ['GPSLongitude'] [1],
264
-                $exif ['GPS'] ['GPSLongitude'] [2],
265
-                $exif ['GPS'] ['GPSLongitudeRef']
266
-            )
267
-        );
260
+		$lon = $this->convertDMStoD(
261
+			array(
262
+				$exif ['GPS'] ['GPSLongitude'] [0],
263
+				$exif ['GPS'] ['GPSLongitude'] [1],
264
+				$exif ['GPS'] ['GPSLongitude'] [2],
265
+				$exif ['GPS'] ['GPSLongitudeRef']
266
+			)
267
+		);
268 268
 
269
-        return new Point($lon, $lat);
270
-    }
269
+		return new Point($lon, $lat);
270
+	}
271 271
 
272
-    /**
273
-     * convert DegreesMinutesSeconds to Decimal degrees.
274
-     *
275
-     * @param array $param array of rational DMS
276
-     * @return float
277
-     */
278
-    public function convertDMStoD(array $param): float
279
-    {
280
-        if (!is_array($param)) {
281
-            $param = array($param);
282
-        }
283
-        $deg = $this->convertRationaltoFloat($param [0]);
284
-        $min = $this->convertRationaltoFloat($param [1]) / 60;
285
-        $sec = $this->convertRationaltoFloat($param [2]) / 60 / 60;
286
-        // Hemisphere (N, S, W or E)
287
-        $hem = ($param [3] === 'N' || $param [3] === 'E') ? 1 : -1;
288
-        return $hem * ($deg + $min + $sec);
289
-    }
272
+	/**
273
+	 * convert DegreesMinutesSeconds to Decimal degrees.
274
+	 *
275
+	 * @param array $param array of rational DMS
276
+	 * @return float
277
+	 */
278
+	public function convertDMStoD(array $param): float
279
+	{
280
+		if (!is_array($param)) {
281
+			$param = array($param);
282
+		}
283
+		$deg = $this->convertRationaltoFloat($param [0]);
284
+		$min = $this->convertRationaltoFloat($param [1]) / 60;
285
+		$sec = $this->convertRationaltoFloat($param [2]) / 60 / 60;
286
+		// Hemisphere (N, S, W or E)
287
+		$hem = ($param [3] === 'N' || $param [3] === 'E') ? 1 : -1;
288
+		return $hem * ($deg + $min + $sec);
289
+	}
290 290
 
291
-    public function convertRationaltoFloat($param): float
292
-    {
293
-        // rational64u
294
-        $nums = explode('/', $param);
295
-        if ((int)$nums[1] > 0) {
296
-            return (float)$nums[0] / (int)$nums[1];
297
-        } else {
298
-            return (float)$nums[0];
299
-        }
300
-    }
291
+	public function convertRationaltoFloat($param): float
292
+	{
293
+		// rational64u
294
+		$nums = explode('/', $param);
295
+		if ((int)$nums[1] > 0) {
296
+			return (float)$nums[0] / (int)$nums[1];
297
+		} else {
298
+			return (float)$nums[0];
299
+		}
300
+	}
301 301
 
302
-    /**
303
-     * Deletes the page from the index.
304
-     *
305
-     * @param string $id document ID
306
-     */
307
-    public function deleteFromIndex(string $id): void
308
-    {
309
-        // check the index for document
310
-        $knownHashes = $this->findHashesForId($id, $this->spatial_idx);
311
-        if (empty ($knownHashes)) {
312
-            return;
313
-        }
302
+	/**
303
+	 * Deletes the page from the index.
304
+	 *
305
+	 * @param string $id document ID
306
+	 */
307
+	public function deleteFromIndex(string $id): void
308
+	{
309
+		// check the index for document
310
+		$knownHashes = $this->findHashesForId($id, $this->spatial_idx);
311
+		if (empty ($knownHashes)) {
312
+			return;
313
+		}
314 314
 
315
-        // TODO shortcut, need to make sure there is only one element, if not the index is corrupt
316
-        $knownHash = $knownHashes [0];
317
-        $knownIds = $this->spatial_idx [$knownHash];
318
-        $i = array_search($id, $knownIds);
319
-        Logger::getInstance(Logger::LOG_DEBUG)->log("removing: $knownIds[$i] from the index.");
320
-        unset ($knownIds [$i]);
321
-        $this->spatial_idx [$knownHash] = $knownIds;
322
-        if (empty ($this->spatial_idx [$knownHash])) {
323
-            // Logger::getInstance(Logger::LOG_DEBUG)->log ( "removing key: $knownHash from the index." );
324
-            unset ($this->spatial_idx [$knownHash]);
325
-        }
326
-        $this->saveIndex();
327
-    }
315
+		// TODO shortcut, need to make sure there is only one element, if not the index is corrupt
316
+		$knownHash = $knownHashes [0];
317
+		$knownIds = $this->spatial_idx [$knownHash];
318
+		$i = array_search($id, $knownIds);
319
+		Logger::getInstance(Logger::LOG_DEBUG)->log("removing: $knownIds[$i] from the index.");
320
+		unset ($knownIds [$i]);
321
+		$this->spatial_idx [$knownHash] = $knownIds;
322
+		if (empty ($this->spatial_idx [$knownHash])) {
323
+			// Logger::getInstance(Logger::LOG_DEBUG)->log ( "removing key: $knownHash from the index." );
324
+			unset ($this->spatial_idx [$knownHash]);
325
+		}
326
+		$this->saveIndex();
327
+	}
328 328
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -292,10 +292,10 @@
 block discarded – undo
292 292
     {
293 293
         // rational64u
294 294
         $nums = explode('/', $param);
295
-        if ((int)$nums[1] > 0) {
296
-            return (float)$nums[0] / (int)$nums[1];
295
+        if (( int ) $nums[1] > 0) {
296
+            return ( float ) $nums[0] / ( int ) $nums[1];
297 297
         } else {
298
-            return (float)$nums[0];
298
+            return ( float ) $nums[0];
299 299
         }
300 300
     }
301 301
 
Please login to merge, or discard this patch.
helper/sitemap.php 1 patch
Indentation   +224 added lines, -224 removed lines patch added patch discarded remove patch
@@ -23,228 +23,228 @@
 block discarded – undo
23 23
  */
24 24
 class helper_plugin_spatialhelper_sitemap extends DokuWiki_Plugin
25 25
 {
26
-    /**
27
-     * spatial index.
28
-     */
29
-    private $spatial_idx;
30
-
31
-    /**
32
-     * constructor, load spatial index.
33
-     */
34
-    public function __construct()
35
-    {
36
-        global $conf;
37
-        $idx_dir = $conf['indexdir'];
38
-        if (!@file_exists($idx_dir . '/spatial.idx')) {
39
-            $indexer = plugin_load('helper', 'spatialhelper_index');
40
-            $indexer->generateSpatialIndex();
41
-        }
42
-        $this->spatial_idx = unserialize(io_readFile($fn = $idx_dir . '/spatial.idx', false));
43
-    }
44
-
45
-    public function getMethods(): array
46
-    {
47
-        $result[] = array(
48
-            'name' => 'createGeoRSSSitemap',
49
-            'desc' => 'create a spatial sitemap in GeoRSS format.',
50
-            'params' => array(
51
-                'path' => 'string'
52
-            ),
53
-            'return' => array(
54
-                'success' => 'boolean'
55
-            )
56
-        );
57
-        $result[] = array(
58
-            'name' => 'createKMLSitemap',
59
-            'desc' => 'create a spatial sitemap in KML format.',
60
-            'params' => array(
61
-                'path' => 'string'
62
-            ),
63
-            'return' => array(
64
-                'success' => 'boolean'
65
-            )
66
-        );
67
-        return $result;
68
-    }
69
-
70
-    /**
71
-     * Create a GeoRSS Simple sitemap (Atom).
72
-     *
73
-     * @param string $mediaID id
74
-     *                        for the GeoRSS file
75
-     */
76
-    public function createGeoRSSSitemap(string $mediaID): bool
77
-    {
78
-        global $conf;
79
-        $namespace = getNS($mediaID);
80
-
81
-        $idTag = 'tag:' . parse_url(DOKU_URL, PHP_URL_HOST) . ',';
82
-
83
-        $RSSstart = '<?xml version="1.0" encoding="UTF-8"?>' . DOKU_LF;
84
-        $RSSstart .= '<feed xmlns="http://www.w3.org/2005/Atom" xmlns:georss="http://www.georss.org/georss" ';
85
-        $RSSstart .= 'xmlns:dc="http://purl.org/dc/elements/1.1/">' . DOKU_LF;
86
-        $RSSstart .= '<title>' . $conf['title'] . ' spatial feed</title>' . DOKU_LF;
87
-        if (!empty($conf['tagline'])) {
88
-            $RSSstart .= '<subtitle>' . $conf['tagline'] . '</subtitle>' . DOKU_LF;
89
-        }
90
-        $RSSstart .= '<dc:publisher>' . $conf['title'] . '</dc:publisher>' . DOKU_LF;
91
-        $RSSstart .= '<link href="' . DOKU_URL . '" />' . DOKU_LF;
92
-        $RSSstart .= '<link href="' . ml($mediaID, '', true, '&amp;', true) . '" rel="self" />';
93
-        $RSSstart .= DOKU_LF . '<updated>' . date(DATE_ATOM) . '</updated>' . DOKU_LF;
94
-        $RSSstart .= '<id>' . $idTag . date("Y-m-d") . ':' . parse_url(ml($mediaID), PHP_URL_PATH)
95
-            . '</id>' . DOKU_LF;
96
-        $RSSstart .= '<rights>' . $conf['license'] . '</rights>' . DOKU_LF;
97
-
98
-        $RSSend = '</feed>' . DOKU_LF;
99
-
100
-        io_createNamespace($mediaID, 'media');
101
-        @touch(mediaFN($mediaID));
102
-        @chmod(mediaFN($mediaID), $conf['fmode']);
103
-        $fh = fopen(mediaFN($mediaID), 'w');
104
-        fwrite($fh, $RSSstart);
105
-
106
-        foreach ($this->spatial_idx as $idxEntry) {
107
-            // get list of id's
108
-            foreach ($idxEntry as $id) {
109
-                // for document item in the index
110
-                if (strpos($id, 'media__', 0) !== 0) {
111
-                    if ($this->skipPage($id, $namespace)) {
112
-                        continue;
113
-                    }
114
-
115
-                    $meta = p_get_metadata($id);
116
-
117
-                    // $desc = p_render('xhtmlsummary', p_get_instructions($meta['description']['abstract']), $info);
118
-                    $desc = strip_tags($meta['description']['abstract']);
119
-
120
-                    $entry = '<entry>' . DOKU_LF;
121
-                    $entry .= '  <title>' . $meta['title'] . '</title>' . DOKU_LF;
122
-                    $entry .= '  <summary>' . $desc . '</summary>' . DOKU_LF;
123
-                    $entry .= '  <georss:point>' . $meta['geo']['lat'] . ' ' . $meta['geo']['lon']
124
-                        . '</georss:point>' . DOKU_LF;
125
-                    if ($meta['geo']['alt']) {
126
-                        $entry .= '  <georss:elev>' . $meta['geo']['alt'] . '</georss:elev>' . DOKU_LF;
127
-                    }
128
-                    $entry .= '  <link href="' . wl($id) . '" rel="alternate" type="text/html" />' . DOKU_LF;
129
-                    if (empty($meta['creator'])) {
130
-                        $meta['creator'] = $conf['title'];
131
-                    }
132
-                    $entry .= '  <author><name>' . $meta['creator'] . '</name></author>' . DOKU_LF;
133
-                    $entry .= '  <updated>' . date_iso8601($meta['date']['modified']) . '</updated>' . DOKU_LF;
134
-                    $entry .= '  <published>' . date_iso8601($meta['date']['created']) . '</published>' . DOKU_LF;
135
-                    $entry .= '  <id>' . $idTag . date("Y-m-d", $meta['date']['modified']) . ':'
136
-                        . parse_url(wl($id), PHP_URL_PATH) . '</id>' . DOKU_LF;
137
-                    $entry .= '</entry>' . DOKU_LF;
138
-                    fwrite($fh, $entry);
139
-                }
140
-            }
141
-        }
142
-
143
-        fwrite($fh, $RSSend);
144
-        return fclose($fh);
145
-    }
146
-
147
-    /**
148
-     * will return true for non-public or hidden pages or pages that are not below or in the namespace.
149
-     */
150
-    private function skipPage(string $id, string $namespace): bool
151
-    {
152
-        Logger::getInstance(Logger::LOG_DEBUG)->log(
153
-            "helper_plugin_spatialhelper_sitemap::skipPage, check for $id in $namespace"
154
-        );
155
-        if (isHiddenPage($id)) {
156
-            return true;
157
-        }
158
-        if (auth_aclcheck($id, '', null) < AUTH_READ) {
159
-            return true;
160
-        }
161
-
162
-        if (!empty($namespace)) {
163
-            // only if id is in or below namespace
164
-            if (0 !== strpos(getNS($id), $namespace)) {
165
-                // Logger::getInstance(Logger::LOG_DEBUG)->log("helper_plugin_spatialhelper_sitemap::skipPage,
166
-                //      skipping $id, not in $namespace");
167
-                return true;
168
-            }
169
-        }
170
-        return false;
171
-    }
172
-
173
-    /**
174
-     * Create a KML sitemap.
175
-     *
176
-     * @param string $mediaID id for the KML file
177
-     */
178
-    public function createKMLSitemap(string $mediaID): bool
179
-    {
180
-        global $conf;
181
-        $namespace = getNS($mediaID);
182
-
183
-        $KMLstart = '<?xml version="1.0" encoding="UTF-8"?>' . DOKU_LF;
184
-        $KMLstart .= '<kml xmlns="http://www.opengis.net/kml/2.2" ';
185
-        $KMLstart .= 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ';
186
-        $KMLstart .= 'xmlns:atom="http://www.w3.org/2005/Atom"';
187
-        $KMLstart .= ' xsi:schemaLocation="http://www.opengis.net/kml/2.2 ';
188
-        $KMLstart .= 'http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd">' . DOKU_LF;
189
-        $KMLstart .= '<Document id="root_doc">' . DOKU_LF;
190
-        $KMLstart .= '<name>' . $conf['title'] . ' spatial sitemap</name>' . DOKU_LF;
191
-        $KMLstart .= '<atom:link href="' . DOKU_URL . '" rel="related" type="text/html" />' . DOKU_LF;
192
-        $KMLstart .= '<!-- atom:updated>' . date(DATE_ATOM) . '</atom:updated -->' . DOKU_LF;
193
-        $KMLstart .= '<Style id="icon"><IconStyle><color>ffffffff</color><scale>1</scale>';
194
-        $KMLstart .= '<Icon><href>'
195
-            . DOKU_BASE . 'lib/plugins/spatialhelper/wikiitem.png</href></Icon></IconStyle></Style>' . DOKU_LF;
196
-
197
-        $KMLend = '</Document>' . DOKU_LF . '</kml>';
198
-
199
-        io_createNamespace($mediaID, 'media');
200
-        @touch(mediaFN($mediaID));
201
-        @chmod(mediaFN($mediaID), $conf['fmode']);
202
-
203
-        $fh = fopen(mediaFN($mediaID), 'w');
204
-        fwrite($fh, $KMLstart);
205
-
206
-        foreach ($this->spatial_idx as $idxEntry) {
207
-            // get list of id's
208
-            foreach ($idxEntry as $id) {
209
-                // for document item in the index
210
-                if (strpos($id, 'media__', 0) !== 0) {
211
-                    if ($this->skipPage($id, $namespace)) {
212
-                        continue;
213
-                    }
214
-
215
-                    $meta = p_get_metadata($id);
216
-
217
-                    // $desc = p_render('xhtmlsummary', p_get_instructions($meta['description']['abstract']), $info);
218
-                    $desc = '<p>' . strip_tags($meta['description']['abstract']) . '</p>';
219
-                    $desc .= '<p><a href="' . wl($id, '', true) . '">' . $meta['title']
220
-                        . '</a></p>';
221
-
222
-                    // create an entry and store it
223
-                    $plcm = '<Placemark id="crc32-' . hash('crc32', $id) . '">' . DOKU_LF;
224
-                    $plcm .= '  <name>' . $meta['title'] . '</name>' . DOKU_LF;
225
-                    // TODO escape quotes in: title="' . $meta['title'] . '"
226
-                    $plcm .= '  <atom:link href="' . wl($id, '' . true);
227
-                    $plcm .= '" rel="alternate" type="text/html" />' . DOKU_LF;
228
-                    if (!empty($meta['creator'])) {
229
-                        $plcm .= '  <atom:author><atom:name>' . $meta['creator'] . '</atom:name></atom:author>'
230
-                            . DOKU_LF;
231
-                    }
232
-
233
-                    $plcm .= '  <description><![CDATA[' . $desc . ']]></description>' . DOKU_LF;
234
-                    $plcm .= '  <styleUrl>#icon</styleUrl>' . DOKU_LF;
235
-
236
-                    $plcm .= '  <Point><coordinates>' . $meta['geo']['lon'] . ',' . $meta['geo']['lat'];
237
-                    if ($meta['geo']['alt']) {
238
-                        $plcm .= ',' . $meta['geo']['alt'];
239
-                    }
240
-                    $plcm .= '</coordinates></Point>' . DOKU_LF;
241
-                    $plcm .= '</Placemark>' . DOKU_LF;
242
-
243
-                    fwrite($fh, $plcm);
244
-                }
245
-            }
246
-        }
247
-        fwrite($fh, $KMLend);
248
-        return fclose($fh);
249
-    }
26
+	/**
27
+	 * spatial index.
28
+	 */
29
+	private $spatial_idx;
30
+
31
+	/**
32
+	 * constructor, load spatial index.
33
+	 */
34
+	public function __construct()
35
+	{
36
+		global $conf;
37
+		$idx_dir = $conf['indexdir'];
38
+		if (!@file_exists($idx_dir . '/spatial.idx')) {
39
+			$indexer = plugin_load('helper', 'spatialhelper_index');
40
+			$indexer->generateSpatialIndex();
41
+		}
42
+		$this->spatial_idx = unserialize(io_readFile($fn = $idx_dir . '/spatial.idx', false));
43
+	}
44
+
45
+	public function getMethods(): array
46
+	{
47
+		$result[] = array(
48
+			'name' => 'createGeoRSSSitemap',
49
+			'desc' => 'create a spatial sitemap in GeoRSS format.',
50
+			'params' => array(
51
+				'path' => 'string'
52
+			),
53
+			'return' => array(
54
+				'success' => 'boolean'
55
+			)
56
+		);
57
+		$result[] = array(
58
+			'name' => 'createKMLSitemap',
59
+			'desc' => 'create a spatial sitemap in KML format.',
60
+			'params' => array(
61
+				'path' => 'string'
62
+			),
63
+			'return' => array(
64
+				'success' => 'boolean'
65
+			)
66
+		);
67
+		return $result;
68
+	}
69
+
70
+	/**
71
+	 * Create a GeoRSS Simple sitemap (Atom).
72
+	 *
73
+	 * @param string $mediaID id
74
+	 *                        for the GeoRSS file
75
+	 */
76
+	public function createGeoRSSSitemap(string $mediaID): bool
77
+	{
78
+		global $conf;
79
+		$namespace = getNS($mediaID);
80
+
81
+		$idTag = 'tag:' . parse_url(DOKU_URL, PHP_URL_HOST) . ',';
82
+
83
+		$RSSstart = '<?xml version="1.0" encoding="UTF-8"?>' . DOKU_LF;
84
+		$RSSstart .= '<feed xmlns="http://www.w3.org/2005/Atom" xmlns:georss="http://www.georss.org/georss" ';
85
+		$RSSstart .= 'xmlns:dc="http://purl.org/dc/elements/1.1/">' . DOKU_LF;
86
+		$RSSstart .= '<title>' . $conf['title'] . ' spatial feed</title>' . DOKU_LF;
87
+		if (!empty($conf['tagline'])) {
88
+			$RSSstart .= '<subtitle>' . $conf['tagline'] . '</subtitle>' . DOKU_LF;
89
+		}
90
+		$RSSstart .= '<dc:publisher>' . $conf['title'] . '</dc:publisher>' . DOKU_LF;
91
+		$RSSstart .= '<link href="' . DOKU_URL . '" />' . DOKU_LF;
92
+		$RSSstart .= '<link href="' . ml($mediaID, '', true, '&amp;', true) . '" rel="self" />';
93
+		$RSSstart .= DOKU_LF . '<updated>' . date(DATE_ATOM) . '</updated>' . DOKU_LF;
94
+		$RSSstart .= '<id>' . $idTag . date("Y-m-d") . ':' . parse_url(ml($mediaID), PHP_URL_PATH)
95
+			. '</id>' . DOKU_LF;
96
+		$RSSstart .= '<rights>' . $conf['license'] . '</rights>' . DOKU_LF;
97
+
98
+		$RSSend = '</feed>' . DOKU_LF;
99
+
100
+		io_createNamespace($mediaID, 'media');
101
+		@touch(mediaFN($mediaID));
102
+		@chmod(mediaFN($mediaID), $conf['fmode']);
103
+		$fh = fopen(mediaFN($mediaID), 'w');
104
+		fwrite($fh, $RSSstart);
105
+
106
+		foreach ($this->spatial_idx as $idxEntry) {
107
+			// get list of id's
108
+			foreach ($idxEntry as $id) {
109
+				// for document item in the index
110
+				if (strpos($id, 'media__', 0) !== 0) {
111
+					if ($this->skipPage($id, $namespace)) {
112
+						continue;
113
+					}
114
+
115
+					$meta = p_get_metadata($id);
116
+
117
+					// $desc = p_render('xhtmlsummary', p_get_instructions($meta['description']['abstract']), $info);
118
+					$desc = strip_tags($meta['description']['abstract']);
119
+
120
+					$entry = '<entry>' . DOKU_LF;
121
+					$entry .= '  <title>' . $meta['title'] . '</title>' . DOKU_LF;
122
+					$entry .= '  <summary>' . $desc . '</summary>' . DOKU_LF;
123
+					$entry .= '  <georss:point>' . $meta['geo']['lat'] . ' ' . $meta['geo']['lon']
124
+						. '</georss:point>' . DOKU_LF;
125
+					if ($meta['geo']['alt']) {
126
+						$entry .= '  <georss:elev>' . $meta['geo']['alt'] . '</georss:elev>' . DOKU_LF;
127
+					}
128
+					$entry .= '  <link href="' . wl($id) . '" rel="alternate" type="text/html" />' . DOKU_LF;
129
+					if (empty($meta['creator'])) {
130
+						$meta['creator'] = $conf['title'];
131
+					}
132
+					$entry .= '  <author><name>' . $meta['creator'] . '</name></author>' . DOKU_LF;
133
+					$entry .= '  <updated>' . date_iso8601($meta['date']['modified']) . '</updated>' . DOKU_LF;
134
+					$entry .= '  <published>' . date_iso8601($meta['date']['created']) . '</published>' . DOKU_LF;
135
+					$entry .= '  <id>' . $idTag . date("Y-m-d", $meta['date']['modified']) . ':'
136
+						. parse_url(wl($id), PHP_URL_PATH) . '</id>' . DOKU_LF;
137
+					$entry .= '</entry>' . DOKU_LF;
138
+					fwrite($fh, $entry);
139
+				}
140
+			}
141
+		}
142
+
143
+		fwrite($fh, $RSSend);
144
+		return fclose($fh);
145
+	}
146
+
147
+	/**
148
+	 * will return true for non-public or hidden pages or pages that are not below or in the namespace.
149
+	 */
150
+	private function skipPage(string $id, string $namespace): bool
151
+	{
152
+		Logger::getInstance(Logger::LOG_DEBUG)->log(
153
+			"helper_plugin_spatialhelper_sitemap::skipPage, check for $id in $namespace"
154
+		);
155
+		if (isHiddenPage($id)) {
156
+			return true;
157
+		}
158
+		if (auth_aclcheck($id, '', null) < AUTH_READ) {
159
+			return true;
160
+		}
161
+
162
+		if (!empty($namespace)) {
163
+			// only if id is in or below namespace
164
+			if (0 !== strpos(getNS($id), $namespace)) {
165
+				// Logger::getInstance(Logger::LOG_DEBUG)->log("helper_plugin_spatialhelper_sitemap::skipPage,
166
+				//      skipping $id, not in $namespace");
167
+				return true;
168
+			}
169
+		}
170
+		return false;
171
+	}
172
+
173
+	/**
174
+	 * Create a KML sitemap.
175
+	 *
176
+	 * @param string $mediaID id for the KML file
177
+	 */
178
+	public function createKMLSitemap(string $mediaID): bool
179
+	{
180
+		global $conf;
181
+		$namespace = getNS($mediaID);
182
+
183
+		$KMLstart = '<?xml version="1.0" encoding="UTF-8"?>' . DOKU_LF;
184
+		$KMLstart .= '<kml xmlns="http://www.opengis.net/kml/2.2" ';
185
+		$KMLstart .= 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ';
186
+		$KMLstart .= 'xmlns:atom="http://www.w3.org/2005/Atom"';
187
+		$KMLstart .= ' xsi:schemaLocation="http://www.opengis.net/kml/2.2 ';
188
+		$KMLstart .= 'http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd">' . DOKU_LF;
189
+		$KMLstart .= '<Document id="root_doc">' . DOKU_LF;
190
+		$KMLstart .= '<name>' . $conf['title'] . ' spatial sitemap</name>' . DOKU_LF;
191
+		$KMLstart .= '<atom:link href="' . DOKU_URL . '" rel="related" type="text/html" />' . DOKU_LF;
192
+		$KMLstart .= '<!-- atom:updated>' . date(DATE_ATOM) . '</atom:updated -->' . DOKU_LF;
193
+		$KMLstart .= '<Style id="icon"><IconStyle><color>ffffffff</color><scale>1</scale>';
194
+		$KMLstart .= '<Icon><href>'
195
+			. DOKU_BASE . 'lib/plugins/spatialhelper/wikiitem.png</href></Icon></IconStyle></Style>' . DOKU_LF;
196
+
197
+		$KMLend = '</Document>' . DOKU_LF . '</kml>';
198
+
199
+		io_createNamespace($mediaID, 'media');
200
+		@touch(mediaFN($mediaID));
201
+		@chmod(mediaFN($mediaID), $conf['fmode']);
202
+
203
+		$fh = fopen(mediaFN($mediaID), 'w');
204
+		fwrite($fh, $KMLstart);
205
+
206
+		foreach ($this->spatial_idx as $idxEntry) {
207
+			// get list of id's
208
+			foreach ($idxEntry as $id) {
209
+				// for document item in the index
210
+				if (strpos($id, 'media__', 0) !== 0) {
211
+					if ($this->skipPage($id, $namespace)) {
212
+						continue;
213
+					}
214
+
215
+					$meta = p_get_metadata($id);
216
+
217
+					// $desc = p_render('xhtmlsummary', p_get_instructions($meta['description']['abstract']), $info);
218
+					$desc = '<p>' . strip_tags($meta['description']['abstract']) . '</p>';
219
+					$desc .= '<p><a href="' . wl($id, '', true) . '">' . $meta['title']
220
+						. '</a></p>';
221
+
222
+					// create an entry and store it
223
+					$plcm = '<Placemark id="crc32-' . hash('crc32', $id) . '">' . DOKU_LF;
224
+					$plcm .= '  <name>' . $meta['title'] . '</name>' . DOKU_LF;
225
+					// TODO escape quotes in: title="' . $meta['title'] . '"
226
+					$plcm .= '  <atom:link href="' . wl($id, '' . true);
227
+					$plcm .= '" rel="alternate" type="text/html" />' . DOKU_LF;
228
+					if (!empty($meta['creator'])) {
229
+						$plcm .= '  <atom:author><atom:name>' . $meta['creator'] . '</atom:name></atom:author>'
230
+							. DOKU_LF;
231
+					}
232
+
233
+					$plcm .= '  <description><![CDATA[' . $desc . ']]></description>' . DOKU_LF;
234
+					$plcm .= '  <styleUrl>#icon</styleUrl>' . DOKU_LF;
235
+
236
+					$plcm .= '  <Point><coordinates>' . $meta['geo']['lon'] . ',' . $meta['geo']['lat'];
237
+					if ($meta['geo']['alt']) {
238
+						$plcm .= ',' . $meta['geo']['alt'];
239
+					}
240
+					$plcm .= '</coordinates></Point>' . DOKU_LF;
241
+					$plcm .= '</Placemark>' . DOKU_LF;
242
+
243
+					fwrite($fh, $plcm);
244
+				}
245
+			}
246
+		}
247
+		fwrite($fh, $KMLend);
248
+		return fclose($fh);
249
+	}
250 250
 }
Please login to merge, or discard this patch.