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(wfMessage('wrmap-error-coordinate-format', $input)->text());
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 $image_url = WrBaseMap::wikipage_to_image($title, 150);
130 if (!is_null($image_url)) $properties['thumb_url'] = $image_url;
131 $json_feature = array(
135 'coordinates' => array($lon, $lat)
137 'properties' => $properties
139 $json_features[] = $json_feature;
141 $dbr->freeResult($res);
142 return $json_features;
146 // convert XML to geojson (http://www.geojson.org/geojson-spec.html)
147 // Returns an array of features
148 public static function xml_to_json_features($input) {
149 libxml_use_internal_errors(true); // without that, we get PHP Warnings if the $input is not well-formed
150 $xml = new SimpleXMLElement($input); // input
151 $whitespace = (string) $xml; // everything between <wrmap> and </wrmap> that's not a sub-element
152 if (strlen($whitespace) > 0 && !ctype_space($whitespace)) { // there must not be anythin except sub-elements or whitespace
153 throw new Exception(wfMessage('wrmap-error-invalid-text', trim($xml))->text());
155 $json_features = array(); // output
156 $point_types = array('gasthaus', 'haltestelle', 'parkplatz', 'achtung', 'foto', 'verleih', 'punkt');
157 $line_types = array('rodelbahn', 'gehweg', 'alternative', 'lift', 'anfahrt', 'linie');
158 foreach ($xml as $feature) {
159 $given_properties = array();
160 foreach ($feature->attributes() as $key => $value) $given_properties[] = $key;
162 // determine feature type
163 $is_point = in_array($feature->getName(), $point_types);
164 $is_line = in_array($feature->getName(), $line_types);
165 if (!$is_point && !$is_line) {
166 throw new Exception(wfMessage('wrmap-error-invalid-element', $feature->getName(), '<' . implode('>, <', array_merge($point_types, $line_types)) . '>')->text());
171 $properties = array('type' => $feature->getName());
172 $allowed_properties = array('name', 'wiki');
173 $wrong_properties = array_diff($given_properties, $allowed_properties);
174 if (count($wrong_properties) > 0) throw new Exception(wfMessage('wrmap-error-invalid-attribute', reset($wrong_properties), $feature->getName(), "'" . implode("', '", $allowed_properties) . "'")->text());
175 foreach ($given_properties as $property) {
176 $propval = (string) $feature[$property];
177 if ($property == 'wiki') {
178 $title = Title::newFromText($propval);
179 $propval = $title->getLocalUrl();
180 $file_url = WrBaseMap::wikipage_to_image($title, 200);
181 if (!is_null($file_url)) $properties['thumb_url'] = $file_url;
183 $properties[$property] = $propval;
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(
191 'coordinates' => reset($coordinates)
193 'properties' => $properties
195 $json_features[] = $json_feature;
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;
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;
215 $json_feature = array(
218 'type' => 'LineString',
219 'coordinates' => WrBaseMap::geo_to_coordinates($feature)
221 'properties' => $properties
223 $json_features[] = $json_feature;
226 return $json_features;
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
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')));
243 $parserOutput = $parser->getOutput();
244 $parserOutput->addHeadItem('<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.8&sensor=false"></script>', 'googlemaps');
245 $parserOutput->addModules('ext.wrmap');
247 // append all sledruns as icon
248 $json_features = array();
249 $show_sledruns = ($tagname == 'wrgmap');
250 if ($show_sledruns) {
251 $json_features = array_merge($json_features, WrBaseMap::sledruns_to_json_features());
256 $properties = array();
257 if (isset($args['lat'])) $properties['lat'] = (float) $args['lat']; // latitude as float value
258 if (isset($args['lon'])) $properties['lon'] = (float) $args['lon']; // longitude as float value
259 if (isset($args['zoom'])) $properties['zoom'] = (int) $args['zoom']; // zoom as int value
260 if (isset($args['width'])) $properties['width'] = (int) $args['width']; // width as int value
261 if (isset($args['height'])) $properties['height'] = (int) $args['height']; // height as int value
263 // append all elements in the XML
264 $json_features = array_merge($json_features, WrBaseMap::xml_to_json_features('<wrmap>' . $content . '</wrmap>'));
265 } catch (Exception $e) {
266 $doc = new WrMapDOMDocument();
267 $doc->appendElement('div', array('class' => 'error'))->appendText('Fehler beim Parsen der Landkarte: ' . $e->getMessage());
268 return array($doc->saveHTML($doc->firstChild), 'markerType' => 'nowiki');
271 // create final geojson
273 'type' => 'FeatureCollection',
274 'features' => $json_features,
275 'properties' => $properties
277 $json_string = json_encode($json);
279 // Create <div/> element where the map is placed in
280 global $wgExtensionAssetsPath;
281 $doc = new WrMapDOMDocument();
282 $div = $doc->appendElement('div', array('class' => 'wrmap', 'style' => 'border-style:none;', 'data-ext-path' => "$wgExtensionAssetsPath/wrmap"));
284 $div->appendElement('div', array())->appendText(wfMessage('wrmap-loading')->text());
286 $div->appendElement('div', array('style' => 'height: 0px; display:none;'))->appendText($json_string);
287 return array($doc->saveHTML($div), 'markerType' => 'nowiki');
291 public static function onEnableMobileModules($out, $mode) {
292 $out->addModules('ext.wrmap.mobile');
299 class WrMap extends WrBaseMap {
304 class WrGMap extends WrBaseMap {