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",
73 sub register_rendered_files {
79 my %formats = get_formats();
80 if ($formats{'GeoJSON'}) {
81 will_render($page, "$map/pois.json");
83 if ($formats{'CSV'}) {
84 will_render($page, "$map/pois.txt");
86 if ($formats{'KML'}) {
87 will_render($page, "$map/pois.kml");
94 my $page = $params{page};
95 my $dest = $params{destpage};
96 my $loc = $params{loc}; # sanitized below
97 my $lat = $params{lat}; # sanitized below
98 my $lon = $params{lon}; # sanitized below
99 my $href = $params{href};
101 my ($width, $height, $float);
102 $height = scrub($params{'height'} || "300px", $page, $dest); # sanitized here
103 $width = scrub($params{'width'} || "500px", $page, $dest); # sanitized here
104 $float = (defined($params{'right'}) && 'right') || (defined($params{'left'}) && 'left'); # sanitized here
106 my $zoom = scrub($params{'zoom'} // $config{'osm_default_zoom'} // 15, $page, $dest); # sanitized below
108 $map = $params{'map'} || 'map';
110 $map = scrub($map, $page, $dest); # sanitized here
111 my $name = scrub($params{'name'} || $map, $page, $dest);
113 if (defined($lon) || defined($lat) || defined($loc)) {
114 ($lon, $lat) = scrub_lonlat($loc, $lon, $lat);
117 if ($zoom !~ /^\d\d?$/ || $zoom < 2 || $zoom > 18) {
121 if (! defined $href || ! length $href) {
122 $href=IkiWiki::cgiurl(
128 register_rendered_files($map, $page, $dest);
130 $pagestate{$page}{'osm'}{$map}{'displays'}{$name} = {
136 editable => defined($params{'editable'}),
141 return "<div id=\"mapdiv-$name\"></div>";
144 sub process_waypoint {
146 my $loc = $params{'loc'}; # sanitized below
147 my $lat = $params{'lat'}; # sanitized below
148 my $lon = $params{'lon'}; # sanitized below
149 my $page = $params{'page'}; # not sanitized?
150 my $dest = $params{'destpage'}; # not sanitized?
151 my $hidden = defined($params{'hidden'}); # sanitized here
152 my ($p) = $page =~ /(?:^|\/)([^\/]+)\/?$/; # shorter page name
153 my $name = scrub($params{'name'} || $p, $page, $dest); # sanitized here
154 my $desc = scrub($params{'desc'} || '', $page, $dest); # sanitized here
155 my $zoom = scrub($params{'zoom'} // $config{'osm_default_zoom'} // 15, $page, $dest); # sanitized below
156 my $icon = $config{'osm_default_icon'} || "ikiwiki/images/osm.png"; # sanitized: we trust $config
157 my $map = scrub($params{'map'} || 'map', $page, $dest); # sanitized here
158 my $alt = $config{'osm_alt'} ? "alt=\"$config{'osm_alt'}\"" : ''; # sanitized: we trust $config
159 if ($zoom !~ /^\d\d?$/ || $zoom < 2 || $zoom > 18) {
163 ($lon, $lat) = scrub_lonlat($loc, $lon, $lat);
164 if (!defined($lat) || !defined($lon)) {
165 error("Must specify lat and lon");
168 my $tag = $params{'tag'};
169 foreach my $t (keys %{$typedlinks{$page}{'tag'}}) {
170 if ($icon = get_tag_icon($t)) {
174 $t =~ s!/$config{'tagbase'}/!!;
175 if ($icon = get_tag_icon($t)) {
180 $icon = urlto($icon, $dest, 1);
181 $tag = '' unless $tag;
182 register_rendered_files($map, $page, $dest);
183 $pagestate{$page}{'osm'}{$map}{'waypoints'}{$name} = {
190 # How to link back to the page from the map, not to be
191 # confused with the URL of the map itself sent to the
192 # embeded map below. Note: used in generated KML etc file,
193 # so must be absolute.
194 href => urlto($page),
197 my $mapurl = IkiWiki::cgiurl(
205 if (defined($params{'embed'})) {
206 $output .= preprocess(%params,
211 $output .= "<a href=\"$mapurl\"><img class=\"img\" src=\"$icon\" $alt /></a>";
216 # get the icon from the given tag
217 sub get_tag_icon($) {
219 # look for an icon attached to the tag
220 my $attached = $tag . '/' . $config{'osm_tag_default_icon'};
221 if (srcfile($attached)) {
229 sub scrub_lonlat($$$) {
230 my ($loc, $lon, $lat) = @_;
232 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*$/) {
241 if ($lat =~ /^(\-?)(\d+)(?:(\.\d*)°?|(?:°|\s)\s*(\d+)(?:(\.\d*)\'?|(?:\'|\s)\s*(\d+(?:\.\d*)?\"?)|\'?)|°?)\s*([NS])?\s*$/) {
242 $lat = $2 + ($3//0) + ((($4//0) + (($5//0) + (($6//0)/60.)))/60.);
243 if (($1 eq '-') || (($7//'') eq 'S')) {
252 if ($lon =~ /^(\-?)(\d+)(?:(\.\d*)°?|(?:°|\s)\s*(\d+)(?:(\.\d*)\'?|(?:\'|\s)\s*(\d+(?:\.\d*)?\"?)|\'?)|°?)\s*([EW])?$/) {
253 $lon = $2 + ($3//0) + ((($4//0) + (($5//0) + (($6//0)/60.)))/60.);
254 if (($1 eq '-') || (($7//'') eq 'W')) {
262 if ($lat < -90 || $lat > 90 || $lon < -180 || $lon > 180) {
263 error("Location out of range");
270 my %linestrings = ();
272 foreach my $page (keys %pagestate) {
273 if (exists $pagestate{$page}{'osm'}) {
274 foreach my $map (keys %{$pagestate{$page}{'osm'}}) {
275 foreach my $name (keys %{$pagestate{$page}{'osm'}{$map}{'waypoints'}}) {
276 debug("found waypoint $name");
277 $waypoints{$map}{$name} = $pagestate{$page}{'osm'}{$map}{'waypoints'}{$name};
283 foreach my $page (keys %pagestate) {
284 if (exists $pagestate{$page}{'osm'}) {
285 foreach my $map (keys %{$pagestate{$page}{'osm'}}) {
286 # examine the links on this page
287 foreach my $name (keys %{$pagestate{$page}{'osm'}{$map}{'waypoints'}}) {
288 if (exists $links{$page}) {
289 foreach my $otherpage (@{$links{$page}}) {
290 if (exists $waypoints{$map}{$otherpage}) {
291 push(@{$linestrings{$map}}, [
292 [ $waypoints{$map}{$name}{'lon'}, $waypoints{$map}{$name}{'lat'} ],
293 [ $waypoints{$map}{$otherpage}{'lon'}, $waypoints{$map}{$otherpage}{'lat'} ]
300 # clear the state, it will be regenerated on the next parse
301 # the idea here is to clear up removed waypoints...
302 $pagestate{$page}{'osm'} = ();
306 my %formats = get_formats();
307 if ($formats{'GeoJSON'}) {
308 writejson(\%waypoints, \%linestrings);
310 if ($formats{'CSV'}) {
311 writecsvs(\%waypoints, \%linestrings);
313 if ($formats{'KML'}) {
314 writekml(\%waypoints, \%linestrings);
319 my %waypoints = %{$_[0]};
320 my %linestrings = %{$_[1]};
323 foreach my $map (keys %waypoints) {
324 my %geojson = ( "type" => "FeatureCollection", "features" => []);
325 foreach my $name (keys %{$waypoints{$map}}) {
326 my %marker = ( "type" => "Feature",
327 "geometry" => { "type" => "Point", "coordinates" => [ $waypoints{$map}{$name}{'lon'}, $waypoints{$map}{$name}{'lat'} ] },
328 "properties" => $waypoints{$map}{$name} );
329 push @{$geojson{'features'}}, \%marker;
331 foreach my $linestring (@{$linestrings{$map}}) {
332 my %json = ( "type" => "Feature",
333 "geometry" => { "type" => "LineString", "coordinates" => $linestring });
334 push @{$geojson{'features'}}, \%json;
336 writefile("pois.json", $config{destdir} . "/$map", to_json(\%geojson));
341 my %waypoints = %{$_[0]};
342 my %linestrings = %{$_[1]};
343 eval q{use XML::Writer};
345 foreach my $map (keys %waypoints) {
347 my $writer = XML::Writer->new( OUTPUT => \$output,
348 DATA_MODE => 1, ENCODING => 'UTF-8');
350 $writer->startTag("kml", "xmlns" => "http://www.opengis.net/kml/2.2");
352 # first pass: get the icons
353 foreach my $name (keys %{$waypoints{$map}}) {
354 my %options = %{$waypoints{$map}{$name}};
355 $writer->startTag("Style", id => $options{tag});
356 $writer->startTag("IconStyle");
357 $writer->startTag("Icon");
358 $writer->startTag("href");
359 $writer->characters($options{icon});
366 foreach my $name (keys %{$waypoints{$map}}) {
367 my %options = %{$waypoints{$map}{$name}};
368 $writer->startTag("Placemark");
369 $writer->startTag("name");
370 $writer->characters($name);
372 $writer->startTag("styleUrl");
373 $writer->characters('#' . $options{tag});
375 #$writer->emptyTag('atom:link', href => $options{href});
376 # to make it easier for us as the atom:link parameter is
377 # hard to access from javascript
378 $writer->startTag('href');
379 $writer->characters($options{href});
381 $writer->startTag("description");
382 $writer->characters($options{desc});
384 $writer->startTag("Point");
385 $writer->startTag("coordinates");
386 $writer->characters($options{lon} . "," . $options{lat});
393 foreach my $linestring (@{$linestrings{$map}}) {
394 $writer->startTag("Placemark");
395 $writer->startTag("name");
396 $writer->characters("linestring " . $i++);
398 $writer->startTag("LineString");
399 $writer->startTag("coordinates");
401 foreach my $coord (@{$linestring}) {
402 $str .= join(',', @{$coord}) . " \n";
404 $writer->characters($str);
412 writefile("pois.kml", $config{destdir} . "/$map", $output);
417 my %waypoints = %{$_[0]};
418 foreach my $map (keys %waypoints) {
419 my $poisf = "lat\tlon\ttitle\tdescription\ticon\ticonSize\ticonOffset\n";
420 foreach my $name (keys %{$waypoints{$map}}) {
421 my %options = %{$waypoints{$map}{$name}};
423 $options{'lat'} . "\t" .
424 $options{'lon'} . "\t" .
426 $options{'desc'} . '<br /><a href="' . $options{'page'} . '">' . $name . "</a>\t" .
427 $options{'icon'} . "\n";
430 writefile("pois.txt", $config{destdir} . "/$map", $poisf);
434 # pipe some data through the HTML scrubber
436 # code taken from the meta.pm plugin
438 if (IkiWiki::Plugin::htmlscrubber->can("sanitize")) {
439 return IkiWiki::Plugin::htmlscrubber::sanitize(
440 content => shift, page => shift, destpage => shift);
447 # taken from toggle.pm
451 if ($params{content}=~m!<div[^>]*id="mapdiv-[^"]*"[^>]*>!g) {
452 if (! ($params{content}=~s!</body>!include_javascript($params{page})."</body>"!em)) {
453 # no <body> tag, probably in preview mode
454 $params{content}=$params{content} . include_javascript($params{page});
457 return $params{content};
460 sub preferred_format() {
461 if (!defined($config{'osm_format'}) || !$config{'osm_format'}) {
462 $config{'osm_format'} = 'KML';
464 my @spl = split(/, */, $config{'osm_format'});
469 if (!defined($config{'osm_format'}) || !$config{'osm_format'}) {
470 $config{'osm_format'} = 'KML';
472 map { $_ => 1 } split(/, */, $config{'osm_format'});
475 sub include_javascript ($) {
479 if (exists $pagestate{$page}{'osm'}) {
480 foreach my $map (keys %{$pagestate{$page}{'osm'}}) {
481 foreach my $name (keys %{$pagestate{$page}{'osm'}{$map}{'displays'}}) {
482 $loader .= map_setup_code($map, $name, %{$pagestate{$page}{'osm'}{$map}{'displays'}{$name}});
487 return embed_map_code($page) . "<script type=\"text/javascript\" charset=\"utf-8\">$loader</script>";
497 return unless defined $cgi->param('do') &&
498 $cgi->param("do") eq "osm";
500 IkiWiki::loadindex();
502 IkiWiki::decode_cgi_utf8($cgi);
504 my $map = $cgi->param('map');
505 if (!defined $map || $map !~ /^[a-z]*$/) {
506 error("invalid map parameter");
509 print "Content-Type: text/html\r\n";
511 print "<html><body>";
512 print "<div id=\"mapdiv-$map\"></div>";
513 print embed_map_code();
514 print "<script type=\"text/javascript\" charset=\"utf-8\">";
515 print map_setup_code($map, $map,
516 lat => "urlParams['lat']",
517 lon => "urlParams['lon']",
518 zoom => "urlParams['zoom']",
523 print "</body></html>";
528 sub embed_map_code(;$) {
530 my $olurl = $config{osm_openlayers_url} || "http://www.openlayers.org/api/OpenLayers.js";
531 return '<script src="'.$olurl.'" type="text/javascript" charset="utf-8"></script>'.
532 '<script src="'.urlto("ikiwiki/osm.js", $page).
533 '" type="text/javascript" charset="utf-8"></script>'."\n";
536 sub map_setup_code($;@) {
544 $options{'format'} = preferred_format();
546 my %formats = get_formats();
547 if ($formats{'GeoJSON'}) {
548 $options{'jsonurl'} = urlto($map."/pois.json");
550 if ($formats{'CSV'}) {
551 $options{'csvurl'} = urlto($map."/pois.txt");
553 if ($formats{'KML'}) {
554 $options{'kmlurl'} = urlto($map."/pois.kml");
557 return "mapsetup('mapdiv-$name', " . to_json(\%options) . ");";