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 => { 'OSM', 'GoogleSattelite' },
73 description => "Layers to use in the map. Can be either the 'OSM' string or a type option for Google maps (GoogleNormal, GoogleSatellite, GoogleHybrid or GooglePhysical). It can also be an arbitrary URL in a syntax acceptable for OpenLayers.Layer.OSM.url parameter.",
77 osm_google_apikey => {
80 description => "Google maps API key, Google layer not used if missing, see https://code.google.com/apis/console/ to get an API key",
86 sub register_rendered_files {
92 my %formats = get_formats();
93 if ($formats{'GeoJSON'}) {
94 will_render($page, "$map/pois.json");
96 if ($formats{'CSV'}) {
97 will_render($page, "$map/pois.txt");
99 if ($formats{'KML'}) {
100 will_render($page, "$map/pois.kml");
107 my $page = $params{page};
108 my $dest = $params{destpage};
109 my $loc = $params{loc}; # sanitized below
110 my $lat = $params{lat}; # sanitized below
111 my $lon = $params{lon}; # sanitized below
112 my $href = $params{href};
114 my ($width, $height, $float);
115 $height = scrub($params{'height'} || "300px", $page, $dest); # sanitized here
116 $width = scrub($params{'width'} || "500px", $page, $dest); # sanitized here
117 $float = (defined($params{'right'}) && 'right') || (defined($params{'left'}) && 'left'); # sanitized here
119 my $zoom = scrub($params{'zoom'} // $config{'osm_default_zoom'} // 15, $page, $dest); # sanitized below
121 $map = $params{'map'} || 'map';
123 $map = scrub($map, $page, $dest); # sanitized here
124 my $name = scrub($params{'name'} || $map, $page, $dest);
126 if (defined($lon) || defined($lat) || defined($loc)) {
127 ($lon, $lat) = scrub_lonlat($loc, $lon, $lat);
130 if ($zoom !~ /^\d\d?$/ || $zoom < 2 || $zoom > 18) {
134 if (! defined $href || ! length $href) {
135 $href=IkiWiki::cgiurl(
141 register_rendered_files($map, $page, $dest);
143 $pagestate{$page}{'osm'}{$map}{'displays'}{$name} = {
149 editable => defined($params{'editable'}),
153 google_apikey => $config{'osm_google_apikey'},
155 return "<div id=\"mapdiv-$name\"></div>";
158 sub process_waypoint {
160 my $loc = $params{'loc'}; # sanitized below
161 my $lat = $params{'lat'}; # sanitized below
162 my $lon = $params{'lon'}; # sanitized below
163 my $page = $params{'page'}; # not sanitized?
164 my $dest = $params{'destpage'}; # not sanitized?
165 my $hidden = defined($params{'hidden'}); # sanitized here
166 my ($p) = $page =~ /(?:^|\/)([^\/]+)\/?$/; # shorter page name
167 my $name = scrub($params{'name'} || $p, $page, $dest); # sanitized here
168 my $desc = scrub($params{'desc'} || '', $page, $dest); # sanitized here
169 my $zoom = scrub($params{'zoom'} // $config{'osm_default_zoom'} // 15, $page, $dest); # sanitized below
170 my $icon = $config{'osm_default_icon'} || "ikiwiki/images/osm.png"; # sanitized: we trust $config
171 my $map = scrub($params{'map'} || 'map', $page, $dest); # sanitized here
172 my $alt = $config{'osm_alt'} ? "alt=\"$config{'osm_alt'}\"" : ''; # sanitized: we trust $config
173 if ($zoom !~ /^\d\d?$/ || $zoom < 2 || $zoom > 18) {
177 ($lon, $lat) = scrub_lonlat($loc, $lon, $lat);
178 if (!defined($lat) || !defined($lon)) {
179 error("Must specify lat and lon");
182 my $tag = $params{'tag'};
183 foreach my $t (keys %{$typedlinks{$page}{'tag'}}) {
184 if ($icon = get_tag_icon($t)) {
188 $t =~ s!/$config{'tagbase'}/!!;
189 if ($icon = get_tag_icon($t)) {
194 $icon = urlto($icon, $dest, 1);
195 $tag = '' unless $tag;
196 register_rendered_files($map, $page, $dest);
197 $pagestate{$page}{'osm'}{$map}{'waypoints'}{$name} = {
204 # How to link back to the page from the map, not to be
205 # confused with the URL of the map itself sent to the
206 # embeded map below. Note: used in generated KML etc file,
207 # so must be absolute.
208 href => urlto($page),
211 my $mapurl = IkiWiki::cgiurl(
219 if (defined($params{'embed'})) {
220 $output .= preprocess(%params,
225 $output .= "<a href=\"$mapurl\"><img class=\"img\" src=\"$icon\" $alt /></a>";
230 # get the icon from the given tag
231 sub get_tag_icon($) {
233 # look for an icon attached to the tag
234 my $attached = $tag . '/' . $config{'osm_tag_default_icon'};
235 if (srcfile($attached)) {
243 sub scrub_lonlat($$$) {
244 my ($loc, $lon, $lat) = @_;
246 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*$/) {
255 if ($lat =~ /^(\-?)(\d+)(?:(\.\d*)°?|(?:°|\s)\s*(\d+)(?:(\.\d*)\'?|(?:\'|\s)\s*(\d+(?:\.\d*)?\"?)|\'?)|°?)\s*([NS])?\s*$/) {
256 $lat = $2 + ($3//0) + ((($4//0) + (($5//0) + (($6//0)/60.)))/60.);
257 if (($1 eq '-') || (($7//'') eq 'S')) {
266 if ($lon =~ /^(\-?)(\d+)(?:(\.\d*)°?|(?:°|\s)\s*(\d+)(?:(\.\d*)\'?|(?:\'|\s)\s*(\d+(?:\.\d*)?\"?)|\'?)|°?)\s*([EW])?$/) {
267 $lon = $2 + ($3//0) + ((($4//0) + (($5//0) + (($6//0)/60.)))/60.);
268 if (($1 eq '-') || (($7//'') eq 'W')) {
276 if ($lat < -90 || $lat > 90 || $lon < -180 || $lon > 180) {
277 error("Location out of range");
284 my %linestrings = ();
286 foreach my $page (keys %pagestate) {
287 if (exists $pagestate{$page}{'osm'}) {
288 foreach my $map (keys %{$pagestate{$page}{'osm'}}) {
289 foreach my $name (keys %{$pagestate{$page}{'osm'}{$map}{'waypoints'}}) {
290 debug("found waypoint $name");
291 $waypoints{$map}{$name} = $pagestate{$page}{'osm'}{$map}{'waypoints'}{$name};
297 foreach my $page (keys %pagestate) {
298 if (exists $pagestate{$page}{'osm'}) {
299 foreach my $map (keys %{$pagestate{$page}{'osm'}}) {
300 # examine the links on this page
301 foreach my $name (keys %{$pagestate{$page}{'osm'}{$map}{'waypoints'}}) {
302 if (exists $links{$page}) {
303 foreach my $otherpage (@{$links{$page}}) {
304 if (exists $waypoints{$map}{$otherpage}) {
305 push(@{$linestrings{$map}}, [
306 [ $waypoints{$map}{$name}{'lon'}, $waypoints{$map}{$name}{'lat'} ],
307 [ $waypoints{$map}{$otherpage}{'lon'}, $waypoints{$map}{$otherpage}{'lat'} ]
314 # clear the state, it will be regenerated on the next parse
315 # the idea here is to clear up removed waypoints...
316 $pagestate{$page}{'osm'} = ();
320 my %formats = get_formats();
321 if ($formats{'GeoJSON'}) {
322 writejson(\%waypoints, \%linestrings);
324 if ($formats{'CSV'}) {
325 writecsvs(\%waypoints, \%linestrings);
327 if ($formats{'KML'}) {
328 writekml(\%waypoints, \%linestrings);
333 my %waypoints = %{$_[0]};
334 my %linestrings = %{$_[1]};
337 foreach my $map (keys %waypoints) {
338 my %geojson = ( "type" => "FeatureCollection", "features" => []);
339 foreach my $name (keys %{$waypoints{$map}}) {
340 my %marker = ( "type" => "Feature",
341 "geometry" => { "type" => "Point", "coordinates" => [ $waypoints{$map}{$name}{'lon'}, $waypoints{$map}{$name}{'lat'} ] },
342 "properties" => $waypoints{$map}{$name} );
343 push @{$geojson{'features'}}, \%marker;
345 foreach my $linestring (@{$linestrings{$map}}) {
346 my %json = ( "type" => "Feature",
347 "geometry" => { "type" => "LineString", "coordinates" => $linestring });
348 push @{$geojson{'features'}}, \%json;
350 writefile("pois.json", $config{destdir} . "/$map", to_json(\%geojson));
355 my %waypoints = %{$_[0]};
356 my %linestrings = %{$_[1]};
357 eval q{use XML::Writer};
359 foreach my $map (keys %waypoints) {
361 my $writer = XML::Writer->new( OUTPUT => \$output,
362 DATA_MODE => 1, ENCODING => 'UTF-8');
364 $writer->startTag("kml", "xmlns" => "http://www.opengis.net/kml/2.2");
365 $writer->startTag("Document");
367 # first pass: get the icons
368 foreach my $name (keys %{$waypoints{$map}}) {
369 my %options = %{$waypoints{$map}{$name}};
370 $writer->startTag("Style", id => $options{tag});
371 $writer->startTag("IconStyle");
372 $writer->startTag("Icon");
373 $writer->startTag("href");
374 $writer->characters($options{icon});
381 foreach my $name (keys %{$waypoints{$map}}) {
382 my %options = %{$waypoints{$map}{$name}};
383 $writer->startTag("Placemark");
384 $writer->startTag("name");
385 $writer->characters($name);
387 $writer->startTag("styleUrl");
388 $writer->characters('#' . $options{tag});
390 #$writer->emptyTag('atom:link', href => $options{href});
391 # to make it easier for us as the atom:link parameter is
392 # hard to access from javascript
393 $writer->startTag('href');
394 $writer->characters($options{href});
396 $writer->startTag("description");
397 $writer->characters($options{desc});
399 $writer->startTag("Point");
400 $writer->startTag("coordinates");
401 $writer->characters($options{lon} . "," . $options{lat});
408 foreach my $linestring (@{$linestrings{$map}}) {
409 $writer->startTag("Placemark");
410 $writer->startTag("name");
411 $writer->characters("linestring " . $i++);
413 $writer->startTag("LineString");
414 $writer->startTag("coordinates");
416 foreach my $coord (@{$linestring}) {
417 $str .= join(',', @{$coord}) . " \n";
419 $writer->characters($str);
428 writefile("pois.kml", $config{destdir} . "/$map", $output);
433 my %waypoints = %{$_[0]};
434 foreach my $map (keys %waypoints) {
435 my $poisf = "lat\tlon\ttitle\tdescription\ticon\ticonSize\ticonOffset\n";
436 foreach my $name (keys %{$waypoints{$map}}) {
437 my %options = %{$waypoints{$map}{$name}};
439 $options{'lat'} . "\t" .
440 $options{'lon'} . "\t" .
442 $options{'desc'} . '<br /><a href="' . $options{'page'} . '">' . $name . "</a>\t" .
443 $options{'icon'} . "\n";
446 writefile("pois.txt", $config{destdir} . "/$map", $poisf);
450 # pipe some data through the HTML scrubber
452 # code taken from the meta.pm plugin
454 if (IkiWiki::Plugin::htmlscrubber->can("sanitize")) {
455 return IkiWiki::Plugin::htmlscrubber::sanitize(
456 content => shift, page => shift, destpage => shift);
463 # taken from toggle.pm
467 if ($params{content}=~m!<div[^>]*id="mapdiv-[^"]*"[^>]*>!g) {
468 if (! ($params{content}=~s!</body>!include_javascript($params{page})."</body>"!em)) {
469 # no <body> tag, probably in preview mode
470 $params{content}=$params{content} . include_javascript($params{page});
473 return $params{content};
476 sub preferred_format() {
477 if (!defined($config{'osm_format'}) || !$config{'osm_format'}) {
478 $config{'osm_format'} = 'KML';
480 my @spl = split(/, */, $config{'osm_format'});
485 if (!defined($config{'osm_format'}) || !$config{'osm_format'}) {
486 $config{'osm_format'} = 'KML';
488 map { $_ => 1 } split(/, */, $config{'osm_format'});
491 sub include_javascript ($) {
495 if (exists $pagestate{$page}{'osm'}) {
496 foreach my $map (keys %{$pagestate{$page}{'osm'}}) {
497 foreach my $name (keys %{$pagestate{$page}{'osm'}{$map}{'displays'}}) {
498 $loader .= map_setup_code($map, $name, %{$pagestate{$page}{'osm'}{$map}{'displays'}{$name}});
503 return embed_map_code($page) . "<script type=\"text/javascript\" charset=\"utf-8\">$loader</script>";
513 return unless defined $cgi->param('do') &&
514 $cgi->param("do") eq "osm";
516 IkiWiki::loadindex();
518 IkiWiki::decode_cgi_utf8($cgi);
520 my $map = $cgi->param('map');
521 if (!defined $map || $map !~ /^[a-z]*$/) {
522 error("invalid map parameter");
525 print "Content-Type: text/html\r\n";
527 print "<html><body>";
528 print "<div id=\"mapdiv-$map\"></div>";
529 print embed_map_code();
530 print "<script type=\"text/javascript\" charset=\"utf-8\">";
531 print map_setup_code($map, $map,
532 lat => "urlParams['lat']",
533 lon => "urlParams['lon']",
534 zoom => "urlParams['zoom']",
537 google_apikey => $config{'osm_google_apikey'},
540 print "</body></html>";
545 sub embed_map_code(;$) {
547 my $olurl = $config{osm_openlayers_url} || "http://www.openlayers.org/api/OpenLayers.js";
548 my $code = '<script src="'.$olurl.'" type="text/javascript" charset="utf-8"></script>'."\n".
549 '<script src="'.urlto("ikiwiki/osm.js", $page).
550 '" type="text/javascript" charset="utf-8"></script>'."\n";
551 if ($config{'osm_google_apikey'}) {
552 $code .= '<script src="http://maps.google.com/maps?file=api&v=2&key='.$config{'osm_google_apikey'}.'&sensor=false" type="text/javascript" charset="utf-8"></script>';
557 sub map_setup_code($;@) {
562 my $mapurl = $config{osm_map_url};
567 $options{'format'} = preferred_format();
569 my %formats = get_formats();
570 if ($formats{'GeoJSON'}) {
571 $options{'jsonurl'} = urlto($map."/pois.json");
573 if ($formats{'CSV'}) {
574 $options{'csvurl'} = urlto($map."/pois.txt");
576 if ($formats{'KML'}) {
577 $options{'kmlurl'} = urlto($map."/pois.kml");
581 $options{'mapurl'} = $mapurl;
583 $options{'layers'} = $config{osm_layers};
585 return "mapsetup('mapdiv-$name', " . to_json(\%options) . ");";