2 # Copyright 2011 Blars Blarson
3 # Released under GPL version 2
5 package IkiWiki::Plugin::osm;
13 hook(type => "getsetup", id => "osm", call => \&getsetup);
14 hook(type => "format", id => "osm", call => \&format);
15 hook(type => "preprocess", id => "osm", call => \&preprocess);
16 hook(type => "preprocess", id => "waypoint", call => \&process_waypoint);
17 hook(type => "savestate", id => "waypoint", call => \&savestate);
18 hook(type => "cgi", id => "osm", call => \&cgi);
26 section => "special-purpose",
31 description => "the default zoom when you click on the map link",
37 example => "ikiwiki/images/osm.png",
38 description => "the icon shown on links and on the main map",
45 description => "the alt tag of links, defaults to empty",
52 description => "the output format for waypoints, can be KML, GeoJSON or CSV (one or many, comma-separated)",
56 osm_tag_default_icon => {
58 example => "icon.png",
59 description => "the icon attached to a tag, displayed on the map for tagged pages",
63 osm_openlayers_url => {
65 example => "http://www.openlayers.org/api/OpenLayers.js",
66 description => "Url for the OpenLayers.js file",
72 example => "/tiles/\${z}/\${x}/\${y}.png",
73 description => "Url to get map tiles from (if none specified, uses the openstreetmap server, see http://wiki.openstreetmap.org/wiki/Creating_your_own_tiles for more info on serving your own tiles)",
80 sub register_rendered_files {
86 my %formats = get_formats();
87 if ($formats{'GeoJSON'}) {
88 will_render($page, "$map/pois.json");
90 if ($formats{'CSV'}) {
91 will_render($page, "$map/pois.txt");
93 if ($formats{'KML'}) {
94 will_render($page, "$map/pois.kml");
101 my $page = $params{page};
102 my $dest = $params{destpage};
103 my $loc = $params{loc}; # sanitized below
104 my $lat = $params{lat}; # sanitized below
105 my $lon = $params{lon}; # sanitized below
106 my $href = $params{href};
108 my ($width, $height, $float);
109 $height = scrub($params{'height'} || "300px", $page, $dest); # sanitized here
110 $width = scrub($params{'width'} || "500px", $page, $dest); # sanitized here
111 $float = (defined($params{'right'}) && 'right') || (defined($params{'left'}) && 'left'); # sanitized here
113 my $zoom = scrub($params{'zoom'} // $config{'osm_default_zoom'} // 15, $page, $dest); # sanitized below
115 $map = $params{'map'} || 'map';
117 $map = scrub($map, $page, $dest); # sanitized here
118 my $name = scrub($params{'name'} || $map, $page, $dest);
120 if (defined($lon) || defined($lat) || defined($loc)) {
121 ($lon, $lat) = scrub_lonlat($loc, $lon, $lat);
124 if ($zoom !~ /^\d\d?$/ || $zoom < 2 || $zoom > 18) {
128 if (! defined $href || ! length $href) {
129 $href=IkiWiki::cgiurl(
135 register_rendered_files($map, $page, $dest);
137 $pagestate{$page}{'osm'}{$map}{'displays'}{$name} = {
143 editable => defined($params{'editable'}),
148 return "<div id=\"mapdiv-$name\"></div>";
151 sub process_waypoint {
153 my $loc = $params{'loc'}; # sanitized below
154 my $lat = $params{'lat'}; # sanitized below
155 my $lon = $params{'lon'}; # sanitized below
156 my $page = $params{'page'}; # not sanitized?
157 my $dest = $params{'destpage'}; # not sanitized?
158 my $hidden = defined($params{'hidden'}); # sanitized here
159 my ($p) = $page =~ /(?:^|\/)([^\/]+)\/?$/; # shorter page name
160 my $name = scrub($params{'name'} || $p, $page, $dest); # sanitized here
161 my $desc = scrub($params{'desc'} || '', $page, $dest); # sanitized here
162 my $zoom = scrub($params{'zoom'} // $config{'osm_default_zoom'} // 15, $page, $dest); # sanitized below
163 my $icon = $config{'osm_default_icon'} || "ikiwiki/images/osm.png"; # sanitized: we trust $config
164 my $map = scrub($params{'map'} || 'map', $page, $dest); # sanitized here
165 my $alt = $config{'osm_alt'} ? "alt=\"$config{'osm_alt'}\"" : ''; # sanitized: we trust $config
166 if ($zoom !~ /^\d\d?$/ || $zoom < 2 || $zoom > 18) {
170 ($lon, $lat) = scrub_lonlat($loc, $lon, $lat);
171 if (!defined($lat) || !defined($lon)) {
172 error("Must specify lat and lon");
175 my $tag = $params{'tag'};
176 foreach my $t (keys %{$typedlinks{$page}{'tag'}}) {
177 if ($icon = get_tag_icon($t)) {
181 $t =~ s!/$config{'tagbase'}/!!;
182 if ($icon = get_tag_icon($t)) {
187 $icon = urlto($icon, $dest, 1);
188 $tag = '' unless $tag;
189 register_rendered_files($map, $page, $dest);
190 $pagestate{$page}{'osm'}{$map}{'waypoints'}{$name} = {
197 # How to link back to the page from the map, not to be
198 # confused with the URL of the map itself sent to the
199 # embeded map below. Note: used in generated KML etc file,
200 # so must be absolute.
201 href => urlto($page),
204 my $mapurl = IkiWiki::cgiurl(
212 if (defined($params{'embed'})) {
213 $output .= preprocess(%params,
218 $output .= "<a href=\"$mapurl\"><img class=\"img\" src=\"$icon\" $alt /></a>";
223 # get the icon from the given tag
224 sub get_tag_icon($) {
226 # look for an icon attached to the tag
227 my $attached = $tag . '/' . $config{'osm_tag_default_icon'};
228 if (srcfile($attached)) {
236 sub scrub_lonlat($$$) {
237 my ($loc, $lon, $lat) = @_;
239 if ($loc =~ /^\s*(\-?\d+(?:\.\d*°?|(?:°?|\s)\s*\d+(?:\.\d*\'?|(?:\'|\s)\s*\d+(?:\.\d*)?\"?|\'?)°?)[NS]?)\s*\,?\;?\s*(\-?\d+(?:\.\d*°?|(?:°?|\s)\s*\d+(?:\.\d*\'?|(?:\'|\s)\s*\d+(?:\.\d*)?\"?|\'?)°?)[EW]?)\s*$/) {
248 if ($lat =~ /^(\-?)(\d+)(?:(\.\d*)°?|(?:°|\s)\s*(\d+)(?:(\.\d*)\'?|(?:\'|\s)\s*(\d+(?:\.\d*)?\"?)|\'?)|°?)\s*([NS])?\s*$/) {
249 $lat = $2 + ($3//0) + ((($4//0) + (($5//0) + (($6//0)/60.)))/60.);
250 if (($1 eq '-') || (($7//'') eq 'S')) {
259 if ($lon =~ /^(\-?)(\d+)(?:(\.\d*)°?|(?:°|\s)\s*(\d+)(?:(\.\d*)\'?|(?:\'|\s)\s*(\d+(?:\.\d*)?\"?)|\'?)|°?)\s*([EW])?$/) {
260 $lon = $2 + ($3//0) + ((($4//0) + (($5//0) + (($6//0)/60.)))/60.);
261 if (($1 eq '-') || (($7//'') eq 'W')) {
269 if ($lat < -90 || $lat > 90 || $lon < -180 || $lon > 180) {
270 error("Location out of range");
277 my %linestrings = ();
279 foreach my $page (keys %pagestate) {
280 if (exists $pagestate{$page}{'osm'}) {
281 foreach my $map (keys %{$pagestate{$page}{'osm'}}) {
282 foreach my $name (keys %{$pagestate{$page}{'osm'}{$map}{'waypoints'}}) {
283 debug("found waypoint $name");
284 $waypoints{$map}{$name} = $pagestate{$page}{'osm'}{$map}{'waypoints'}{$name};
290 foreach my $page (keys %pagestate) {
291 if (exists $pagestate{$page}{'osm'}) {
292 foreach my $map (keys %{$pagestate{$page}{'osm'}}) {
293 # examine the links on this page
294 foreach my $name (keys %{$pagestate{$page}{'osm'}{$map}{'waypoints'}}) {
295 if (exists $links{$page}) {
296 foreach my $otherpage (@{$links{$page}}) {
297 if (exists $waypoints{$map}{$otherpage}) {
298 push(@{$linestrings{$map}}, [
299 [ $waypoints{$map}{$name}{'lon'}, $waypoints{$map}{$name}{'lat'} ],
300 [ $waypoints{$map}{$otherpage}{'lon'}, $waypoints{$map}{$otherpage}{'lat'} ]
307 # clear the state, it will be regenerated on the next parse
308 # the idea here is to clear up removed waypoints...
309 $pagestate{$page}{'osm'} = ();
313 my %formats = get_formats();
314 if ($formats{'GeoJSON'}) {
315 writejson(\%waypoints, \%linestrings);
317 if ($formats{'CSV'}) {
318 writecsvs(\%waypoints, \%linestrings);
320 if ($formats{'KML'}) {
321 writekml(\%waypoints, \%linestrings);
326 my %waypoints = %{$_[0]};
327 my %linestrings = %{$_[1]};
330 foreach my $map (keys %waypoints) {
331 my %geojson = ( "type" => "FeatureCollection", "features" => []);
332 foreach my $name (keys %{$waypoints{$map}}) {
333 my %marker = ( "type" => "Feature",
334 "geometry" => { "type" => "Point", "coordinates" => [ $waypoints{$map}{$name}{'lon'}, $waypoints{$map}{$name}{'lat'} ] },
335 "properties" => $waypoints{$map}{$name} );
336 push @{$geojson{'features'}}, \%marker;
338 foreach my $linestring (@{$linestrings{$map}}) {
339 my %json = ( "type" => "Feature",
340 "geometry" => { "type" => "LineString", "coordinates" => $linestring });
341 push @{$geojson{'features'}}, \%json;
343 writefile("pois.json", $config{destdir} . "/$map", to_json(\%geojson));
348 my %waypoints = %{$_[0]};
349 my %linestrings = %{$_[1]};
350 eval q{use XML::Writer};
352 foreach my $map (keys %waypoints) {
354 my $writer = XML::Writer->new( OUTPUT => \$output,
355 DATA_MODE => 1, ENCODING => 'UTF-8');
357 $writer->startTag("kml", "xmlns" => "http://www.opengis.net/kml/2.2");
358 $writer->startTag("Document");
360 # first pass: get the icons
361 foreach my $name (keys %{$waypoints{$map}}) {
362 my %options = %{$waypoints{$map}{$name}};
363 $writer->startTag("Style", id => $options{tag});
364 $writer->startTag("IconStyle");
365 $writer->startTag("Icon");
366 $writer->startTag("href");
367 $writer->characters($options{icon});
374 foreach my $name (keys %{$waypoints{$map}}) {
375 my %options = %{$waypoints{$map}{$name}};
376 $writer->startTag("Placemark");
377 $writer->startTag("name");
378 $writer->characters($name);
380 $writer->startTag("styleUrl");
381 $writer->characters('#' . $options{tag});
383 #$writer->emptyTag('atom:link', href => $options{href});
384 # to make it easier for us as the atom:link parameter is
385 # hard to access from javascript
386 $writer->startTag('href');
387 $writer->characters($options{href});
389 $writer->startTag("description");
390 $writer->characters($options{desc});
392 $writer->startTag("Point");
393 $writer->startTag("coordinates");
394 $writer->characters($options{lon} . "," . $options{lat});
401 foreach my $linestring (@{$linestrings{$map}}) {
402 $writer->startTag("Placemark");
403 $writer->startTag("name");
404 $writer->characters("linestring " . $i++);
406 $writer->startTag("LineString");
407 $writer->startTag("coordinates");
409 foreach my $coord (@{$linestring}) {
410 $str .= join(',', @{$coord}) . " \n";
412 $writer->characters($str);
421 writefile("pois.kml", $config{destdir} . "/$map", $output);
426 my %waypoints = %{$_[0]};
427 foreach my $map (keys %waypoints) {
428 my $poisf = "lat\tlon\ttitle\tdescription\ticon\ticonSize\ticonOffset\n";
429 foreach my $name (keys %{$waypoints{$map}}) {
430 my %options = %{$waypoints{$map}{$name}};
432 $options{'lat'} . "\t" .
433 $options{'lon'} . "\t" .
435 $options{'desc'} . '<br /><a href="' . $options{'page'} . '">' . $name . "</a>\t" .
436 $options{'icon'} . "\n";
439 writefile("pois.txt", $config{destdir} . "/$map", $poisf);
443 # pipe some data through the HTML scrubber
445 # code taken from the meta.pm plugin
447 if (IkiWiki::Plugin::htmlscrubber->can("sanitize")) {
448 return IkiWiki::Plugin::htmlscrubber::sanitize(
449 content => shift, page => shift, destpage => shift);
456 # taken from toggle.pm
460 if ($params{content}=~m!<div[^>]*id="mapdiv-[^"]*"[^>]*>!g) {
461 if (! ($params{content}=~s!</body>!include_javascript($params{page})."</body>"!em)) {
462 # no <body> tag, probably in preview mode
463 $params{content}=$params{content} . include_javascript($params{page});
466 return $params{content};
469 sub preferred_format() {
470 if (!defined($config{'osm_format'}) || !$config{'osm_format'}) {
471 $config{'osm_format'} = 'KML';
473 my @spl = split(/, */, $config{'osm_format'});
478 if (!defined($config{'osm_format'}) || !$config{'osm_format'}) {
479 $config{'osm_format'} = 'KML';
481 map { $_ => 1 } split(/, */, $config{'osm_format'});
484 sub include_javascript ($) {
488 if (exists $pagestate{$page}{'osm'}) {
489 foreach my $map (keys %{$pagestate{$page}{'osm'}}) {
490 foreach my $name (keys %{$pagestate{$page}{'osm'}{$map}{'displays'}}) {
491 $loader .= map_setup_code($map, $name, %{$pagestate{$page}{'osm'}{$map}{'displays'}{$name}});
496 return embed_map_code($page) . "<script type=\"text/javascript\" charset=\"utf-8\">$loader</script>";
506 return unless defined $cgi->param('do') &&
507 $cgi->param("do") eq "osm";
509 IkiWiki::loadindex();
511 IkiWiki::decode_cgi_utf8($cgi);
513 my $map = $cgi->param('map');
514 if (!defined $map || $map !~ /^[a-z]*$/) {
515 error("invalid map parameter");
518 print "Content-Type: text/html\r\n";
520 print "<html><body>";
521 print "<div id=\"mapdiv-$map\"></div>";
522 print embed_map_code();
523 print "<script type=\"text/javascript\" charset=\"utf-8\">";
524 print map_setup_code($map, $map,
525 lat => "urlParams['lat']",
526 lon => "urlParams['lon']",
527 zoom => "urlParams['zoom']",
532 print "</body></html>";
537 sub embed_map_code(;$) {
539 my $olurl = $config{osm_openlayers_url} || "http://www.openlayers.org/api/OpenLayers.js";
540 return '<script src="'.$olurl.'" type="text/javascript" charset="utf-8"></script>'.
541 '<script src="'.urlto("ikiwiki/osm.js", $page).
542 '" type="text/javascript" charset="utf-8"></script>'."\n";
545 sub map_setup_code($;@) {
550 my $mapurl = $config{osm_map_url};
555 $options{'format'} = preferred_format();
557 my %formats = get_formats();
558 if ($formats{'GeoJSON'}) {
559 $options{'jsonurl'} = urlto($map."/pois.json");
561 if ($formats{'CSV'}) {
562 $options{'csvurl'} = urlto($map."/pois.txt");
564 if ($formats{'KML'}) {
565 $options{'kmlurl'} = urlto($map."/pois.kml");
569 $options{'mapurl'} = $mapurl;
572 return "mapsetup('mapdiv-$name', " . to_json(\%options) . ");";