]> ToastFreeware Gitweb - philipp/winterrodeln/mediawiki_extensions/wrmap.git/blob - wrmap.body.php
Support map from Swiss OpenStreetMap Association.
[philipp/winterrodeln/mediawiki_extensions/wrmap.git] / wrmap.body.php
1 <?php
2 use MediaWiki\MediaWikiServices;
3
4
5 // DOM helper classes
6 // ------------------
7
8 // The following two classes are "duplicated" from the wrreport extension to keep them separate.
9 // Put improvements in both classes.
10 class WrMapDOMDocument extends DOMDocument {
11         function __construct() {
12                 parent::__construct('1.0', 'utf-8');
13                 $this->registerNodeClass('DOMElement', 'WrMapDOMElement');
14         }
15
16         /// Creates and adds the element with the given tag name and returns it.
17         /// Additionally, it calls setAttribute($key, $value) for every entry
18         /// in $attributes.
19         function appendElement(string $tagName, $attributes=array()): WrMapDOMElement {
20                 $child = $this->appendChild($this->createElement($tagName));
21                 foreach ($attributes as $key => $value) $child->setAttribute($key, $value);
22                 return $child;
23         }
24 }
25
26
27 class WrMapDOMElement extends DOMElement {
28
29         /// Creates and adds the element with the given tag name and returns it
30         /// Additionally, it calls setAttribute($key, $value) for every entry
31         /// in $attributes.
32         function appendElement(string $tagName, $attributes=array()): WrMapDOMElement {
33                 $child = $this->appendChild($this->ownerDocument->createElement($tagName));
34                 foreach ($attributes as $key => $value) $child->setAttribute($key, $value);
35                 return $child;
36         }
37
38         /// Adds any UTF-8 string as content of the element - it will be escaped.
39         function appendText(string|NULL $text) {
40                 return $this->appendChild($this->ownerDocument->createTextNode($text));
41         }
42
43         // Appends a CDATASections to the element. This can be used to include
44         // raw (unparsed) HTML to the DOM tree as it is necessary because
45         // $parser->recursiveTagParse does not always escape & characters.
46         // (see https://bugzilla.wikimedia.org/show_bug.cgi?id=55526 )
47         // Workaround: Use a CDATA section. When serializing with $doc->saveHTML,
48         // the <![CDATA[...]]> is returned as ... .
49         // However, we end up having unescaped & in the output due to this bug in recursiveTagParse.
50         function appendCDATA($data) {
51                 return $this->appendChild($this->ownerDocument->createCDATASection($data));
52         }
53 }
54
55
56 // WrBaseMap
57 // ---------
58
59 class WrBaseMap {
60         // gets coordinates and returns an array of lon/lat coordinate pairs, e.g.
61         // 47.12 N 11.87 E
62         // 47.13 N 11.70 E
63         // ->
64         // array(array(11.87, 47.12), array(11.70, 47.13))
65         public static function geo_to_coordinates($input) {
66                 $matches = array();
67                 $num_matches = preg_match_all('/\s*(\d+\.?\d*)\s*N?\s+(\d+\.?\d*)\s*E?\s*/', $input, $matches);
68                 $result = array();
69                 for ($i=0; $i!=$num_matches; ++$i) {
70                         $result[] = array(floatval($matches[2][$i]), floatval($matches[1][$i]));
71                 }
72                 if (implode($matches[0]) != $input) throw new Exception(wfMessage('wrmap-error-coordinate-format', $input)->text());
73                 return $result;
74         }
75
76
77         /// Takes a page title from the wiki and returns an image (if available)
78         /// or Null. For image wiki pages, the image is the corresponding image,
79         /// for inns it's the image of the "Gasthausbox".
80         public static function wikipage_to_image(Title $title, int $width) {
81                 $file = false; // File class or false
82                 // for NS_FILE titles, use the corresponding file as image
83                 if ($title->inNamespace(NS_FILE)) {
84                         $file = MediaWikiServices::getInstance()->getRepoGroup()->findFile($title); // $file is a mediawiki File class or false
85                 } else {
86                         $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
87                         $categories = $title->getParentCategories(); // e.g. array('Kategorie:Rodelbahn' => 'Juifenalm')
88                         $wgContLang = MediaWikiServices::getInstance()->getContentLanguage();
89                         $key_sledrun = $wgContLang->getNSText(NS_CATEGORY) . ':Rodelbahn';
90                         if (array_key_exists($key_sledrun, $categories)) {
91                                 // for sledrun titles use the image from the rodelbahnbox
92                                 $dbr = $lb->getConnection( DB_REPLICA );
93                                 $res = $dbr->select('wrsledruncache', 'image', array('page_id' => $title->getArticleID()), __METHOD__);
94                                 $image = $res->fetchRow();
95                                 if ($image && !is_null($image['image'])) $file = MediaWikiServices::getInstance()->getRepoGroup()->findFile($image['image']);
96                         }
97                         $key_inn = $wgContLang->getNSText(NS_CATEGORY) . ':Gasthaus';
98                         if (array_key_exists($key_inn, $categories)) {
99                                 // for inn titles use the image from the gasthausbox
100                                 $dbr = $lb->getConnection( DB_REPLICA );
101                                 $res = $dbr->select('wrinncache', 'image', array('page_id' => $title->getArticleID()), __METHOD__);
102                                 $image = $res->fetchRow();
103                                 if ($image && !is_null($image['image'])) $file = MediaWikiServices::getInstance()->getRepoGroup()->findFile($image['image']);
104                         }
105                 }
106                 if ($file === false) return Null;
107                 if (!$file->canRender()) return Null;
108                 $thumb_url = $file->createThumb($width, $width); // limit width and hight to $width
109                 if (strlen($thumb_url) == 0) return Null;
110                 return $thumb_url;
111         }
112
113
114         // convert sledruns to geojson (https://datatracker.ietf.org/doc/html/rfc7946)
115         // Returns an array of features
116         public static function sledruns_to_json_features() {
117                 $json_features = array(); // result
118                 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
119                 $dbr = $lb->getConnection( DB_REPLICA );
120                 $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')));
121                 while ($sledrun = $res->fetchRow()) {
122                         $lat = $sledrun['position_latitude'];
123                         $lon = $sledrun['position_longitude'];
124                         if (is_null($lat) || is_null($lon)) continue;
125                         $lat = floatval($lat);
126                         $lon = floatval($lon);
127                         $title = Title::newFromText($sledrun['page_title']);
128                         $properties = array('type' => 'sledrun', 'name' => $title->getText(), 'wiki' => $sledrun['page_title']);
129                         if (!is_null($sledrun['date_report'])) $properties['date_report'] = $sledrun['date_report'];
130                         if (!is_null($sledrun['condition'])) $properties['condition'] = intval($sledrun['condition']);
131                         $image_url = WrBaseMap::wikipage_to_image($title, 150);
132                         if (!is_null($image_url)) $properties['thumb_url'] = $image_url;
133                         $json_feature = array(
134                                 'type' => 'Feature',
135                                 'geometry' => array(
136                                         'type' => 'Point',
137                                         'coordinates' => array($lon, $lat)
138                                 ),
139                                 'properties' => $properties
140                         );
141                         $json_features[] = $json_feature;
142                 }
143                 return $json_features;
144         }
145
146
147         // convert XML to geojson (http://www.geojson.org/geojson-spec.html)
148         // Returns an array of features
149         public static function xml_to_json_features($input) {
150                 libxml_use_internal_errors(true); // without that, we get PHP Warnings if the $input is not well-formed
151                 $xml = new SimpleXMLElement($input); // input
152                 $whitespace = (string) $xml; // everything between <wrmap> and </wrmap> that's not a sub-element
153                 if (strlen($whitespace) > 0 && !ctype_space($whitespace)) { // there must not be anythin except sub-elements or whitespace
154                         throw new Exception(wfMessage('wrmap-error-invalid-text', trim($xml))->text());
155                 }
156                 $json_features = array(); // output
157                 $point_types = array('gasthaus', 'haltestelle', 'parkplatz', 'achtung', 'foto', 'verleih', 'punkt');
158                 $line_types = array('rodelbahn', 'gehweg', 'alternative', 'lift', 'anfahrt', 'linie');
159                 foreach ($xml as $feature) {
160                         $given_properties = array();
161                         foreach ($feature->attributes() as $key => $value) $given_properties[] = $key;
162
163                         // determine feature type
164                         $is_point = in_array($feature->getName(), $point_types);
165                         $is_line = in_array($feature->getName(), $line_types);
166                         if (!$is_point && !$is_line) {
167                                 throw new Exception(wfMessage('wrmap-error-invalid-element', $feature->getName(), '<' . implode('>, <', array_merge($point_types, $line_types)) . '>')->text());
168                         }
169
170                         // point
171                         if ($is_point) {
172                                 $properties = array('type' => $feature->getName());
173                                 $allowed_properties = array('name', 'wiki');
174                                 $wrong_properties = array_diff($given_properties, $allowed_properties);
175                                 if (count($wrong_properties) > 0) throw new Exception(wfMessage('wrmap-error-invalid-attribute',  reset($wrong_properties), $feature->getName(), "'" . implode("', '", $allowed_properties) . "'")->text());
176                                 foreach ($given_properties as $property) {
177                                         $propval = (string) $feature[$property];
178                                         if ($property == 'wiki') {
179                                                 $title = Title::newFromText($propval);
180                                                 $file_url = WrBaseMap::wikipage_to_image($title, 200);
181                                                 if (!is_null($file_url)) $properties['thumb_url'] = $file_url;
182                                         }
183                                         $properties[$property] = $propval;
184                                 }
185                                 $coordinates = WrBaseMap::geo_to_coordinates($feature);
186                                 if (count($coordinates) != 1) throw new Exception(wfMessage('wrmap-error-coordinate-count', $feature->getName())->text());
187                                 $json_feature = array(
188                                         'type' => 'Feature',
189                                         'geometry' => array(
190                                                 'type' => 'Point',
191                                                 'coordinates' => reset($coordinates)
192                                         ),
193                                         'properties' => $properties
194                                 );
195                                 $json_features[] = $json_feature;
196                         }
197                         // line
198                         if ($is_line) {
199                                 $properties = array('type' => $feature->getName());
200                                 $allowed_properties = array('farbe', 'dicke');
201                                 $wrong_properties = array_diff($given_properties, $allowed_properties);
202                                 if (count($wrong_properties) > 0) throw new Exception(wfMessage('wrmap-error-invalid-attribute',  reset($wrong_properties), $feature->getName(), "'" . implode("', '", $allowed_properties) . "'")->text());
203                                 if (isset($feature['farbe'])) {
204                                         $color = (string) $feature['farbe']; // e.g. #a200b7
205                                         if (preg_match('/^#[0-9a-f]{6}$/i', $color) != 1)
206                                                 throw new Exception(wfMessage('wrmap-error-line-color')->text());
207                                         $properties['strokeColor'] = $color;
208                                 }
209                                 if (isset($feature['dicke'])) {
210                                         $stroke_width = (int) $feature['dicke']; // e.g. 6
211                                         if (((string) $stroke_width) !== (string) $feature['dicke'])
212                                                 throw new Exception(wfMessage('wrmap-error-line-width')->text());
213                                         $properties['strokeWidth'] = $stroke_width;
214                                 }
215                                 $json_feature = array(
216                                         'type' => 'Feature',
217                                         'geometry' => array(
218                                                 'type' => 'LineString',
219                                                 'coordinates' => WrBaseMap::geo_to_coordinates($feature)
220                                         ),
221                                         'properties' => $properties
222                                 );
223                                 $json_features[] = $json_feature;
224                         }
225                 }
226                 return $json_features;
227         }
228
229
230         /// Renders the <wrgmap> tag and the <wrmap> tag.
231         /// The WrBaseMap class would be the only class needed but as the function render() does not provide an argument
232         /// telling which tag name called the function, a trick with two inherited classes has to be used.
233         /// @param $content string - the content of the <wrgmap> tag
234         /// @param $args array - the array of attribute name/value pairs for the tag
235         /// @param $parser Parser - the MW Parser object for the current page
236         ///
237         /// @return string - the html for rendering the map
238         public static function render($content, $args, $parser, $frame) {
239                 // Unfortunately, $tagname is no argument of this function, therefore we have to use a trick with derived classes.
240                 $tagname = strtolower(get_called_class()); // either wrmap or wrgmap
241                 assert(in_array($tagname, array('wrmap', 'wrgmap')));
242
243                 $parserOutput = $parser->getOutput();
244                 $parserOutput->addModules(array('ext.wrmap'));
245
246                 // append all sledruns as icon
247                 $json_features = array();
248                 $show_sledruns = ($tagname == 'wrgmap');
249                 if ($show_sledruns) {
250                         $json_features = array_merge($json_features, WrBaseMap::sledruns_to_json_features());
251                 }
252
253                 try {
254                         // map properties
255                         $properties = array();
256                         if (isset($args['lat'])) $properties['lat'] = (float) $args['lat']; // latitude as float value
257                         if (isset($args['lon'])) $properties['lon'] = (float) $args['lon']; // longitude as float value
258                         if (isset($args['zoom'])) $properties['zoom'] = (int) $args['zoom']; // zoom as int value
259                         if (isset($args['width'])) $properties['width'] = (int) $args['width']; // width as int value
260                         if (isset($args['height'])) $properties['height'] = (int) $args['height']; // height as int value
261
262                         // append all elements in the XML
263                         $json_features = array_merge($json_features, WrBaseMap::xml_to_json_features('<wrmap>' . $content . '</wrmap>'));
264                 } catch (Exception $e) {
265                         $doc = new WrMapDOMDocument();
266                         $doc->appendElement('div', array('class' => 'error'))->appendText('Fehler beim Parsen der Landkarte: ' . $e->getMessage());
267                         return array($doc->saveHTML($doc->firstChild), 'markerType' => 'nowiki');
268                 }
269
270                 // create final geojson
271                 $json = array(
272                         'type' => 'FeatureCollection',
273                         'features' => $json_features,
274                         'wr_properties' => $properties
275                 );
276                 $json_string = json_encode($json);
277
278                 // Create <div/> element where the map is placed in
279                 global $wgExtensionAssetsPath;
280                 $doc = new WrMapDOMDocument();
281                 $div_map = $doc->appendElement('div', array('class' => 'wrmap', 'style' => 'border-style:none;', 'data-ext-path' => "$wgExtensionAssetsPath/wrmap"));
282                 // progress message
283                 $div_map->appendElement('div', array())->appendText(wfMessage('wrmap-loading')->text());
284                 // data
285                 $div_map->appendElement('div', array('style' => 'height: 0px; display:none;'))->appendText($json_string);
286                 return array($doc->saveHTML($div_map), 'markerType' => 'nowiki');
287         }
288 }
289
290
291 // <wrmap> tag
292 class WrMap extends WrBaseMap {
293         public static function onParserFirstCallInit(Parser $parser) {
294                 $parser->setHook('wrmap', 'WrMap::render');
295                 return true;
296         }
297 }
298
299
300 // <wrgmap> tag
301 class WrGMap extends WrBaseMap {
302         public static function onParserFirstCallInit(Parser $parser) {
303                 $parser->setHook('wrgmap', 'WrGMap::render');
304                 return true;
305         }
306 }
307
308 ?>