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 if ($file === false) return Null;
85 if (!$file->canRender()) return Null;
86 $thumb_url = $file->createThumb($width, $width); // limit width and hight to $width
87 if (strlen($thumb_url) == 0) return Null;
92 // convert sledruns to geojson (http://www.geojson.org/geojson-spec.html)
93 // Returns an array of features
94 public static function sledruns_to_json_features() {
95 $json_features = array(); // result
96 $dbr = wfGetDB(DB_SLAVE);
97 $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')));
98 while ($sledrun = $dbr->fetchRow($res)) {
99 $lat = $sledrun['position_latitude'];
100 $lon = $sledrun['position_longitude'];
101 if (is_null($lat) || is_null($lon)) continue;
102 $lat = floatval($lat);
103 $lon = floatval($lon);
104 $title = Title::newFromText($sledrun['page_title']);
105 $properties = array('type' => 'sledrun', 'name' => $title->getText(), 'wiki' => $title->getLocalUrl());
106 if (!is_null($sledrun['date_report'])) $properties['date_report'] = $sledrun['date_report'];
107 if (!is_null($sledrun['condition'])) $properties['condition'] = intval($sledrun['condition']);
108 $json_feature = array(
112 'coordinates' => array($lon, $lat)
114 'properties' => $properties
116 $json_features[] = $json_feature;
118 $dbr->freeResult($res);
119 return $json_features;
123 // convert XML to geojson (http://www.geojson.org/geojson-spec.html)
124 // Returns an array of features
125 public static function xml_to_json_features($input) {
126 libxml_use_internal_errors(true); // without that, we get PHP Warnings if the $input is not well-formed
127 $xml = new SimpleXMLElement($input); // input
128 $whitespace = (string) $xml; // everything between <wrmap> and </wrmap> that's not a sub-element
129 if (strlen($whitespace) > 0 && !ctype_space($whitespace)) { // there must not be anythin except sub-elements or whitespace
130 throw new Exception('Die Landkarte enthält folgenden ungültigen Text: "' . trim($xml) . '".');
132 $json_features = array(); // output
133 $point_types = array('gasthaus', 'haltestelle', 'parkplatz', 'achtung', 'foto', 'punkt');
134 $line_types = array('rodelbahn', 'gehweg', 'alternative', 'lift', 'anfahrt', 'linie');
135 foreach ($xml as $feature) {
136 $given_properties = array();
137 foreach ($feature->attributes() as $key => $value) $given_properties[] = $key;
139 // determine feature type
140 $is_point = in_array($feature->getName(), $point_types);
141 $is_line = in_array($feature->getName(), $line_types);
142 if (!$is_point && !$is_line) {
143 throw new Exception('Unbekanntes Element <' . $feature->getName() . '>. Erlaubt sind: <' . implode('>, <', array_merge($point_types, $line_types)) . '>.');
148 $properties = array('type' => $feature->getName());
149 $allowed_properties = array('name', 'wiki');
150 $wrong_properties = array_diff($given_properties, $allowed_properties);
151 if (count($wrong_properties) > 0) throw new Exception("Das Attribut '" . reset($wrong_properties) . "' ist nicht erlaubt bei <" . $feature->getName() . ">. Erlaubt sind: '" . implode("', '", $allowed_properties) . "'.");
152 foreach ($given_properties as $property) {
153 $propval = (string) $feature[$property];
154 if ($property == 'wiki') {
155 $title = Title::newFromText($propval);
156 $propval = $title->getLocalUrl();
157 $file_url = WrBaseMap::wikipage_to_image($title, 300);
158 if (!is_null($file_url)) $properties['thumb_url'] = $file_url;
160 $properties[$property] = $propval;
162 $coordinates = WrBaseMap::geo_to_coordinates($feature);
163 if (count($coordinates) != 1) throw new Exception('Das Element <' . $feature->getName() . '> muss genau ein Koordinatenpaar haben.');
164 $json_feature = array(
168 'coordinates' => reset($coordinates)
170 'properties' => $properties
172 $json_features[] = $json_feature;
176 $properties = array('type' => $feature->getName());
177 $allowed_properties = array('farbe', 'dicke');
178 $wrong_properties = array_diff($given_properties, $allowed_properties);
179 if (count($wrong_properties) > 0) throw new Exception("Das Attribut '" . reset($wrong_properties) . "' ist nicht erlaubt bei <" . $feature->getName() . ">. Erlaubt sind: '" . implode("', '", $allowed_properties) . "'.");
180 if (isset($feature['farbe'])) {
181 $color = (string) $feature['farbe']; // e.g. #a200b7
182 if (preg_match('/^#[0-9a-f]{6}$/i', $color) != 1)
183 throw new Exception('Die Farbangabe der Linie hat ein falsches Format. Sie muss z.B. so aussehen: #a200b7.');
184 $properties['strokeColor'] = $color;
186 if (isset($feature['dicke'])) {
187 $stroke_width = (int) $feature['dicke']; // e.g. 6
188 if (((string) $stroke_width) !== (string) $feature['dicke'])
189 throw new Exception('Die Angabe der Liniendicke hat ein falsches Format. Sie muss eine ganze Zahl wie z.B. 6 sein.');
190 $properties['strokeWidth'] = $stroke_width;
192 $json_feature = array(
195 'type' => 'LineString',
196 'coordinates' => WrBaseMap::geo_to_coordinates($feature)
198 'properties' => $properties
200 $json_features[] = $json_feature;
203 return $json_features;
207 /// Renders the <wrgmap> tag and the <wrmap> tag.
208 /// The WrBaseMap class would be the only class needed but as the function render() does not provide an argument
209 /// telling which tag name called the function, a trick with two inherited classes has to be used.
210 /// @param $content string - the content of the <wrgmap> tag
211 /// @param $args array - the array of attribute name/value pairs for the tag
212 /// @param $parser Parser - the MW Parser object for the current page
214 /// @return string - the html for rendering the map
215 public static function render($content, $args, $parser, $frame) {
216 // Unfortunately, $tagname is no argument of this function, therefore we have to use a trick with derived classes.
217 $tagname = strtolower(get_called_class()); // either wrmap or wrgmap
218 assert(in_array($tagname, array('wrmap', 'wrgmap')));
220 $parserOutput = $parser->getOutput();
221 $parserOutput->addHeadItem('<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.8&sensor=false"></script>', 'googlemaps');
222 $parserOutput->addModules('ext.wrmap');
224 // append all sledruns as icon
225 $json_features = array();
226 $show_sledruns = ($tagname == 'wrgmap');
227 if ($show_sledruns) {
228 $json_features = array_merge($json_features, WrBaseMap::sledruns_to_json_features());
233 $properties = array();
234 if (isset($args['lat'])) $properties['lat'] = (float) $args['lat']; // latitude as float value
235 if (isset($args['lon'])) $properties['lon'] = (float) $args['lon']; // longitude as float value
236 if (isset($args['zoom'])) $properties['zoom'] = (int) $args['zoom']; // zoom as int value
237 if (isset($args['width'])) $properties['width'] = (int) $args['width']; // width as int value
238 if (isset($args['height'])) $properties['height'] = (int) $args['height']; // height as int value
240 // append all elements in the XML
241 $json_features = array_merge($json_features, WrBaseMap::xml_to_json_features('<wrmap>' . $content . '</wrmap>'));
242 } catch (Exception $e) {
243 $doc = new WrMapDOMDocument();
244 $doc->appendElement('div', array('class' => 'error'))->appendText('Fehler beim Parsen der Landkarte: ' . $e->getMessage());
245 return array($doc->saveHTML($doc->firstChild), 'markerType' => 'nowiki');
248 // create final geojson
250 'type' => 'FeatureCollection',
251 'features' => $json_features,
252 'properties' => $properties
254 $json_string = json_encode($json);
256 // Create <div/> element where the map is placed in
257 global $wgExtensionAssetsPath;
258 $doc = new WrMapDOMDocument();
259 $div = $doc->appendElement('div', array('class' => 'wrmap', 'style' => 'border-style:none;', 'data-img-path' => "$wgExtensionAssetsPath/wrmap/openlayers/img/"));
261 $div->appendElement('div', array())->appendText('Die Landkarte wird geladen...');
263 $div->appendElement('div', array('style' => 'height: 0px; display:none;'))->appendText($json_string);
264 return array($doc->saveHTML($div), 'markerType' => 'nowiki');
270 class WrMap extends WrBaseMap {
275 class WrGMap extends WrBaseMap {