Now using the minimized version of OpenLayers.
[philipp/winterrodeln/mediawiki_extensions/wrmap.git] / wrmap.body.php
index 546a778507e4d142d5b894526eecd359e4831155..8723f96c0304e18d7e45cd8bc7748acc1d899309 100644 (file)
 <?php
 
-class WrMap {
-       /// Renders the <wrgmap> tag
+// gets coordinates and returns an array of lon/lat coordinate pairs, e.g.
+// 47.12 N 11.87 E
+// 47.13 N 11.70 E
+// ->
+// array(array(11.87, 47.12), array(11.70, 47.13))
+function geo_to_coordinates($input) {
+       $matches = array();
+       $num_matches = preg_match_all('/\s*(\d+\.?\d*)\s*N?\s+(\d+\.?\d*)\s*E?\s*/', $input, $matches);
+       $result = array();
+       for ($i=0; $i!=$num_matches; ++$i) {
+               $result[] = array(floatval($matches[2][$i]), floatval($matches[1][$i]));
+       }
+       if (implode($matches[0]) != $input) throw new Exception('Falsches Koordinatenformat: ' . $input);
+       return $result;
+}
+
+
+// convert sledruns to geojson (http://www.geojson.org/geojson-spec.html)
+// Returns an array of features
+function sledruns_to_json_features() {
+       $json_features = array(); // result
+       $dbr = wfGetDB(DB_SLAVE);
+       $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')));
+       while ($sledrun = $dbr->fetchRow($res)) {
+               $lat = $sledrun['position_latitude'];
+               $lon = $sledrun['position_longitude'];
+               if (is_null($lat) || is_null($lon)) continue;
+               $lat = floatval($lat);
+               $lon = floatval($lon);
+               $title = Title::newFromText($sledrun['page_title']);
+               $properties = array('type' => 'sledrun', 'name' => $title->getText(), 'wiki' => $title->getLocalUrl());
+               if (!is_null($sledrun['date_report'])) $properties[] = $sledrun['date_report'];
+               if (!is_null($sledrun['condition'])) $properties[] = intval($sledrun['condition']);
+               $json_feature = array(
+                       'type' => 'feature',
+                       'geometry' => array(
+                               'type' => 'Point',
+                               'coordinates' => array($lon, $lat)
+                       ),
+                       'properties' => $properties
+               );
+               $json_features[] = $json_feature;
+       }
+       $dbr->freeResult($res);
+       return $json_features;
+}
+
+
+// convert XML to geojson (http://www.geojson.org/geojson-spec.html)
+// Returns an array of features
+function xml_to_json_features($input) {
+       libxml_use_internal_errors(true); // without that, we get PHP Warnings if the $input is not well-formed
+       $xml = new SimpleXMLElement($input); // input
+       $json_features = array(); // output
+       $point_types = array('gasthaus', 'haltestelle', 'parkplatz', 'achtung', 'punkt');
+       $line_types = array('rodelbahn', 'gehweg', 'alternative', 'lift', 'anfahrt', 'linie');
+       foreach ($xml as $feature) {
+               $given_properties = array();
+               foreach ($feature->attributes() as $key => $value) $given_properties[] = $key;
+
+               // determine feature type
+               $is_point = in_array($feature->getName(), $point_types);
+               $is_line = in_array($feature->getName(), $line_types);
+               if (!$is_point && !$is_line) {
+                       throw new Exception('Unbekanntes Element <' . $feature->getName() . '>. Erlaubt sind: <' . implode('>, <', array_keys(array_merge($point_type, $line_type))) . '>.');
+               }
+
+               // point
+               if ($is_point) {
+                       $properties = array('type' => $feature->getName());
+                       $allowed_properties = array('name', 'wiki');
+                       $wrong_properties = array_diff($given_properties, $allowed_properties);
+                       if (count($wrong_properties) > 0) throw new Exception("Das Attribut '" . reset($wrong_properties) . "' ist nicht erlaubt bei <" . $feature->getName() . ">. Erlaubt sind: '" . implode("', '", $allowed_properties) . "'.");
+                       foreach ($given_properties as $property) {
+                               $properties[$property] = (string) $feature[$property];
+                       }
+                       $coordinates = geo_to_coordinates($feature);
+                       if (count($coordinates) != 1) throw new Exception('Das Element <' . $feature->getName() . '> muss genau ein Koordinatenpaar haben.');
+                       $json_feature = array(
+                               'type' => 'feature',
+                               'geometry' => array(
+                                       'type' => 'Point',
+                                       'coordinates' => reset($coordinates)
+                               ),
+                               'properties' => $properties
+                       );
+                       $json_features[] = $json_feature;
+               }
+               // line
+               if ($is_line) {
+                       $properties = array('type' => $feature->getName());
+                       $allowed_properties = array('farbe', 'dicke');
+                       $wrong_properties = array_diff($given_properties, $allowed_properties);
+                       if (count($wrong_properties) > 0) throw new Exception("Das Attribut '" . reset($wrong_properties) . "' ist nicht erlaubt bei <" . $feature->getName() . ">. Erlaubt sind: '" . implode("', '", $allowed_properties) . "'.");
+                       if (isset($feature['farbe'])) $properties['strokeColor'] = (string) $feature['farbe']; // e.g. #a200b7 // TODO: Check
+                       if (isset($feature['dicke'])) $properties['strokeWidth'] = (int) $feature['dicke']; // e.g. 6 // TODO: Check
+                       $json_feature = array(
+                               'type' => 'feature',
+                               'geometry' => array(
+                                       'type' => 'LineString',
+                                       'coordinates' => geo_to_coordinates($feature)
+                               ),
+                               'properties' => $properties
+                       );
+                       $json_features[] = $json_feature;
+               }
+       }
+       return $json_features;
+}
+
+
+
+class WrBaseMap {
+       /// Renders the <wrgmap> tag and the <wrmap> tag.
+       /// This class would be the only class needed but as the function render() toes not provide an argument
+       /// telling which tag name called the function, a trick with two inherited classes has to be used.
        /// @param $content string - the content of the <wrgmap> tag
        /// @param $args array - the array of attribute name/value pairs for the tag
        /// @param $parser Parser - the MW Parser object for the current page
        ///
        /// @return string - the html for rendering the map
        public static function render($content, $args, $parser, $frame) {
-               // Get center and zoom level from $args
-               if (isset($args['lat'])) $latitude = floatval($args['lat']); else $latitude = 47.267648;   // latitude as float value
-               if (isset($args['lon'])) $longitude = floatval($args['lon']); else $longitude = 11.404655; // longitude as float value
-               if (isset($args['zoom'])) $zoom = intval($args['zoom']); else $zoom = 10; // Google Zoom Level
-               $latitude_s = sprintf('%.6F', $latitude);
-               $longitude_s = sprintf('%.6F', $longitude);
-
-               // Query database
-               $dbr = wfGetDB(DB_SLAVE);
-               $res = $dbr->select('wrsledruncache', array('page_title', 'position_latitude', 'position_longitude'), array('show_in_overview', 'not under_construction'));
-               $sledruns = array();
-               while ($sledrun = $dbr->fetchRow($res)) $sledruns[] = $sledrun;
-               $dbr->freeResult($res);
-               
+               // Unfortunately, $tagname is no argument of this function, therefore we have to use a trick with derived classes.
+               $tagname = strtolower(get_called_class()); // either wrmap or wrgmap
+               assert(in_array($tagname, array('wrmap', 'wrgmap')));
+
                $parserOutput = $parser->getOutput();
                $parserOutput->addHeadItem('<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.8&amp;sensor=false"></script>', 'googlemaps');
                $parserOutput->addModules('ext.wrmap');
-               
-               // Create <div/> element where the map is placed in
-               $output = "<div class=\"wrmap\" style=\"width: 100%; height: 450px; border-style:none;\" data-center-lon=\"$longitude_s\" data-center-lat=\"$latitude_s\" data-zoom=\"$zoom\">\n";
-               foreach ($sledruns as $sledrun) {
-                       $lat = $sledrun['position_latitude'];
-                       $lon = $sledrun['position_longitude'];
-                       if (!$lat || !$lon) continue;
-                       $title = Title::newFromText($sledrun['page_title']);
-                       $output .= "<p data-lon=\"$lon\" data-lat=\"$lat\" data-title=\"{$title->getText()}\" data-url=\"{$title->getLocalUrl()}\" />\n";
+
+               // append all sledruns as icon
+               $json_features = array();
+               $show_sledruns = ($tagname == 'wrgmap');
+               if ($show_sledruns) {
+                       $json_features = array_merge($json_features, sledruns_to_json_features());
+               }
+
+               try {
+                       // map properties
+                       $properties = array();
+                       if (isset($args['lat'])) $properties['lat'] = (float) $args['lat']; // latitude as float value
+                       if (isset($args['lon'])) $properties['lon'] = (float) $args['lon']; // longitude as float value
+                       if (isset($args['zoom'])) $properties['zoom'] = (int) $args['zoom']; // zoom as int value
+                       if (isset($args['width'])) $properties['width'] = (int) $args['width']; // width as int value
+                       if (isset($args['height'])) $properties['height'] = (int) $args['height']; // height as int value
+
+                       // append all elements in the XML
+                       $json_features = array_merge($json_features, xml_to_json_features('<wrmap>' . $content . '</wrmap>'));
+               } catch (Exception $e) {
+                       return '<div class="error">' . htmlspecialchars("Fehler beim Parsen der Landkarte: " . $e->getMessage()) . '</div>';
                }
+
+               // create final geojson
+               $json = array(
+                       'type' => 'FeatureCollection',
+                       'features' => $json_features,
+                       'properties' => $properties
+               );
+               $json_string = json_encode($json);
+
+               // Create <div/> element where the map is placed in
+               global $wgExtensionAssetsPath;
+               $width_s = (isset($properties['width'])) ? (string) $properties['width'] . 'px' : '100%';
+               $height_s = (isset($properties['height']) ? (string) $properties['height'] : 450) . 'px';
+               $output = "<div class=\"wrmap\" style=\"width: $width_s; height: $height_s; border-style:none;\" data-img-path=\"$wgExtensionAssetsPath/wrmap/openlayers/img/\">";
+               $output .= "<script type=\"application/json\">";
+               $output .= htmlspecialchars($json_string, ENT_NOQUOTES);
+               $output .= "</script>";
                $output .= "</div>\n";
                
                return $output;
        }
+}
+
 
+// <wrmap> tag
+class WrMap extends WrBaseMap {
 }
 
 
+// <wrgmap> tag
+class WrGMap extends WrBaseMap {
+}
+
 ?>