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
89 $dbr = wfGetDB(DB_SLAVE);
90 $res = $dbr->select('wrsledruncache', 'image', array('page_id' => $title->getArticleID()), __METHOD__);
91 $image = $dbr->fetchRow($res);
92 if ($image && !is_null($image['image'])) $file = wfFindFile($image['image']);
93 $dbr->freeResult($res);
95 $key_inn = $wgContLang->getNSText(NS_CATEGORY) . ':Gasthaus';
96 if (array_key_exists($key_inn, $categories)) {
97 // for inn titles use the image from the gasthausbox
98 $dbr = wfGetDB(DB_SLAVE);
99 $res = $dbr->select('wrinncache', 'image', array('page_id' => $title->getArticleID()), __METHOD__);
100 $image = $dbr->fetchRow($res);
101 if ($image && !is_null($image['image'])) $file = wfFindFile($image['image']);
102 $dbr->freeResult($res);
105 if ($file === false) return Null;
106 if (!$file->canRender()) return Null;
107 $thumb_url = $file->createThumb($width, $width); // limit width and hight to $width
108 if (strlen($thumb_url) == 0) return Null;
113 // convert sledruns to geojson (http://www.geojson.org/geojson-spec.html)
114 // Returns an array of features
115 public static function sledruns_to_json_features() {
116 $json_features = array(); // result
117 $dbr = wfGetDB(DB_SLAVE);
118 $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')));
119 while ($sledrun = $dbr->fetchRow($res)) {
120 $lat = $sledrun['position_latitude'];
121 $lon = $sledrun['position_longitude'];
122 if (is_null($lat) || is_null($lon)) continue;
123 $lat = floatval($lat);
124 $lon = floatval($lon);
125 $title = Title::newFromText($sledrun['page_title']);
126 $properties = array('type' => 'sledrun', 'name' => $title->getText(), 'wiki' => $title->getLocalUrl());
127 if (!is_null($sledrun['date_report'])) $properties['date_report'] = $sledrun['date_report'];
128 if (!is_null($sledrun['condition'])) $properties['condition'] = intval($sledrun['condition']);
129 $json_feature = array(
133 'coordinates' => array($lon, $lat)
135 'properties' => $properties
137 $json_features[] = $json_feature;
139 $dbr->freeResult($res);
140 return $json_features;
144 // convert XML to geojson (http://www.geojson.org/geojson-spec.html)
145 // Returns an array of features
146 public static function xml_to_json_features($input) {
147 libxml_use_internal_errors(true); // without that, we get PHP Warnings if the $input is not well-formed
148 $xml = new SimpleXMLElement($input); // input
149 $whitespace = (string) $xml; // everything between <wrmap> and </wrmap> that's not a sub-element
150 if (strlen($whitespace) > 0 && !ctype_space($whitespace)) { // there must not be anythin except sub-elements or whitespace
151 throw new Exception('Die Landkarte enthält folgenden ungültigen Text: "' . trim($xml) . '".');
153 $json_features = array(); // output
154 $point_types = array('gasthaus', 'haltestelle', 'parkplatz', 'achtung', 'foto', 'punkt');
155 $line_types = array('rodelbahn', 'gehweg', 'alternative', 'lift', 'anfahrt', 'linie');
156 foreach ($xml as $feature) {
157 $given_properties = array();
158 foreach ($feature->attributes() as $key => $value) $given_properties[] = $key;
160 // determine feature type
161 $is_point = in_array($feature->getName(), $point_types);
162 $is_line = in_array($feature->getName(), $line_types);
163 if (!$is_point && !$is_line) {
164 throw new Exception('Unbekanntes Element <' . $feature->getName() . '>. Erlaubt sind: <' . implode('>, <', array_merge($point_types, $line_types)) . '>.');
169 $properties = array('type' => $feature->getName());
170 $allowed_properties = array('name', 'wiki');
171 $wrong_properties = array_diff($given_properties, $allowed_properties);
172 if (count($wrong_properties) > 0) throw new Exception("Das Attribut '" . reset($wrong_properties) . "' ist nicht erlaubt bei <" . $feature->getName() . ">. Erlaubt sind: '" . implode("', '", $allowed_properties) . "'.");
173 foreach ($given_properties as $property) {
174 $propval = (string) $feature[$property];
175 if ($property == 'wiki') {
176 $title = Title::newFromText($propval);
177 $propval = $title->getLocalUrl();
178 $file_url = WrBaseMap::wikipage_to_image($title, 200);
179 if (!is_null($file_url)) $properties['thumb_url'] = $file_url;
181 $properties[$property] = $propval;
183 $coordinates = WrBaseMap::geo_to_coordinates($feature);
184 if (count($coordinates) != 1) throw new Exception('Das Element <' . $feature->getName() . '> muss genau ein Koordinatenpaar haben.');
185 $json_feature = array(
189 'coordinates' => reset($coordinates)
191 'properties' => $properties
193 $json_features[] = $json_feature;
197 $properties = array('type' => $feature->getName());
198 $allowed_properties = array('farbe', 'dicke');
199 $wrong_properties = array_diff($given_properties, $allowed_properties);
200 if (count($wrong_properties) > 0) throw new Exception("Das Attribut '" . reset($wrong_properties) . "' ist nicht erlaubt bei <" . $feature->getName() . ">. Erlaubt sind: '" . implode("', '", $allowed_properties) . "'.");
201 if (isset($feature['farbe'])) {
202 $color = (string) $feature['farbe']; // e.g. #a200b7
203 if (preg_match('/^#[0-9a-f]{6}$/i', $color) != 1)
204 throw new Exception('Die Farbangabe der Linie hat ein falsches Format. Sie muss z.B. so aussehen: #a200b7.');
205 $properties['strokeColor'] = $color;
207 if (isset($feature['dicke'])) {
208 $stroke_width = (int) $feature['dicke']; // e.g. 6
209 if (((string) $stroke_width) !== (string) $feature['dicke'])
210 throw new Exception('Die Angabe der Liniendicke hat ein falsches Format. Sie muss eine ganze Zahl wie z.B. 6 sein.');
211 $properties['strokeWidth'] = $stroke_width;
213 $json_feature = array(
216 'type' => 'LineString',
217 'coordinates' => WrBaseMap::geo_to_coordinates($feature)
219 'properties' => $properties
221 $json_features[] = $json_feature;
224 return $json_features;
228 /// Renders the <wrgmap> tag and the <wrmap> tag.
229 /// The WrBaseMap class would be the only class needed but as the function render() does not provide an argument
230 /// telling which tag name called the function, a trick with two inherited classes has to be used.
231 /// @param $content string - the content of the <wrgmap> tag
232 /// @param $args array - the array of attribute name/value pairs for the tag
233 /// @param $parser Parser - the MW Parser object for the current page
235 /// @return string - the html for rendering the map
236 public static function render($content, $args, $parser, $frame) {
237 // Unfortunately, $tagname is no argument of this function, therefore we have to use a trick with derived classes.
238 $tagname = strtolower(get_called_class()); // either wrmap or wrgmap
239 assert(in_array($tagname, array('wrmap', 'wrgmap')));
241 $parserOutput = $parser->getOutput();
242 $parserOutput->addHeadItem('<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.8&sensor=false"></script>', 'googlemaps');
243 $parserOutput->addModules('ext.wrmap');
245 // append all sledruns as icon
246 $json_features = array();
247 $show_sledruns = ($tagname == 'wrgmap');
248 if ($show_sledruns) {
249 $json_features = array_merge($json_features, WrBaseMap::sledruns_to_json_features());
254 $properties = array();
255 if (isset($args['lat'])) $properties['lat'] = (float) $args['lat']; // latitude as float value
256 if (isset($args['lon'])) $properties['lon'] = (float) $args['lon']; // longitude as float value
257 if (isset($args['zoom'])) $properties['zoom'] = (int) $args['zoom']; // zoom as int value
258 if (isset($args['width'])) $properties['width'] = (int) $args['width']; // width as int value
259 if (isset($args['height'])) $properties['height'] = (int) $args['height']; // height as int value
261 // append all elements in the XML
262 $json_features = array_merge($json_features, WrBaseMap::xml_to_json_features('<wrmap>' . $content . '</wrmap>'));
263 } catch (Exception $e) {
264 $doc = new WrMapDOMDocument();
265 $doc->appendElement('div', array('class' => 'error'))->appendText('Fehler beim Parsen der Landkarte: ' . $e->getMessage());
266 return array($doc->saveHTML($doc->firstChild), 'markerType' => 'nowiki');
269 // create final geojson
271 'type' => 'FeatureCollection',
272 'features' => $json_features,
273 'properties' => $properties
275 $json_string = json_encode($json);
277 // Create <div/> element where the map is placed in
278 global $wgExtensionAssetsPath;
279 $doc = new WrMapDOMDocument();
280 $div = $doc->appendElement('div', array('class' => 'wrmap', 'style' => 'border-style:none;', 'data-img-path' => "$wgExtensionAssetsPath/wrmap/openlayers/img/"));
282 $div->appendElement('div', array())->appendText('Die Landkarte wird geladen...');
284 $div->appendElement('div', array('style' => 'height: 0px; display:none;'))->appendText($json_string);
285 return array($doc->saveHTML($div), 'markerType' => 'nowiki');
291 class WrMap extends WrBaseMap {
296 class WrGMap extends WrBaseMap {