2 /* This extension creates a map using OpenLayers to show sledrun details and sledrun overviews.
3 This extension depends on no other extension.
9 <wrgmap lat="47.267648" lon="11.40465" zoom="10"/>
11 (Shows icons for all sledruns. lat, lon and zoom are optional.)
17 <wrmap lat="47.2417134" lon="11.21408895" zoom="14" width="700" height="400">
19 <gasthaus name="Rosskogelhütte" wiki="Rosskogelhütte">47.240689 11.190454</gasthaus>
20 <gasthaus name="Stiglreith">47.238186 11.221940</gasthaus>
21 <gasthaus name="Sulzstich">47.240287 11.203006</gasthaus>
22 <parkplatz>47.245789 11.238971</parkplatz>
23 <parkplatz>47.237627 11.218886</parkplatz>
24 <haltestelle name="Oberperfuss Rangger Köpfl Lift">47.245711 11.238283</haltestelle>
25 <achtung name="Kreuzung mit Schipiste">47.2383200 11.2235592</achtung>
108 * <wrmap>...</wrmap> has to be valid XML.
109 * All coordinates are in WGS84 coordinate system.
110 * Coordinates have the preferred format "latitude N longitude E",
111 however for parsing the N and E can be omitted.
112 * <wrmap> has the following attributes:
113 * lat (float): latitude of map-center, optional.
114 * lon (float): longitude of map-center, optional.
115 * zoom (integer): zoom level of the map (google zoom levels). optional.
116 * width (integer): width of the map in pixel. optional (100% if omitted)
117 * height (integer): height of the map in pixel. optional.
118 * <wrmap> can have any number of the following sub-elements:
132 * The order may be used by the renderer to determine in which order the
133 elements should be drawn: First mentioned elements are drawn first.
134 * <gasthaus>, <haltestelle>, <parkplatz>, <achtung>, <foto>, <verleih> and <punkt> define points
135 * The elements may have the following attributes:
136 * name (string): defines the name (not the label) of the element
137 * wiki (string): name of a MediaWiki page the point refers to
138 * The content is exactly one coordinate pair.
139 * <rodelbahn>, <alternative>, <gehweg>, <lift>, <anfahrt> and <linie>
140 define non-closed polygons.
141 * They may have the following attributes:
142 farbe (hex format, e.g. #12a50f): color of the line
143 dicke (int): width of the line in pixel
144 * The content of the elements are a whitespace separated list of
148 For transmitting the map to javascript, geojson is used in the <div> element of the map.
149 This way, an extra request is avoided. The geojson format used here consists of a single
150 "FeatureCollection" (representing the <wrmap>) containing the sub-elements of wrmap
152 The features have an properties key that has a hash as values with the properties of
153 the XML subelements of wrmap. Optional attributes/properties can be omitted.
154 Additionally one mandatory property key is called 'type' and has the sub-element's name
156 The featurecollection itself has a properties key as well containing the attributes of
159 use MediaWiki\MediaWikiServices;
162 // DOM helper classes
163 // ------------------
165 // The following two classes are "duplicated" from the wrreport extension to keep them separate.
166 // Put improvements in both classes.
167 class WrMapDOMDocument extends DOMDocument {
168 function __construct() {
169 parent::__construct('1.0', 'utf-8');
170 $this->registerNodeClass('DOMElement', 'WrMapDOMElement');
173 /// Creates and adds the element with the given tag name and returns it.
174 /// Additionally, it calls setAttribute($key, $value) for every entry
176 function appendElement(string $tagName, $attributes=array()): WrMapDOMElement {
177 $child = $this->appendChild($this->createElement($tagName));
178 foreach ($attributes as $key => $value) $child->setAttribute($key, $value);
184 class WrMapDOMElement extends DOMElement {
186 /// Creates and adds the element with the given tag name and returns it
187 /// Additionally, it calls setAttribute($key, $value) for every entry
189 function appendElement(string $tagName, $attributes=array()): WrMapDOMElement {
190 $child = $this->appendChild($this->ownerDocument->createElement($tagName));
191 foreach ($attributes as $key => $value) $child->setAttribute($key, $value);
195 /// Adds any UTF-8 string as content of the element - it will be escaped.
196 function appendText(string $text) {
197 return $this->appendChild($this->ownerDocument->createTextNode($text));
200 // Appends a CDATASections to the element. This can be used to include
201 // raw (unparsed) HTML to the DOM tree as it is necessary because
202 // $parser->recursiveTagParse does not always escape & characters.
203 // (see https://bugzilla.wikimedia.org/show_bug.cgi?id=55526 )
204 // Workaround: Use a CDATA section. When serializing with $doc->saveHTML,
205 // the <![CDATA[...]]> is returned as ... .
206 // However, we end up having unescaped & in the output due to this bug in recursiveTagParse.
207 function appendCDATA($data) {
208 return $this->appendChild($this->ownerDocument->createCDATASection($data));
217 // gets coordinates and returns an array of lon/lat coordinate pairs, e.g.
221 // array(array(11.87, 47.12), array(11.70, 47.13))
222 public static function geo_to_coordinates($input) {
224 $num_matches = preg_match_all('/\s*(\d+\.?\d*)\s*N?\s+(\d+\.?\d*)\s*E?\s*/', $input, $matches);
226 for ($i=0; $i!=$num_matches; ++$i) {
227 $result[] = array(floatval($matches[2][$i]), floatval($matches[1][$i]));
229 if (implode($matches[0]) != $input) throw new Exception(wfMessage('wrmap-error-coordinate-format', $input)->text());
234 /// Takes a page title from the wiki and returns an image (if available)
235 /// or Null. For image wiki pages, the image is the corresponding image,
236 /// for inns it's the image of the "Gasthausbox".
237 public static function wikipage_to_image(Title $title, int $width) {
238 $file = false; // File class or false
239 // for NS_FILE titles, use the corresponding file as image
240 if ($title->inNamespace(NS_FILE)) {
241 $file = MediaWikiServices::getInstance()->getRepoGroup()->findFile($title); // $file is a mediawiki File class or false
243 $categories = $title->getParentCategories(); // e.g. array('Kategorie:Rodelbahn' => 'Juifenalm')
244 $wgContLang = MediaWikiServices::getInstance()->getContentLanguage();
245 $key_sledrun = $wgContLang->getNSText(NS_CATEGORY) . ':Rodelbahn';
246 if (array_key_exists($key_sledrun, $categories)) {
247 // for sledrun titles use the image from the rodelbahnbox
248 $dbr = wfGetDB(DB_REPLICA);
249 $res = $dbr->select('wrsledruncache', 'image', array('page_id' => $title->getArticleID()), __METHOD__);
250 $image = $res->fetchRow();
251 if ($image && !is_null($image['image'])) $file = MediaWikiServices::getInstance()->getRepoGroup()->findFile($image['image']);
253 $key_inn = $wgContLang->getNSText(NS_CATEGORY) . ':Gasthaus';
254 if (array_key_exists($key_inn, $categories)) {
255 // for inn titles use the image from the gasthausbox
256 $dbr = wfGetDB(DB_REPLICA);
257 $res = $dbr->select('wrinncache', 'image', array('page_id' => $title->getArticleID()), __METHOD__);
258 $image = $res->fetchRow();
259 if ($image && !is_null($image['image'])) $file = MediaWikiServices::getInstance()->getRepoGroup()->findFile($image['image']);
262 if ($file === false) return Null;
263 if (!$file->canRender()) return Null;
264 $thumb_url = $file->createThumb($width, $width); // limit width and hight to $width
265 if (strlen($thumb_url) == 0) return Null;
270 // convert sledruns to geojson (https://datatracker.ietf.org/doc/html/rfc7946)
271 // Returns an array of features
272 public static function sledruns_to_json_features() {
273 $json_features = array(); // result
274 $dbr = wfGetDB(DB_REPLICA);
275 $res = $dbr->select(array('wrsledruncache', 'wrreportcache'), array('wrsledruncache.page_title', 'position_latitude', 'position_longitude', 'date_report', '`condition`'), array('show_in_overview', 'not under_construction'), __METHOD__, array(), array('wrreportcache' => array('left outer join', 'wrsledruncache.page_id=wrreportcache.page_id')));
276 while ($sledrun = $res->fetchRow()) {
277 $lat = $sledrun['position_latitude'];
278 $lon = $sledrun['position_longitude'];
279 if (is_null($lat) || is_null($lon)) continue;
280 $lat = floatval($lat);
281 $lon = floatval($lon);
282 $title = Title::newFromText($sledrun['page_title']);
283 $properties = array('type' => 'sledrun', 'name' => $title->getText(), 'wiki' => $sledrun['page_title']);
284 if (!is_null($sledrun['date_report'])) $properties['date_report'] = $sledrun['date_report'];
285 if (!is_null($sledrun['condition'])) $properties['condition'] = intval($sledrun['condition']);
286 $image_url = WrBaseMap::wikipage_to_image($title, 150);
287 if (!is_null($image_url)) $properties['thumb_url'] = $image_url;
288 $json_feature = array(
292 'coordinates' => array($lon, $lat)
294 'properties' => $properties
296 $json_features[] = $json_feature;
298 return $json_features;
302 // convert XML to geojson (http://www.geojson.org/geojson-spec.html)
303 // Returns an array of features
304 public static function xml_to_json_features($input) {
305 libxml_use_internal_errors(true); // without that, we get PHP Warnings if the $input is not well-formed
306 $xml = new SimpleXMLElement($input); // input
307 $whitespace = (string) $xml; // everything between <wrmap> and </wrmap> that's not a sub-element
308 if (strlen($whitespace) > 0 && !ctype_space($whitespace)) { // there must not be anythin except sub-elements or whitespace
309 throw new Exception(wfMessage('wrmap-error-invalid-text', trim($xml))->text());
311 $json_features = array(); // output
312 $point_types = array('gasthaus', 'haltestelle', 'parkplatz', 'achtung', 'foto', 'verleih', 'punkt');
313 $line_types = array('rodelbahn', 'gehweg', 'alternative', 'lift', 'anfahrt', 'linie');
314 foreach ($xml as $feature) {
315 $given_properties = array();
316 foreach ($feature->attributes() as $key => $value) $given_properties[] = $key;
318 // determine feature type
319 $is_point = in_array($feature->getName(), $point_types);
320 $is_line = in_array($feature->getName(), $line_types);
321 if (!$is_point && !$is_line) {
322 throw new Exception(wfMessage('wrmap-error-invalid-element', $feature->getName(), '<' . implode('>, <', array_merge($point_types, $line_types)) . '>')->text());
327 $properties = array('type' => $feature->getName());
328 $allowed_properties = array('name', 'wiki');
329 $wrong_properties = array_diff($given_properties, $allowed_properties);
330 if (count($wrong_properties) > 0) throw new Exception(wfMessage('wrmap-error-invalid-attribute', reset($wrong_properties), $feature->getName(), "'" . implode("', '", $allowed_properties) . "'")->text());
331 foreach ($given_properties as $property) {
332 $propval = (string) $feature[$property];
333 if ($property == 'wiki') {
334 $title = Title::newFromText($propval);
335 $file_url = WrBaseMap::wikipage_to_image($title, 200);
336 if (!is_null($file_url)) $properties['thumb_url'] = $file_url;
338 $properties[$property] = $propval;
340 $coordinates = WrBaseMap::geo_to_coordinates($feature);
341 if (count($coordinates) != 1) throw new Exception(wfMessage('wrmap-error-coordinate-count', $feature->getName())->text());
342 $json_feature = array(
346 'coordinates' => reset($coordinates)
348 'properties' => $properties
350 $json_features[] = $json_feature;
354 $properties = array('type' => $feature->getName());
355 $allowed_properties = array('farbe', 'dicke');
356 $wrong_properties = array_diff($given_properties, $allowed_properties);
357 if (count($wrong_properties) > 0) throw new Exception(wfMessage('wrmap-error-invalid-attribute', reset($wrong_properties), $feature->getName(), "'" . implode("', '", $allowed_properties) . "'")->text());
358 if (isset($feature['farbe'])) {
359 $color = (string) $feature['farbe']; // e.g. #a200b7
360 if (preg_match('/^#[0-9a-f]{6}$/i', $color) != 1)
361 throw new Exception(wfMessage('wrmap-error-line-color')->text());
362 $properties['strokeColor'] = $color;
364 if (isset($feature['dicke'])) {
365 $stroke_width = (int) $feature['dicke']; // e.g. 6
366 if (((string) $stroke_width) !== (string) $feature['dicke'])
367 throw new Exception(wfMessage('wrmap-error-line-width')->text());
368 $properties['strokeWidth'] = $stroke_width;
370 $json_feature = array(
373 'type' => 'LineString',
374 'coordinates' => WrBaseMap::geo_to_coordinates($feature)
376 'properties' => $properties
378 $json_features[] = $json_feature;
381 return $json_features;
385 /// Renders the <wrgmap> tag and the <wrmap> tag.
386 /// The WrBaseMap class would be the only class needed but as the function render() does not provide an argument
387 /// telling which tag name called the function, a trick with two inherited classes has to be used.
388 /// @param $content string - the content of the <wrgmap> tag
389 /// @param $args array - the array of attribute name/value pairs for the tag
390 /// @param $parser Parser - the MW Parser object for the current page
392 /// @return string - the html for rendering the map
393 public static function render($content, $args, $parser, $frame) {
394 // Unfortunately, $tagname is no argument of this function, therefore we have to use a trick with derived classes.
395 $tagname = strtolower(get_called_class()); // either wrmap or wrgmap
396 assert(in_array($tagname, array('wrmap', 'wrgmap')));
398 $parserOutput = $parser->getOutput();
399 $parserOutput->addModules(array('ext.wrmap'));
401 // append all sledruns as icon
402 $json_features = array();
403 $show_sledruns = ($tagname == 'wrgmap');
404 if ($show_sledruns) {
405 $json_features = array_merge($json_features, WrBaseMap::sledruns_to_json_features());
410 $properties = array();
411 if (isset($args['lat'])) $properties['lat'] = (float) $args['lat']; // latitude as float value
412 if (isset($args['lon'])) $properties['lon'] = (float) $args['lon']; // longitude as float value
413 if (isset($args['zoom'])) $properties['zoom'] = (int) $args['zoom']; // zoom as int value
414 if (isset($args['width'])) $properties['width'] = (int) $args['width']; // width as int value
415 if (isset($args['height'])) $properties['height'] = (int) $args['height']; // height as int value
417 // append all elements in the XML
418 $json_features = array_merge($json_features, WrBaseMap::xml_to_json_features('<wrmap>' . $content . '</wrmap>'));
419 } catch (Exception $e) {
420 $doc = new WrMapDOMDocument();
421 $doc->appendElement('div', array('class' => 'error'))->appendText('Fehler beim Parsen der Landkarte: ' . $e->getMessage());
422 return array($doc->saveHTML($doc->firstChild), 'markerType' => 'nowiki');
425 // create final geojson
427 'type' => 'FeatureCollection',
428 'features' => $json_features,
429 'properties' => $properties
431 $json_string = json_encode($json);
433 // Create <div/> element where the map is placed in
434 global $wgExtensionAssetsPath;
435 $doc = new WrMapDOMDocument();
436 $div_map = $doc->appendElement('div', array('class' => 'wrmap', 'style' => 'border-style:none;', 'data-ext-path' => "$wgExtensionAssetsPath/wrmap"));
438 $div_map->appendElement('div', array())->appendText(wfMessage('wrmap-loading')->text());
440 $div_map->appendElement('div', array('style' => 'height: 0px; display:none;'))->appendText($json_string);
442 $div_popup = $doc->appendElement('div', array('id' => 'popup', 'class' => 'ol-popup'));
443 $div_popup->appendElement('a', array('id' => 'popup-closer', 'href' => '#', 'class' => 'ol-popup-closer'));
444 $div_popup->appendElement('div', array('id' => 'popup-content'));
445 return array($doc->saveHTML($div_map) . $doc->saveHTML($div_popup), 'markerType' => 'nowiki');
451 class WrMap extends WrBaseMap {
452 public static function onParserFirstCallInit(Parser $parser) {
453 $parser->setHook('wrmap', 'WrMap::render');
460 class WrGMap extends WrBaseMap {
461 public static function onParserFirstCallInit(Parser $parser) {
462 $parser->setHook('wrgmap', 'WrGMap::render');