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.
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
161 // DOM helper classes
162 // ------------------
164 // The following two classes are "duplicated" from the wrreport extension to keep them separate.
165 // Put improvements in both classes.
166 class WrMapDOMDocument extends DOMDocument {
167 function __construct() {
168 parent::__construct('1.0', 'utf-8');
169 $this->registerNodeClass('DOMElement', 'WrMapDOMElement');
172 /// Creates and adds the element with the given tag name and returns it.
173 /// Additionally, it calls setAttribute($key, $value) for every entry
175 function appendElement($tagName, $attributes=array()) {
176 $child = $this->appendChild($this->createElement($tagName));
177 foreach ($attributes as $key => $value) $child->setAttribute($key, $value);
183 class WrMapDOMElement extends DOMElement {
185 /// Creates and adds the element with the given tag name and returns it
186 /// Additionally, it calls setAttribute($key, $value) for every entry
188 function appendElement($tagName, $attributes=array()) {
189 $child = $this->appendChild($this->ownerDocument->createElement($tagName));
190 foreach ($attributes as $key => $value) $child->setAttribute($key, $value);
194 /// Adds any UTF-8 string as content of the element - it will be escaped.
195 function appendText($text) {
196 return $this->appendChild($this->ownerDocument->createTextNode($text));
199 // Appends a CDATASections to the element. This can be used to include
200 // raw (unparsed) HTML to the DOM tree as it is necessary because
201 // $parser->recursiveTagParse does not always escape & characters.
202 // (see https://bugzilla.wikimedia.org/show_bug.cgi?id=55526 )
203 // Workaround: Use a CDATA section. When serializing with $doc->saveHTML,
204 // the <![CDATA[...]]> is returned as ... .
205 // However, we end up having unescaped & in the output due to this bug in recursiveTagParse.
206 function appendCDATA($data) {
207 return $this->appendChild($this->ownerDocument->createCDATASection($data));
216 // gets coordinates and returns an array of lon/lat coordinate pairs, e.g.
220 // array(array(11.87, 47.12), array(11.70, 47.13))
221 public static function geo_to_coordinates($input) {
223 $num_matches = preg_match_all('/\s*(\d+\.?\d*)\s*N?\s+(\d+\.?\d*)\s*E?\s*/', $input, $matches);
225 for ($i=0; $i!=$num_matches; ++$i) {
226 $result[] = array(floatval($matches[2][$i]), floatval($matches[1][$i]));
228 if (implode($matches[0]) != $input) throw new Exception(wfMessage('wrmap-error-coordinate-format', $input)->text());
233 /// Takes a page title from the wiki and returns an image (if available)
234 /// or Null. For image wiki pages, the image is the corresponding image,
235 /// for inns it's the image of the "Gasthausbox".
236 public static function wikipage_to_image($title, $width) {
237 $file = false; // File class or false
238 // for NS_FILE titles, use the corresponding file as image
239 if ($title->getNamespace() == NS_FILE) {
240 $file = wfFindFile($title); // $file is a mediawiki File class or false
242 $categories = $title->getParentCategories(); // e.g. array('Kategorie:Rodelbahn' => 'Juifenalm')
244 $key_sledrun = $wgContLang->getNSText(NS_CATEGORY) . ':Rodelbahn';
245 if (array_key_exists($key_sledrun, $categories)) {
246 // for sledrun titles use the image from the rodelbahnbox
247 $dbr = wfGetDB(DB_SLAVE);
248 $res = $dbr->select('wrsledruncache', 'image', array('page_id' => $title->getArticleID()), __METHOD__);
249 $image = $dbr->fetchRow($res);
250 if ($image && !is_null($image['image'])) $file = wfFindFile($image['image']);
251 $dbr->freeResult($res);
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_SLAVE);
257 $res = $dbr->select('wrinncache', 'image', array('page_id' => $title->getArticleID()), __METHOD__);
258 $image = $dbr->fetchRow($res);
259 if ($image && !is_null($image['image'])) $file = wfFindFile($image['image']);
260 $dbr->freeResult($res);
263 if ($file === false) return Null;
264 if (!$file->canRender()) return Null;
265 $thumb_url = $file->createThumb($width, $width); // limit width and hight to $width
266 if (strlen($thumb_url) == 0) return Null;
271 // convert sledruns to geojson (http://www.geojson.org/geojson-spec.html)
272 // Returns an array of features
273 public static function sledruns_to_json_features() {
274 $json_features = array(); // result
275 $dbr = wfGetDB(DB_SLAVE);
276 $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')));
277 while ($sledrun = $dbr->fetchRow($res)) {
278 $lat = $sledrun['position_latitude'];
279 $lon = $sledrun['position_longitude'];
280 if (is_null($lat) || is_null($lon)) continue;
281 $lat = floatval($lat);
282 $lon = floatval($lon);
283 $title = Title::newFromText($sledrun['page_title']);
284 $properties = array('type' => 'sledrun', 'name' => $title->getText(), 'wiki' => $title->getLocalUrl());
285 if (!is_null($sledrun['date_report'])) $properties['date_report'] = $sledrun['date_report'];
286 if (!is_null($sledrun['condition'])) $properties['condition'] = intval($sledrun['condition']);
287 $image_url = WrBaseMap::wikipage_to_image($title, 150);
288 if (!is_null($image_url)) $properties['thumb_url'] = $image_url;
289 $json_feature = array(
293 'coordinates' => array($lon, $lat)
295 'properties' => $properties
297 $json_features[] = $json_feature;
299 $dbr->freeResult($res);
300 return $json_features;
304 // convert XML to geojson (http://www.geojson.org/geojson-spec.html)
305 // Returns an array of features
306 public static function xml_to_json_features($input) {
307 libxml_use_internal_errors(true); // without that, we get PHP Warnings if the $input is not well-formed
308 $xml = new SimpleXMLElement($input); // input
309 $whitespace = (string) $xml; // everything between <wrmap> and </wrmap> that's not a sub-element
310 if (strlen($whitespace) > 0 && !ctype_space($whitespace)) { // there must not be anythin except sub-elements or whitespace
311 throw new Exception(wfMessage('wrmap-error-invalid-text', trim($xml))->text());
313 $json_features = array(); // output
314 $point_types = array('gasthaus', 'haltestelle', 'parkplatz', 'achtung', 'foto', 'verleih', 'punkt');
315 $line_types = array('rodelbahn', 'gehweg', 'alternative', 'lift', 'anfahrt', 'linie');
316 foreach ($xml as $feature) {
317 $given_properties = array();
318 foreach ($feature->attributes() as $key => $value) $given_properties[] = $key;
320 // determine feature type
321 $is_point = in_array($feature->getName(), $point_types);
322 $is_line = in_array($feature->getName(), $line_types);
323 if (!$is_point && !$is_line) {
324 throw new Exception(wfMessage('wrmap-error-invalid-element', $feature->getName(), '<' . implode('>, <', array_merge($point_types, $line_types)) . '>')->text());
329 $properties = array('type' => $feature->getName());
330 $allowed_properties = array('name', 'wiki');
331 $wrong_properties = array_diff($given_properties, $allowed_properties);
332 if (count($wrong_properties) > 0) throw new Exception(wfMessage('wrmap-error-invalid-attribute', reset($wrong_properties), $feature->getName(), "'" . implode("', '", $allowed_properties) . "'")->text());
333 foreach ($given_properties as $property) {
334 $propval = (string) $feature[$property];
335 if ($property == 'wiki') {
336 $title = Title::newFromText($propval);
337 $propval = $title->getLocalUrl();
338 $file_url = WrBaseMap::wikipage_to_image($title, 200);
339 if (!is_null($file_url)) $properties['thumb_url'] = $file_url;
341 $properties[$property] = $propval;
343 $coordinates = WrBaseMap::geo_to_coordinates($feature);
344 if (count($coordinates) != 1) throw new Exception(wfMessage('wrmap-error-coordinate-count', $feature->getName())->text());
345 $json_feature = array(
349 'coordinates' => reset($coordinates)
351 'properties' => $properties
353 $json_features[] = $json_feature;
357 $properties = array('type' => $feature->getName());
358 $allowed_properties = array('farbe', 'dicke');
359 $wrong_properties = array_diff($given_properties, $allowed_properties);
360 if (count($wrong_properties) > 0) throw new Exception(wfMessage('wrmap-error-invalid-attribute', reset($wrong_properties), $feature->getName(), "'" . implode("', '", $allowed_properties) . "'")->text());
361 if (isset($feature['farbe'])) {
362 $color = (string) $feature['farbe']; // e.g. #a200b7
363 if (preg_match('/^#[0-9a-f]{6}$/i', $color) != 1)
364 throw new Exception(wfMessage('wrmap-error-line-color')->text());
365 $properties['strokeColor'] = $color;
367 if (isset($feature['dicke'])) {
368 $stroke_width = (int) $feature['dicke']; // e.g. 6
369 if (((string) $stroke_width) !== (string) $feature['dicke'])
370 throw new Exception(wfMessage('wrmap-error-line-width')->text());
371 $properties['strokeWidth'] = $stroke_width;
373 $json_feature = array(
376 'type' => 'LineString',
377 'coordinates' => WrBaseMap::geo_to_coordinates($feature)
379 'properties' => $properties
381 $json_features[] = $json_feature;
384 return $json_features;
388 /// Renders the <wrgmap> tag and the <wrmap> tag.
389 /// The WrBaseMap class would be the only class needed but as the function render() does not provide an argument
390 /// telling which tag name called the function, a trick with two inherited classes has to be used.
391 /// @param $content string - the content of the <wrgmap> tag
392 /// @param $args array - the array of attribute name/value pairs for the tag
393 /// @param $parser Parser - the MW Parser object for the current page
395 /// @return string - the html for rendering the map
396 public static function render($content, $args, $parser, $frame) {
397 // Unfortunately, $tagname is no argument of this function, therefore we have to use a trick with derived classes.
398 $tagname = strtolower(get_called_class()); // either wrmap or wrgmap
399 assert(in_array($tagname, array('wrmap', 'wrgmap')));
401 $parserOutput = $parser->getOutput();
402 // Polyfill für Internet Explorer
403 $parserOutput->addHeadItem('<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,fetch"></script>', 'polyfill_ie');
404 // OpenLayers 6.5.0 does not work with Internet Explorer, see https://github.com/openlayers/openlayers/issues/11870
405 $parserOutput->addHeadItem('<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.4.3/build/ol.js"></script>', 'openlayers_js');
406 $parserOutput->addHeadItem('<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.5.0/css/ol.css">', 'openlayers_css');
407 $parserOutput->addModules('ext.wrmap');
409 // append all sledruns as icon
410 $json_features = array();
411 $show_sledruns = ($tagname == 'wrgmap');
412 if ($show_sledruns) {
413 $json_features = array_merge($json_features, WrBaseMap::sledruns_to_json_features());
418 $properties = array();
419 if (isset($args['lat'])) $properties['lat'] = (float) $args['lat']; // latitude as float value
420 if (isset($args['lon'])) $properties['lon'] = (float) $args['lon']; // longitude as float value
421 if (isset($args['zoom'])) $properties['zoom'] = (int) $args['zoom']; // zoom as int value
422 if (isset($args['width'])) $properties['width'] = (int) $args['width']; // width as int value
423 if (isset($args['height'])) $properties['height'] = (int) $args['height']; // height as int value
425 // append all elements in the XML
426 $json_features = array_merge($json_features, WrBaseMap::xml_to_json_features('<wrmap>' . $content . '</wrmap>'));
427 } catch (Exception $e) {
428 $doc = new WrMapDOMDocument();
429 $doc->appendElement('div', array('class' => 'error'))->appendText('Fehler beim Parsen der Landkarte: ' . $e->getMessage());
430 return array($doc->saveHTML($doc->firstChild), 'markerType' => 'nowiki');
433 // create final geojson
435 'type' => 'FeatureCollection',
436 'features' => $json_features,
437 'properties' => $properties
439 $json_string = json_encode($json);
441 // Create <div/> element where the map is placed in
442 global $wgExtensionAssetsPath;
443 $doc = new WrMapDOMDocument();
444 $div_map = $doc->appendElement('div', array('class' => 'wrmap', 'style' => 'border-style:none;', 'data-ext-path' => "$wgExtensionAssetsPath/wrmap"));
446 $div_map->appendElement('div', array())->appendText(wfMessage('wrmap-loading')->text());
448 $div_map->appendElement('div', array('style' => 'height: 0px; display:none;'))->appendText($json_string);
450 $div_popup = $doc->appendElement('div', array('id' => 'popup', 'class' => 'ol-popup'));
451 $div_popup->appendElement('a', array('id' => 'popup-closer', 'href' => '#', 'class' => 'ol-popup-closer'));
452 $div_popup->appendElement('div', array('id' => 'popup-content'));
453 return array($doc->saveHTML($div_map) . $doc->saveHTML($div_popup), 'markerType' => 'nowiki');
459 class WrMap extends WrBaseMap {
460 public static function onParserFirstCallInit(Parser $parser) {
461 $parser->setHook('wrmap', 'WrMap::render');
468 class WrGMap extends WrBaseMap {
469 public static function onParserFirstCallInit(Parser $parser) {
470 $parser->setHook('wrgmap', 'WrGMap::render');