Moved global functions belonging to that extension to the WrBaseMap class.
[philipp/winterrodeln/mediawiki_extensions/wrmap.git] / wrmap.body.php
1 <?php
2
3 // DOM helper classes
4 // ------------------
5
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');
12         }
13
14         /// Creates and adds the element with the given tag name and returns it.
15         /// Additionally, it calls setAttribute($key, $value) for every entry
16         /// in $attributes.
17         function appendElement($tagName, $attributes=array()) {
18                 $child = $this->appendChild($this->createElement($tagName));
19                 foreach ($attributes as $key => $value) $child->setAttribute($key, $value);
20                 return $child;
21         }
22 }
23
24
25 class WrMapDOMElement extends DOMElement {
26
27         /// Creates and adds the element with the given tag name and returns it
28         /// Additionally, it calls setAttribute($key, $value) for every entry
29         /// in $attributes.
30         function appendElement($tagName, $attributes=array()) {
31                 $child = $this->appendChild($this->ownerDocument->createElement($tagName));
32                 foreach ($attributes as $key => $value) $child->setAttribute($key, $value);
33                 return $child;
34         }
35
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));
39         }
40
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));
50         }
51 }
52
53
54 // WrBaseMap
55 // ---------
56
57 class WrBaseMap {
58         // gets coordinates and returns an array of lon/lat coordinate pairs, e.g.
59         // 47.12 N 11.87 E
60         // 47.13 N 11.70 E
61         // ->
62         // array(array(11.87, 47.12), array(11.70, 47.13))
63         public static function geo_to_coordinates($input) {
64                 $matches = array();
65                 $num_matches = preg_match_all('/\s*(\d+\.?\d*)\s*N?\s+(\d+\.?\d*)\s*E?\s*/', $input, $matches);
66                 $result = array();
67                 for ($i=0; $i!=$num_matches; ++$i) {
68                         $result[] = array(floatval($matches[2][$i]), floatval($matches[1][$i]));
69                 }
70                 if (implode($matches[0]) != $input) throw new Exception('Falsches Koordinatenformat: ' . $input);
71                 return $result;
72         }
73
74
75         // convert sledruns to geojson (http://www.geojson.org/geojson-spec.html)
76         // Returns an array of features
77         public static function sledruns_to_json_features() {
78                 $json_features = array(); // result
79                 $dbr = wfGetDB(DB_SLAVE);
80                 $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')));
81                 while ($sledrun = $dbr->fetchRow($res)) {
82                         $lat = $sledrun['position_latitude'];
83                         $lon = $sledrun['position_longitude'];
84                         if (is_null($lat) || is_null($lon)) continue;
85                         $lat = floatval($lat);
86                         $lon = floatval($lon);
87                         $title = Title::newFromText($sledrun['page_title']);
88                         $properties = array('type' => 'sledrun', 'name' => $title->getText(), 'wiki' => $title->getLocalUrl());
89                         if (!is_null($sledrun['date_report'])) $properties['date_report'] = $sledrun['date_report'];
90                         if (!is_null($sledrun['condition'])) $properties['condition'] = intval($sledrun['condition']);
91                         $json_feature = array(
92                                 'type' => 'feature',
93                                 'geometry' => array(
94                                         'type' => 'Point',
95                                         'coordinates' => array($lon, $lat)
96                                 ),
97                                 'properties' => $properties
98                         );
99                         $json_features[] = $json_feature;
100                 }
101                 $dbr->freeResult($res);
102                 return $json_features;
103         }
104
105
106         // convert XML to geojson (http://www.geojson.org/geojson-spec.html)
107         // Returns an array of features
108         public static function xml_to_json_features($input) {
109                 libxml_use_internal_errors(true); // without that, we get PHP Warnings if the $input is not well-formed
110                 $xml = new SimpleXMLElement($input); // input
111                 $whitespace = (string) $xml; // everything between <wrmap> and </wrmap> that's not a sub-element
112                 if (strlen($whitespace) > 0 && !ctype_space($whitespace)) { // there must not be anythin except sub-elements or whitespace
113                         throw new Exception('Die Landkarte enthält folgenden ungültigen Text: "' . trim($xml) . '".');
114                 }
115                 $json_features = array(); // output
116                 $point_types = array('gasthaus', 'haltestelle', 'parkplatz', 'achtung', 'foto', 'punkt');
117                 $line_types = array('rodelbahn', 'gehweg', 'alternative', 'lift', 'anfahrt', 'linie');
118                 foreach ($xml as $feature) {
119                         $given_properties = array();
120                         foreach ($feature->attributes() as $key => $value) $given_properties[] = $key;
121
122                         // determine feature type
123                         $is_point = in_array($feature->getName(), $point_types);
124                         $is_line = in_array($feature->getName(), $line_types);
125                         if (!$is_point && !$is_line) {
126                                 throw new Exception('Unbekanntes Element <' . $feature->getName() . '>. Erlaubt sind: <' . implode('>, <', array_merge($point_types, $line_types)) . '>.');
127                         }
128
129                         // point
130                         if ($is_point) {
131                                 $properties = array('type' => $feature->getName());
132                                 $allowed_properties = array('name', 'wiki');
133                                 $wrong_properties = array_diff($given_properties, $allowed_properties);
134                                 if (count($wrong_properties) > 0) throw new Exception("Das Attribut '" . reset($wrong_properties) . "' ist nicht erlaubt bei <" . $feature->getName() . ">. Erlaubt sind: '" . implode("', '", $allowed_properties) . "'.");
135                                 foreach ($given_properties as $property) {
136                                         $propval = (string) $feature[$property];
137                                         if ($property == 'wiki') {
138                                                 $title = Title::newFromText($propval);
139                                                 $propval = $title->getLocalUrl();
140                                         }
141                                         $properties[$property] = $propval;
142                                 }
143                                 $coordinates = WrBaseMap::geo_to_coordinates($feature);
144                                 if (count($coordinates) != 1) throw new Exception('Das Element <' . $feature->getName() . '> muss genau ein Koordinatenpaar haben.');
145                                 $json_feature = array(
146                                         'type' => 'feature',
147                                         'geometry' => array(
148                                                 'type' => 'Point',
149                                                 'coordinates' => reset($coordinates)
150                                         ),
151                                         'properties' => $properties
152                                 );
153                                 $json_features[] = $json_feature;
154                         }
155                         // line
156                         if ($is_line) {
157                                 $properties = array('type' => $feature->getName());
158                                 $allowed_properties = array('farbe', 'dicke');
159                                 $wrong_properties = array_diff($given_properties, $allowed_properties);
160                                 if (count($wrong_properties) > 0) throw new Exception("Das Attribut '" . reset($wrong_properties) . "' ist nicht erlaubt bei <" . $feature->getName() . ">. Erlaubt sind: '" . implode("', '", $allowed_properties) . "'.");
161                                 if (isset($feature['farbe'])) {
162                                         $color = (string) $feature['farbe']; // e.g. #a200b7
163                                         if (preg_match('/^#[0-9a-f]{6}$/i', $color) != 1) 
164                                                 throw new Exception('Die Farbangabe der Linie hat ein falsches Format. Sie muss z.B. so aussehen: #a200b7.');
165                                         $properties['strokeColor'] = $color;
166                                 }
167                                 if (isset($feature['dicke'])) {
168                                         $stroke_width = (int) $feature['dicke']; // e.g. 6
169                                         if (((string) $stroke_width) !== (string) $feature['dicke'])
170                                                 throw new Exception('Die Angabe der Liniendicke hat ein falsches Format. Sie muss eine ganze Zahl wie z.B. 6 sein.');
171                                         $properties['strokeWidth'] = $stroke_width;
172                                 }
173                                 $json_feature = array(
174                                         'type' => 'feature',
175                                         'geometry' => array(
176                                                 'type' => 'LineString',
177                                                 'coordinates' => WrBaseMap::geo_to_coordinates($feature)
178                                         ),
179                                         'properties' => $properties
180                                 );
181                                 $json_features[] = $json_feature;
182                         }
183                 }
184                 return $json_features;
185         }
186
187
188         /// Renders the <wrgmap> tag and the <wrmap> tag.
189         /// The WrBaseMap class would be the only class needed but as the function render() does not provide an argument
190         /// telling which tag name called the function, a trick with two inherited classes has to be used.
191         /// @param $content string - the content of the <wrgmap> tag
192         /// @param $args array - the array of attribute name/value pairs for the tag
193         /// @param $parser Parser - the MW Parser object for the current page
194         ///
195         /// @return string - the html for rendering the map
196         public static function render($content, $args, $parser, $frame) {
197                 // Unfortunately, $tagname is no argument of this function, therefore we have to use a trick with derived classes.
198                 $tagname = strtolower(get_called_class()); // either wrmap or wrgmap
199                 assert(in_array($tagname, array('wrmap', 'wrgmap')));
200
201                 $parserOutput = $parser->getOutput();
202                 $parserOutput->addHeadItem('<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.8&amp;sensor=false"></script>', 'googlemaps');
203                 $parserOutput->addModules('ext.wrmap');
204
205                 // append all sledruns as icon
206                 $json_features = array();
207                 $show_sledruns = ($tagname == 'wrgmap');
208                 if ($show_sledruns) {
209                         $json_features = array_merge($json_features, WrBaseMap::sledruns_to_json_features());
210                 }
211
212                 try {
213                         // map properties
214                         $properties = array();
215                         if (isset($args['lat'])) $properties['lat'] = (float) $args['lat']; // latitude as float value
216                         if (isset($args['lon'])) $properties['lon'] = (float) $args['lon']; // longitude as float value
217                         if (isset($args['zoom'])) $properties['zoom'] = (int) $args['zoom']; // zoom as int value
218                         if (isset($args['width'])) $properties['width'] = (int) $args['width']; // width as int value
219                         if (isset($args['height'])) $properties['height'] = (int) $args['height']; // height as int value
220
221                         // append all elements in the XML
222                         $json_features = array_merge($json_features, WrBaseMap::xml_to_json_features('<wrmap>' . $content . '</wrmap>'));
223                 } catch (Exception $e) {
224                         $doc = new WrMapDOMDocument();
225                         $doc->appendElement('div', array('class' => 'error'))->appendText('Fehler beim Parsen der Landkarte: ' . $e->getMessage());
226                         return array($doc->saveHTML($doc->firstChild), 'markerType' => 'nowiki');
227                 }
228
229                 // create final geojson
230                 $json = array(
231                         'type' => 'FeatureCollection',
232                         'features' => $json_features,
233                         'properties' => $properties
234                 );
235                 $json_string = json_encode($json);
236
237                 // Create <div/> element where the map is placed in
238                 global $wgExtensionAssetsPath;
239                 $doc = new WrMapDOMDocument();
240                 $div = $doc->appendElement('div', array('class' => 'wrmap', 'style' => 'border-style:none;', 'data-img-path' => "$wgExtensionAssetsPath/wrmap/openlayers/img/"));
241                 // progress message
242                 $div->appendElement('div', array())->appendText('Die Landkarte wird geladen...');
243                 // data
244                 $div->appendElement('div', array('style' => 'height: 0px; display:none;'))->appendText($json_string);
245                 return array($doc->saveHTML($div), 'markerType' => 'nowiki');
246         }
247 }
248
249
250 // <wrmap> tag
251 class WrMap extends WrBaseMap {
252 }
253
254
255 // <wrgmap> tag
256 class WrGMap extends WrBaseMap {
257 }
258
259 ?>