1<?php 2 3/* 4 * Copyright (c) 2011-2026 Mark C. Prins <mprins@users.sf.net> 5 * 6 * Permission to use, copy, modify, and distribute this software for any 7 * purpose with or without fee is hereby granted, provided that the above 8 * copyright notice and this permission notice appear in all copies. 9 * 10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 17 */ 18 19use dokuwiki\Extension\ActionPlugin; 20use dokuwiki\Extension\Event; 21use dokuwiki\Extension\EventHandler; 22use dokuwiki\Logger; 23use dokuwiki\Sitemap\Item; 24 25/** 26 * DokuWiki Plugin dokuwikispatial (Action Component). 27 * 28 * @license BSD license 29 * @author Mark C. Prins <mprins@users.sf.net> 30 * 31 * @phpcs:disable Squiz.Classes.ValidClassName.NotPascalCase 32 */ 33class action_plugin_spatialhelper extends ActionPlugin 34{ 35 /** 36 * Register for events. 37 * 38 * @param EventHandler $controller 39 * DokuWiki's event controller object. 40 */ 41 final public function register(EventHandler $controller): void 42 { 43 // listen for page add / delete events 44 // http://www.dokuwiki.org/devel:event:indexer_page_add 45 $controller->register_hook('INDEXER_PAGE_ADD', 'BEFORE', $this, 'handleIndexerPageAdd'); 46 $controller->register_hook('IO_WIKIPAGE_WRITE', 'BEFORE', $this, 'removeFromIndex'); 47 48 // http://www.dokuwiki.org/devel:event:sitemap_generate 49 $controller->register_hook('SITEMAP_GENERATE', 'BEFORE', $this, 'handleSitemapGenerateBefore'); 50 // using after will only trigger us if a sitemap was actually created 51 $controller->register_hook('SITEMAP_GENERATE', 'AFTER', $this, 'handleSitemapGenerateAfter'); 52 53 // handle actions we know of 54 $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'handleActionActPreprocess', []); 55 // handle HTML eg. /dokuwiki/doku.php?id=start&do=findnearby&geohash=u15vk4 56 $controller->register_hook( 57 'TPL_ACT_UNKNOWN', 58 'BEFORE', 59 $this, 60 'findnearby', 61 ['format' => 'HTML'] 62 ); 63 // handles AJAX/json eg: jQuery.post("/dokuwiki/lib/exe/ajax.php?id=start&call=findnearby&geohash=u15vk4"); 64 $controller->register_hook( 65 'AJAX_CALL_UNKNOWN', 66 'BEFORE', 67 $this, 68 'findnearby', 69 ['format' => 'JSON'] 70 ); 71 72 // listen for media uploads and deletes 73 $controller->register_hook('MEDIA_UPLOAD_FINISH', 'BEFORE', $this, 'handleMediaUploaded', []); 74 $controller->register_hook('MEDIA_DELETE_FILE', 'BEFORE', $this, 'handleMediaDeleted', []); 75 76 $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'handleMetaheaderOutput'); 77 $controller->register_hook('PLUGIN_POPULARITY_DATA_SETUP', 'AFTER', $this, 'popularity'); 78 } 79 80 /** 81 * Update the spatial index for the page. 82 * 83 * @param Event $event 84 * event object 85 */ 86 final public function handleIndexerPageAdd(Event $event): void 87 { 88 // $event→data['page'] – the page id 89 // $event→data['body'] – empty, can be filled by additional content to index by your plugin 90 // $event→data['metadata'] – the metadata that shall be indexed. This is an array where the keys are the 91 // metadata indexes and the value a string or an array of strings with the values. 92 // title and relation_references will already be set. 93 $id = $event->data ['page']; 94 $indexer = plugin_load('helper', 'spatialhelper_index'); 95 $indexer->updateSpatialIndex($id); 96 } 97 98 /** 99 * Update the spatial index, removing the page. 100 * 101 * @param Event $event 102 * event object 103 */ 104 final public function removeFromIndex(Event $event): void 105 { 106 // event data: 107 // $data[0] – The raw arguments for io_saveFile as an array. Do not change file path. 108 // $data[0][0] – the file path. 109 // $data[0][1] – the content to be saved, and may be modified. 110 // $data[1] – ns: The colon separated namespace path minus the trailing page name. (false if root ns) 111 // $data[2] – page_name: The wiki page name. 112 // $data[3] – rev: The page revision, false for current wiki pages. 113 114 Logger::debug("Event data in removeFromIndex.", $event->data); 115 if (@file_exists($event->data [0] [0])) { 116 // file not new 117 if (!$event->data [0] [1]) { 118 // file is empty, page is being deleted 119 if (empty($event->data [1])) { 120 // root namespace 121 $id = $event->data [2]; 122 } else { 123 $id = $event->data [1] . ":" . $event->data [2]; 124 } 125 $indexer = plugin_load('helper', 'spatialhelper_index'); 126 $indexer?->deleteFromIndex($id); 127 } 128 } 129 } 130 131 /** 132 * Add a new SitemapItem object that points to the KML of public geocoded pages. 133 * 134 * @param Event $event 135 */ 136 final public function handleSitemapGenerateBefore(Event $event): void 137 { 138 $path = mediaFN($this->getConf('media_kml')); 139 $lastmod = @filemtime($path); 140 $event->data ['items'] [] = new Item(ml($this->getConf('media_kml'), '', true, '&', true), $lastmod); 141 } 142 143 /** 144 * Create a spatial sitemap or attach the geo/kml map to the sitemap. 145 * 146 * event object, not used 147 */ 148 final public function handleSitemapGenerateAfter(): bool 149 { 150 // $event→data['items']: Array of SitemapItem instances, the array of sitemap items that already 151 // contains all public pages of the wiki 152 // $event→data['sitemap']: The path of the file the sitemap will be saved to. 153 if (($helper = plugin_load('helper', 'spatialhelper_sitemap')) !== null) { 154 $kml = $helper->createKMLSitemap($this->getConf('media_kml')); 155 $rss = $helper->createGeoRSSSitemap($this->getConf('media_georss')); 156 157 if (!empty($this->getConf('sitemap_namespaces'))) { 158 $namespaces = array_map(trim(...), explode("\n", $this->getConf('sitemap_namespaces'))); 159 foreach ($namespaces as $namespace) { 160 $kmlN = $helper->createKMLSitemap($namespace . $this->getConf('media_kml')); 161 $rssN = $helper->createGeoRSSSitemap($namespace . $this->getConf('media_georss')); 162 Logger::debug( 163 "handleSitemapGenerateAfter, created KML / GeoRSS sitemap in $namespace, succes: ", 164 $kmlN && $rssN 165 ); 166 } 167 } 168 return $kml && $rss; 169 } 170 return false; 171 } 172 173 /** 174 * trap findnearby action. 175 * This additional handler is required as described at: https://www.dokuwiki.org/devel:event:tpl_act_unknown 176 * 177 * @param Event $event 178 * event object 179 */ 180 final public function handleActionActPreprocess(Event $event): void 181 { 182 if ($event->data !== 'findnearby') { 183 return; 184 } 185 $event->preventDefault(); 186 } 187 188 /** 189 * handle findnearby action. 190 * 191 * @param Event $event 192 * event object 193 * @param array $param 194 * associative array with keys 195 * 'format'=> HTML | JSON 196 * @throws JsonException if anything goes wrong with JSON encoding 197 */ 198 final public function findnearby(Event $event, array $param): void 199 { 200 if ($event->data !== 'findnearby') { 201 return; 202 } 203 $event->preventDefault(); 204 $results = []; 205 global $INPUT; 206 if (($helper = plugin_load('helper', 'spatialhelper_search')) !== null) { 207 if ($INPUT->has('lat') && $INPUT->has('lon')) { 208 $results = $helper->findNearbyLatLon($INPUT->param('lat'), $INPUT->param('lon')); 209 } elseif ($INPUT->has('geohash')) { 210 $results = $helper->findNearby($INPUT->str('geohash')); 211 } else { 212 $results = ['error' => hsc($this->getLang('invalidinput'))]; 213 } 214 } 215 216 $showMedia = $INPUT->bool('showMedia', true); 217 218 match ($param['format']) { 219 'JSON' => $this->printJSON($results), 220 default => $this->printHTML($results, $showMedia), 221 }; 222 } 223 224 /** 225 * Print seachresults as HTML lists. 226 * 227 * @param array $searchresults 228 * @throws JsonException if anything goes wrong with JSON encoding 229 */ 230 private function printJSON(array $searchresults): void 231 { 232 header('Content-Type: application/json'); 233 echo json_encode($searchresults, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT); 234 } 235 236 /** 237 * Print seachresults as HTML lists. 238 * 239 * @param array $searchresults 240 * @param bool $showMedia 241 */ 242 private function printHTML(array $searchresults, bool $showMedia = true): void 243 { 244 $pages = (array)($searchresults ['pages']); 245 $media = (array)$searchresults ['media']; 246 $lat = (float)$searchresults ['lat']; 247 $lon = (float)$searchresults ['lon']; 248 $geohash = (string)$searchresults ['geohash']; 249 250 if (isset($searchresults ['error'])) { 251 echo '<div class="level1"><p>' . hsc($searchresults ['error']) . '</p></div>'; 252 return; 253 } 254 255 // print the HTML list 256 echo '<h1>' . $this->getLang('results_header') . '</h1>' . DOKU_LF; 257 echo '<div class="level1">' . DOKU_LF; 258 if ($pages !== []) { 259 $pagelist = '<ol>' . DOKU_LF; 260 foreach ($pages as $page) { 261 $pagelist .= '<li>' . html_wikilink( 262 ':' . $page ['id'], 263 useHeading('navigation') ? null : 264 noNS($page ['id']) 265 ) . ' (' . $this->getLang('results_distance_prefix') 266 . $page ['distance'] . ' m) ' . $page ['description'] . '</li>' . DOKU_LF; 267 } 268 $pagelist .= '</ol>' . DOKU_LF; 269 270 echo '<h2>' . $this->getLang('results_pages') . hsc( 271 ' lat;lon: ' . $lat . ';' . $lon 272 . ' (geohash: ' . $geohash . ')' 273 ) . '</h2>'; 274 echo '<div class="level2">' . DOKU_LF; 275 echo $pagelist; 276 echo '</div>' . DOKU_LF; 277 } else { 278 echo '<p>' . hsc($this->getLang('nothingfound')) . '</p>'; 279 } 280 281 if ($media !== [] && $showMedia) { 282 $pagelist = '<ol>' . DOKU_LF; 283 foreach ($media as $m) { 284 $opts = []; 285 $link = ml($m ['id'], $opts, false); 286 $opts ['w'] = '100'; 287 $src = ml($m ['id'], $opts); 288 $pagelist .= '<li><a href="' . $link . '"><img src="' . $src . '" alt=""></a> (' 289 . $this->getLang('results_distance_prefix') . $m ['distance'] . ' m) ' 290 . '</li>' . DOKU_LF; 291 } 292 $pagelist .= '</ol>' . DOKU_LF; 293 294 echo '<h2>' . $this->getLang('results_media') . hsc( 295 ' lat;lon: ' . $lat . ';' . $lon 296 . ' (geohash: ' . $geohash . ')' 297 ) . '</h2>' . DOKU_LF; 298 echo '<div class="level2">' . DOKU_LF; 299 echo $pagelist; 300 echo '</div>' . DOKU_LF; 301 } 302 echo '<p>' . $this->getLang('results_precision') . $searchresults ['precision'] . ' m. '; 303 if (strlen($geohash) > 1) { 304 $url = wl( 305 getID(), 306 ['do' => 'findnearby', 'geohash' => substr($geohash, 0, -1)] 307 ); 308 echo '<a href="' . $url . '" class="findnearby">' . $this->getLang('search_largerarea') . '</a>.</p>' 309 . DOKU_LF; 310 } 311 echo '</div>' . DOKU_LF; 312 } 313 314 /** 315 * add media to spatial index. 316 * 317 * @param Event $event 318 */ 319 final public function handleMediaUploaded(Event $event): void 320 { 321 //data[0] path/to/new/media.file (normally read from $_FILES, potentially could come from elsewhere) 322 //data[1] file name of the file being uploaded 323 //data[2] future directory id of the file being uploaded 324 //data[3] the mime type of the file being uploaded 325 //data[4] true if the uploaded file exists already 326 //data[5] (since 2011-02-06) the PHP function used to move the file to the correct location 327 328 Logger::debug("handleMediaUploaded::event data", $event->data); 329 330 // check the list of mimetypes 331 // if it's a supported type call appropriate index function 332 if (str_contains($event->data [3], 'image/jpeg')) { 333 $indexer = plugin_load('helper', 'spatialhelper_index'); 334 $indexer?->indexImage($event->data [2]); 335 } 336 // TODO add image/tiff 337 // TODO kml, gpx, geojson... 338 } 339 340 /** 341 * removes the media from the index. 342 * @param Event $event event object with data 343 */ 344 final public function handleMediaDeleted(Event $event): void 345 { 346 // data['id'] ID data['unl'] unlink return code 347 // data['del'] Namespace directory unlink return code 348 // data['name'] file name data['path'] full path to the file 349 // data['size'] file size 350 351 // remove the media id from the index 352 $indexer = plugin_load('helper', 'spatialhelper_index'); 353 $indexer?->deleteFromIndex('media__' . $event->data ['id']); 354 } 355 356 /** 357 * add a link to the spatial sitemap files in the header. 358 * 359 * @param Event $event the DokuWiki event. $event->data is a two-dimensional array of all meta headers. 360 * The keys are meta, link and script. 361 * 362 * @see http://www.dokuwiki.org/devel:event:tpl_metaheader_output 363 */ 364 final public function handleMetaheaderOutput(Event $event): void 365 { 366 // TODO maybe test for exist 367 $event->data ["link"] [] = ["type" => "application/atom+xml", "rel" => "alternate", 368 "href" => ml($this->getConf('media_georss')), "title" => "Spatial ATOM Feed"]; 369 $event->data ["link"] [] = ["type" => "application/vnd.google-earth.kml+xml", "rel" => "alternate", 370 "href" => ml($this->getConf('media_kml')), "title" => "KML Sitemap"]; 371 } 372 373 /** 374 * Add spatialhelper popularity data. 375 * 376 * @param Event $event 377 * the DokuWiki event 378 */ 379 final public function popularity(Event $event): void 380 { 381 $versionInfo = getVersionData(); 382 $plugin_info = $this->getInfo(); 383 $event->data['spatialhelper']['version'] = $plugin_info['date']; 384 $event->data['spatialhelper']['dwversion'] = $versionInfo['date']; 385 $event->data['spatialhelper']['combinedversion'] = $versionInfo['date'] . '_' . $plugin_info['date']; 386 } 387} 388