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);
24 class WrMapDOMElement extends DOMElement {
26 /// Creates and adds the element with the given tag name and returns it
27 /// Additionally, it calls setAttribute($key, $value) for every entry
29 function appendElement($tagName, $attributes=array()) {
30 $child = $this->appendChild($this->ownerDocument->createElement($tagName));
31 foreach ($attributes as $key => $value) $child->setAttribute($key, $value);
35 /// Adds any UTF-8 string as content of the element - it will be escaped.
36 function appendText($text) {
37 return $this->appendChild($this->ownerDocument->createTextNode($text));
40 // Appends a CDATASections to the element. This can be used to include
41 // raw (unparsed) HTML to the DOM tree as it is necessary because
42 // $parser->recursiveTagParse does not always escape & characters.
43 // (see https://bugzilla.wikimedia.org/show_bug.cgi?id=55526 )
44 // Workaround: Use a CDATA section. When serializing with $doc->saveHTML,
45 // the <![CDATA[...]]> is returned as ... .
46 // However, we end up having unescaped & in the output due to this bug in recursiveTagParse.
47 function appendCDATA($data) {
48 return $this->appendChild($this->ownerDocument->createCDATASection($data));
53 // gets coordinates and returns an array of lon/lat coordinate pairs, e.g.
57 // array(array(11.87, 47.12), array(11.70, 47.13))
58 function geo_to_coordinates($input) {
60 $num_matches = preg_match_all('/\s*(\d+\.?\d*)\s*N?\s+(\d+\.?\d*)\s*E?\s*/', $input, $matches);
62 for ($i=0; $i!=$num_matches; ++$i) {
63 $result[] = array(floatval($matches[2][$i]), floatval($matches[1][$i]));
65 if (implode($matches[0]) != $input) throw new Exception('Falsches Koordinatenformat: ' . $input);
70 // convert sledruns to geojson (http://www.geojson.org/geojson-spec.html)
71 // Returns an array of features
72 function sledruns_to_json_features() {
73 $json_features = array(); // result
74 $dbr = wfGetDB(DB_SLAVE);
75 $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')));
76 while ($sledrun = $dbr->fetchRow($res)) {
77 $lat = $sledrun['position_latitude'];
78 $lon = $sledrun['position_longitude'];
79 if (is_null($lat) || is_null($lon)) continue;
80 $lat = floatval($lat);
81 $lon = floatval($lon);
82 $title = Title::newFromText($sledrun['page_title']);
83 $properties = array('type' => 'sledrun', 'name' => $title->getText(), 'wiki' => $title->getLocalUrl());
84 if (!is_null($sledrun['date_report'])) $properties['date_report'] = $sledrun['date_report'];
85 if (!is_null($sledrun['condition'])) $properties['condition'] = intval($sledrun['condition']);
86 $json_feature = array(
90 'coordinates' => array($lon, $lat)
92 'properties' => $properties
94 $json_features[] = $json_feature;
96 $dbr->freeResult($res);
97 return $json_features;
101 // convert XML to geojson (http://www.geojson.org/geojson-spec.html)
102 // Returns an array of features
103 function xml_to_json_features($input) {
104 libxml_use_internal_errors(true); // without that, we get PHP Warnings if the $input is not well-formed
105 $xml = new SimpleXMLElement($input); // input
106 $whitespace = (string) $xml; // everything between <wrmap> and </wrmap> that's not a sub-element
107 if (strlen($whitespace) > 0 && !ctype_space($whitespace)) { // there must not be anythin except sub-elements or whitespace
108 throw new Exception('Die Landkarte enthält folgenden ungültigen Text: "' . trim($xml) . '".');
110 $json_features = array(); // output
111 $point_types = array('gasthaus', 'haltestelle', 'parkplatz', 'achtung', 'punkt');
112 $line_types = array('rodelbahn', 'gehweg', 'alternative', 'lift', 'anfahrt', 'linie');
113 foreach ($xml as $feature) {
114 $given_properties = array();
115 foreach ($feature->attributes() as $key => $value) $given_properties[] = $key;
117 // determine feature type
118 $is_point = in_array($feature->getName(), $point_types);
119 $is_line = in_array($feature->getName(), $line_types);
120 if (!$is_point && !$is_line) {
121 throw new Exception('Unbekanntes Element <' . $feature->getName() . '>. Erlaubt sind: <' . implode('>, <', array_merge($point_types, $line_types)) . '>.');
126 $properties = array('type' => $feature->getName());
127 $allowed_properties = array('name', 'wiki');
128 $wrong_properties = array_diff($given_properties, $allowed_properties);
129 if (count($wrong_properties) > 0) throw new Exception("Das Attribut '" . reset($wrong_properties) . "' ist nicht erlaubt bei <" . $feature->getName() . ">. Erlaubt sind: '" . implode("', '", $allowed_properties) . "'.");
130 foreach ($given_properties as $property) {
131 $propval = (string) $feature[$property];
132 if ($property == 'wiki') {
133 $title = Title::newFromText($propval);
134 $propval = $title->getLocalUrl();
136 $properties[$property] = $propval;
138 $coordinates = geo_to_coordinates($feature);
139 if (count($coordinates) != 1) throw new Exception('Das Element <' . $feature->getName() . '> muss genau ein Koordinatenpaar haben.');
140 $json_feature = array(
144 'coordinates' => reset($coordinates)
146 'properties' => $properties
148 $json_features[] = $json_feature;
152 $properties = array('type' => $feature->getName());
153 $allowed_properties = array('farbe', 'dicke');
154 $wrong_properties = array_diff($given_properties, $allowed_properties);
155 if (count($wrong_properties) > 0) throw new Exception("Das Attribut '" . reset($wrong_properties) . "' ist nicht erlaubt bei <" . $feature->getName() . ">. Erlaubt sind: '" . implode("', '", $allowed_properties) . "'.");
156 if (isset($feature['farbe'])) {
157 $color = (string) $feature['farbe']; // e.g. #a200b7
158 if (preg_match('/^#[0-9a-f]{6}$/i', $color) != 1)
159 throw new Exception('Die Farbangabe der Linie hat ein falsches Format. Sie muss z.B. so aussehen: #a200b7.');
160 $properties['strokeColor'] = $color;
162 if (isset($feature['dicke'])) {
163 $stroke_width = (int) $feature['dicke']; // e.g. 6
164 if (((string) $stroke_width) !== (string) $feature['dicke'])
165 throw new Exception('Die Angabe der Liniendicke hat ein falsches Format. Sie muss eine ganze Zahl wie z.B. 6 sein.');
166 $properties['strokeWidth'] = $stroke_width;
168 $json_feature = array(
171 'type' => 'LineString',
172 'coordinates' => geo_to_coordinates($feature)
174 'properties' => $properties
176 $json_features[] = $json_feature;
179 return $json_features;
185 /// Renders the <wrgmap> tag and the <wrmap> tag.
186 /// This class would be the only class needed but as the function render() toes not provide an argument
187 /// telling which tag name called the function, a trick with two inherited classes has to be used.
188 /// @param $content string - the content of the <wrgmap> tag
189 /// @param $args array - the array of attribute name/value pairs for the tag
190 /// @param $parser Parser - the MW Parser object for the current page
192 /// @return string - the html for rendering the map
193 public static function render($content, $args, $parser, $frame) {
194 // Unfortunately, $tagname is no argument of this function, therefore we have to use a trick with derived classes.
195 $tagname = strtolower(get_called_class()); // either wrmap or wrgmap
196 assert(in_array($tagname, array('wrmap', 'wrgmap')));
198 $parserOutput = $parser->getOutput();
199 $parserOutput->addHeadItem('<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.8&sensor=false"></script>', 'googlemaps');
200 $parserOutput->addModules('ext.wrmap');
202 // append all sledruns as icon
203 $json_features = array();
204 $show_sledruns = ($tagname == 'wrgmap');
205 if ($show_sledruns) {
206 $json_features = array_merge($json_features, sledruns_to_json_features());
211 $properties = array();
212 if (isset($args['lat'])) $properties['lat'] = (float) $args['lat']; // latitude as float value
213 if (isset($args['lon'])) $properties['lon'] = (float) $args['lon']; // longitude as float value
214 if (isset($args['zoom'])) $properties['zoom'] = (int) $args['zoom']; // zoom as int value
215 if (isset($args['width'])) $properties['width'] = (int) $args['width']; // width as int value
216 if (isset($args['height'])) $properties['height'] = (int) $args['height']; // height as int value
218 // append all elements in the XML
219 $json_features = array_merge($json_features, xml_to_json_features('<wrmap>' . $content . '</wrmap>'));
220 } catch (Exception $e) {
221 return '<div class="error">' . htmlspecialchars("Fehler beim Parsen der Landkarte: " . $e->getMessage()) . '</div>';
224 // create final geojson
226 'type' => 'FeatureCollection',
227 'features' => $json_features,
228 'properties' => $properties
230 $json_string = json_encode($json);
232 // Create <div/> element where the map is placed in
233 global $wgExtensionAssetsPath;
234 $output = "<div class=\"wrmap\" style=\"border-style:none;\" data-img-path=\"$wgExtensionAssetsPath/wrmap/openlayers/img/\">";
235 $output .= htmlspecialchars($json_string, ENT_NOQUOTES);
236 $output .= "</div>\n";
238 return array($output, 'markerType' => 'nowiki');
244 class WrMap extends WrBaseMap {
249 class WrGMap extends WrBaseMap {