6 // The following two classes are "duplicated" from the wrreport extension to keep them separate.
7 // Put improvements in both classes.
8 class WrMapDOMDocument extends DOMDocument {
9 function __construct() {
10 parent::__construct('1.0', 'utf-8');
11 $this->registerNodeClass('DOMElement', 'WrMapDOMElement');
14 /// Creates and adds the element with the given tag name and returns it.
15 /// Additionally, it calls setAttribute($key, $value) for every entry
17 function appendElement($tagName, $attributes=array()) {
18 $child = $this->appendChild($this->createElement($tagName));
19 foreach ($attributes as $key => $value) $child->setAttribute($key, $value);
25 class WrMapDOMElement extends DOMElement {
27 /// Creates and adds the element with the given tag name and returns it
28 /// Additionally, it calls setAttribute($key, $value) for every entry
30 function appendElement($tagName, $attributes=array()) {
31 $child = $this->appendChild($this->ownerDocument->createElement($tagName));
32 foreach ($attributes as $key => $value) $child->setAttribute($key, $value);
36 /// Adds any UTF-8 string as content of the element - it will be escaped.
37 function appendText($text) {
38 return $this->appendChild($this->ownerDocument->createTextNode($text));
41 // Appends a CDATASections to the element. This can be used to include
42 // raw (unparsed) HTML to the DOM tree as it is necessary because
43 // $parser->recursiveTagParse does not always escape & characters.
44 // (see https://bugzilla.wikimedia.org/show_bug.cgi?id=55526 )
45 // Workaround: Use a CDATA section. When serializing with $doc->saveHTML,
46 // the <![CDATA[...]]> is returned as ... .
47 // However, we end up having unescaped & in the output due to this bug in recursiveTagParse.
48 function appendCDATA($data) {
49 return $this->appendChild($this->ownerDocument->createCDATASection($data));
58 // gets coordinates and returns an array of lon/lat coordinate pairs, e.g.
62 // array(array(11.87, 47.12), array(11.70, 47.13))
63 public static function geo_to_coordinates($input) {
65 $num_matches = preg_match_all('/\s*(\d+\.?\d*)\s*N?\s+(\d+\.?\d*)\s*E?\s*/', $input, $matches);
67 for ($i=0; $i!=$num_matches; ++$i) {
68 $result[] = array(floatval($matches[2][$i]), floatval($matches[1][$i]));
70 if (implode($matches[0]) != $input) throw new Exception('Falsches Koordinatenformat: ' . $input);
75 /// Takes a page title from the wiki and returns an image (if available)
76 /// or Null. For image wiki pages, the image is the corresponding image,
77 /// for inns it's the image of the "Gasthausbox".
78 public static function wikipage_to_image($title, $width) {
79 $file = false; // File class or false
80 // for NS_FILE titles, use the corresponding file as image
81 if ($title->getNamespace() == NS_FILE) {
82 $file = wfFindFile($title); // $file is a mediawiki File class or false
84 $categories = $title->getParentCategories(); // e.g. array('Kategorie:Rodelbahn' => 'Juifenalm')
86 $key_sledrun = $wgContLang->getNSText(NS_CATEGORY) . ':Rodelbahn';
87 if (array_key_exists($key_sledrun, $categories)) {
88 // for sledrun titles use the image from the rodelbahnbox
91 $key_inn = $wgContLang->getNSText(NS_CATEGORY) . ':Gasthaus';
92 if (array_key_exists($key_inn, $categories)) {
93 // for inn titles use the image from the gasthausbox
94 $dbr = wfGetDB(DB_SLAVE);
95 $res = $dbr->select('wrinncache', 'image', array('page_id' => $title->getArticleID()), __METHOD__);
96 $image = $dbr->fetchRow($res);
97 if ($image && !is_null($image['image'])) $file = wfFindFile($image['image']);
98 $dbr->freeResult($res);
101 if ($file === false) return Null;
102 if (!$file->canRender()) return Null;
103 $thumb_url = $file->createThumb($width, $width); // limit width and hight to $width
104 if (strlen($thumb_url) == 0) return Null;
109 // convert sledruns to geojson (http://www.geojson.org/geojson-spec.html)
110 // Returns an array of features
111 public static function sledruns_to_json_features() {
112 $json_features = array(); // result
113 $dbr = wfGetDB(DB_SLAVE);
114 $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')));
115 while ($sledrun = $dbr->fetchRow($res)) {
116 $lat = $sledrun['position_latitude'];
117 $lon = $sledrun['position_longitude'];
118 if (is_null($lat) || is_null($lon)) continue;
119 $lat = floatval($lat);
120 $lon = floatval($lon);
121 $title = Title::newFromText($sledrun['page_title']);
122 $properties = array('type' => 'sledrun', 'name' => $title->getText(), 'wiki' => $title->getLocalUrl());
123 if (!is_null($sledrun['date_report'])) $properties['date_report'] = $sledrun['date_report'];
124 if (!is_null($sledrun['condition'])) $properties['condition'] = intval($sledrun['condition']);
125 $json_feature = array(
129 'coordinates' => array($lon, $lat)
131 'properties' => $properties
133 $json_features[] = $json_feature;
135 $dbr->freeResult($res);
136 return $json_features;
140 // convert XML to geojson (http://www.geojson.org/geojson-spec.html)
141 // Returns an array of features
142 public static function xml_to_json_features($input) {
143 libxml_use_internal_errors(true); // without that, we get PHP Warnings if the $input is not well-formed
144 $xml = new SimpleXMLElement($input); // input
145 $whitespace = (string) $xml; // everything between <wrmap> and </wrmap> that's not a sub-element
146 if (strlen($whitespace) > 0 && !ctype_space($whitespace)) { // there must not be anythin except sub-elements or whitespace
147 throw new Exception('Die Landkarte enthält folgenden ungültigen Text: "' . trim($xml) . '".');
149 $json_features = array(); // output
150 $point_types = array('gasthaus', 'haltestelle', 'parkplatz', 'achtung', 'foto', 'punkt');
151 $line_types = array('rodelbahn', 'gehweg', 'alternative', 'lift', 'anfahrt', 'linie');
152 foreach ($xml as $feature) {
153 $given_properties = array();
154 foreach ($feature->attributes() as $key => $value) $given_properties[] = $key;
156 // determine feature type
157 $is_point = in_array($feature->getName(), $point_types);
158 $is_line = in_array($feature->getName(), $line_types);
159 if (!$is_point && !$is_line) {
160 throw new Exception('Unbekanntes Element <' . $feature->getName() . '>. Erlaubt sind: <' . implode('>, <', array_merge($point_types, $line_types)) . '>.');
165 $properties = array('type' => $feature->getName());
166 $allowed_properties = array('name', 'wiki');
167 $wrong_properties = array_diff($given_properties, $allowed_properties);
168 if (count($wrong_properties) > 0) throw new Exception("Das Attribut '" . reset($wrong_properties) . "' ist nicht erlaubt bei <" . $feature->getName() . ">. Erlaubt sind: '" . implode("', '", $allowed_properties) . "'.");
169 foreach ($given_properties as $property) {
170 $propval = (string) $feature[$property];
171 if ($property == 'wiki') {
172 $title = Title::newFromText($propval);
173 $propval = $title->getLocalUrl();
174 $file_url = WrBaseMap::wikipage_to_image($title, 200);
175 if (!is_null($file_url)) $properties['thumb_url'] = $file_url;
177 $properties[$property] = $propval;
179 $coordinates = WrBaseMap::geo_to_coordinates($feature);
180 if (count($coordinates) != 1) throw new Exception('Das Element <' . $feature->getName() . '> muss genau ein Koordinatenpaar haben.');
181 $json_feature = array(
185 'coordinates' => reset($coordinates)
187 'properties' => $properties
189 $json_features[] = $json_feature;
193 $properties = array('type' => $feature->getName());
194 $allowed_properties = array('farbe', 'dicke');
195 $wrong_properties = array_diff($given_properties, $allowed_properties);
196 if (count($wrong_properties) > 0) throw new Exception("Das Attribut '" . reset($wrong_properties) . "' ist nicht erlaubt bei <" . $feature->getName() . ">. Erlaubt sind: '" . implode("', '", $allowed_properties) . "'.");
197 if (isset($feature['farbe'])) {
198 $color = (string) $feature['farbe']; // e.g. #a200b7
199 if (preg_match('/^#[0-9a-f]{6}$/i', $color) != 1)
200 throw new Exception('Die Farbangabe der Linie hat ein falsches Format. Sie muss z.B. so aussehen: #a200b7.');
201 $properties['strokeColor'] = $color;
203 if (isset($feature['dicke'])) {
204 $stroke_width = (int) $feature['dicke']; // e.g. 6
205 if (((string) $stroke_width) !== (string) $feature['dicke'])
206 throw new Exception('Die Angabe der Liniendicke hat ein falsches Format. Sie muss eine ganze Zahl wie z.B. 6 sein.');
207 $properties['strokeWidth'] = $stroke_width;
209 $json_feature = array(
212 'type' => 'LineString',
213 'coordinates' => WrBaseMap::geo_to_coordinates($feature)
215 'properties' => $properties
217 $json_features[] = $json_feature;
220 return $json_features;
224 /// Renders the <wrgmap> tag and the <wrmap> tag.
225 /// The WrBaseMap class would be the only class needed but as the function render() does not provide an argument
226 /// telling which tag name called the function, a trick with two inherited classes has to be used.
227 /// @param $content string - the content of the <wrgmap> tag
228 /// @param $args array - the array of attribute name/value pairs for the tag
229 /// @param $parser Parser - the MW Parser object for the current page
231 /// @return string - the html for rendering the map
232 public static function render($content, $args, $parser, $frame) {
233 // Unfortunately, $tagname is no argument of this function, therefore we have to use a trick with derived classes.
234 $tagname = strtolower(get_called_class()); // either wrmap or wrgmap
235 assert(in_array($tagname, array('wrmap', 'wrgmap')));
237 $parserOutput = $parser->getOutput();
238 $parserOutput->addHeadItem('<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.8&sensor=false"></script>', 'googlemaps');
239 $parserOutput->addModules('ext.wrmap');
241 // append all sledruns as icon
242 $json_features = array();
243 $show_sledruns = ($tagname == 'wrgmap');
244 if ($show_sledruns) {
245 $json_features = array_merge($json_features, WrBaseMap::sledruns_to_json_features());
250 $properties = array();
251 if (isset($args['lat'])) $properties['lat'] = (float) $args['lat']; // latitude as float value
252 if (isset($args['lon'])) $properties['lon'] = (float) $args['lon']; // longitude as float value
253 if (isset($args['zoom'])) $properties['zoom'] = (int) $args['zoom']; // zoom as int value
254 if (isset($args['width'])) $properties['width'] = (int) $args['width']; // width as int value
255 if (isset($args['height'])) $properties['height'] = (int) $args['height']; // height as int value
257 // append all elements in the XML
258 $json_features = array_merge($json_features, WrBaseMap::xml_to_json_features('<wrmap>' . $content . '</wrmap>'));
259 } catch (Exception $e) {
260 $doc = new WrMapDOMDocument();
261 $doc->appendElement('div', array('class' => 'error'))->appendText('Fehler beim Parsen der Landkarte: ' . $e->getMessage());
262 return array($doc->saveHTML($doc->firstChild), 'markerType' => 'nowiki');
265 // create final geojson
267 'type' => 'FeatureCollection',
268 'features' => $json_features,
269 'properties' => $properties
271 $json_string = json_encode($json);
273 // Create <div/> element where the map is placed in
274 global $wgExtensionAssetsPath;
275 $doc = new WrMapDOMDocument();
276 $div = $doc->appendElement('div', array('class' => 'wrmap', 'style' => 'border-style:none;', 'data-img-path' => "$wgExtensionAssetsPath/wrmap/openlayers/img/"));
278 $div->appendElement('div', array())->appendText('Die Landkarte wird geladen...');
280 $div->appendElement('div', array('style' => 'height: 0px; display:none;'))->appendText($json_string);
281 return array($doc->saveHTML($div), 'markerType' => 'nowiki');
287 class WrMap extends WrBaseMap {
292 class WrGMap extends WrBaseMap {