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