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 shon 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 so that pages tagged with that tag will have that icon on the map",
66 'test' => '/img/test.png',
67 'trailer' => '/img/trailer.png'
69 description => "tag to icon mapping, leading slash is important!",
77 my $page = $params{'page'};
78 my $dest = $params{'destpage'};
79 my $loc = $params{'loc'}; # sanitized below
80 my $lat = $params{'lat'}; # sanitized below
81 my $lon = $params{'lon'}; # sanitized below
82 my $href = $params{'href'};
84 my $fullscreen = defined($params{'fullscreen'}); # sanitized here
85 my ($width, $height, $float);
92 $height = scrub($params{'height'} || "300px", $page, $dest); # sanitized here
93 $width = scrub($params{'width'} || "500px", $page, $dest); # sanitized here
94 $float = (defined($params{'right'}) && 'right') || (defined($params{'left'}) && 'left'); # sanitized here
96 my $zoom = scrub($params{'zoom'} // $config{'osm_default_zoom'} // 15, $page, $dest); # sanitized below
99 $map = $params{'map'} || $page;
102 $map = $params{'map'} || 'map';
104 $map = scrub($map, $page, $dest); # sanitized here
105 my $name = scrub($params{'name'} || $map, $page, $dest);
107 if (defined($lon) || defined($lat) || defined($loc)) {
108 ($lon, $lat) = scrub_lonlat($loc, $lon, $lat);
111 if ($zoom !~ /^\d\d?$/ || $zoom < 2 || $zoom > 18) {
114 $pagestate{$page}{'osm'}{$map}{'displays'}{$name} = {
119 fullscreen => $fullscreen,
120 editable => defined($params{'editable'}),
125 return "<div id=\"mapdiv-$name\"></div>";
128 sub process_waypoint {
130 my $loc = $params{'loc'}; # sanitized below
131 my $lat = $params{'lat'}; # sanitized below
132 my $lon = $params{'lon'}; # sanitized below
133 my $page = $params{'page'}; # not sanitized?
134 my $dest = $params{'destpage'}; # not sanitized?
135 my $hidden = defined($params{'hidden'}); # sanitized here
136 my ($p) = $page =~ /(?:^|\/)([^\/]+)\/?$/; # shorter page name
137 my $name = scrub($params{'name'} || $p, $page, $dest); # sanitized here
138 my $desc = scrub($params{'desc'} || '', $page, $dest); # sanitized here
139 my $zoom = scrub($params{'zoom'} // $config{'osm_default_zoom'} // 15, $page, $dest); # sanitized below
140 my $icon = $config{'osm__default_icon'} || "/ikiwiki/images/osm.png"; # sanitized: we trust $config
141 my $map = scrub($params{'map'} || 'map', $page, $dest); # sanitized here
142 my $alt = $config{'osm_alt'} ? "alt=\"$config{'osm_alt'}\"" : ''; # sanitized: we trust $config
143 if ($zoom !~ /^\d\d?$/ || $zoom < 2 || $zoom > 18) {
147 ($lon, $lat) = scrub_lonlat($loc, $lon, $lat);
148 if (!defined($lat) || !defined($lon)) {
149 error("Must specify lat and lon");
152 my $tag = $params{'tag'};
154 if (!defined($config{'osm_tag_icons'}->{$tag})) {
155 error("invalid tag specified, see osm_tag_icons configuration or don't specify any");
157 $icon = $config{'osm_tag_icons'}->{$tag};
160 foreach my $t (keys %{$typedlinks{$page}{'tag'}}) {
161 if ($icon = get_tag_icon($t)) {
165 $t =~ s!/$config{'tagbase'}/!!;
166 if ($icon = get_tag_icon($t)) {
172 $icon = "/ikiwiki/images/osm.png" unless $icon;
173 $tag = '' unless $tag;
174 if ($page eq $dest) {
175 if (!defined($config{'osm_format'}) || !$config{'osm_format'}) {
176 $config{'osm_format'} = 'KML';
178 my %formats = map { $_ => 1 } split(/, */, $config{'osm_format'});
179 if ($formats{'GeoJSON'}) {
180 will_render($page,$config{destdir} . "/$map/pois.json");
182 if ($formats{'CSV'}) {
183 will_render($page,$config{destdir} . "/$map/pois.txt");
185 if ($formats{'KML'}) {
186 will_render($page,$config{destdir} . "/$map/pois.kml");
189 my $href = "/ikiwiki.cgi?do=osm&map=$map&lat=$lat&lon=$lon&zoom=$zoom";
190 if (defined($destsources{htmlpage($map)})) {
191 $href = urlto($map,$page) . "?lat=$lat&lon=$lon&zoom=$zoom";
193 $pagestate{$page}{'osm'}{$map}{'waypoints'}{$name} = {
200 # how to link back to the page from the map, not to be
201 # confused with the URL of the map itself sent to the
203 href => urlto($page,$map),
206 if (defined($params{'embed'})) {
207 $params{'href'} = $href; # propagate down to embeded
208 $output .= preprocess(%params);
211 $href =~ s!&!&!g;
212 $output .= "<a href=\"$href\"><img class=\"img\" src=\"$icon\" $alt /></a>";
217 # get the icon from the given tag
218 sub get_tag_icon($) {
220 # look for an icon attached to the tag
221 my $attached = $tag . '/' . $config{'osm_tag_default_icon'};
222 if (srcfile($attached)) {
225 # look for the old way: mappings
226 if ($config{'osm_tag_icons'}->{$tag}) {
227 return $config{'osm_tag_icons'}->{$tag};
234 sub scrub_lonlat($$$) {
235 my ($loc, $lon, $lat) = @_;
237 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*$/) {
246 if ($lat =~ /^(\-?)(\d+)(?:(\.\d*)°?|(?:°|\s)\s*(\d+)(?:(\.\d*)\'?|(?:\'|\s)\s*(\d+(?:\.\d*)?\"?)|\'?)|°?)\s*([NS])?\s*$/) {
247 $lat = $2 + ($3//0) + ((($4//0) + (($5//0) + (($6//0)/60.)))/60.);
248 if (($1 eq '-') || (($7//'') eq 'S')) {
257 if ($lon =~ /^(\-?)(\d+)(?:(\.\d*)°?|(?:°|\s)\s*(\d+)(?:(\.\d*)\'?|(?:\'|\s)\s*(\d+(?:\.\d*)?\"?)|\'?)|°?)\s*([EW])?$/) {
258 $lon = $2 + ($3//0) + ((($4//0) + (($5//0) + (($6//0)/60.)))/60.);
259 if (($1 eq '-') || (($7//'') eq 'W')) {
267 if ($lat < -90 || $lat > 90 || $lon < -180 || $lon > 180) {
268 error("Location out of range");
275 my %linestrings = ();
277 foreach my $page (keys %pagestate) {
278 if (exists $pagestate{$page}{'osm'}) {
279 foreach my $map (keys %{$pagestate{$page}{'osm'}}) {
280 foreach my $name (keys %{$pagestate{$page}{'osm'}{$map}{'waypoints'}}) {
281 debug("found waypoint $name");
282 $waypoints{$map}{$name} = $pagestate{$page}{'osm'}{$map}{'waypoints'}{$name};
288 foreach my $page (keys %pagestate) {
289 if (exists $pagestate{$page}{'osm'}) {
290 foreach my $map (keys %{$pagestate{$page}{'osm'}}) {
291 # examine the links on this page
292 foreach my $name (keys %{$pagestate{$page}{'osm'}{$map}{'waypoints'}}) {
293 if (exists $links{$page}) {
294 foreach my $otherpage (@{$links{$page}}) {
295 if (exists $waypoints{$map}{$otherpage}) {
296 push(@{$linestrings{$map}}, [
297 [ $waypoints{$map}{$name}{'lon'}, $waypoints{$map}{$name}{'lat'} ],
298 [ $waypoints{$map}{$otherpage}{'lon'}, $waypoints{$map}{$otherpage}{'lat'} ]
305 # clear the state, it will be regenerated on the next parse
306 # the idea here is to clear up removed waypoints...
307 $pagestate{$page}{'osm'} = ();
311 if (!defined($config{'osm_format'}) || !$config{'osm_format'}) {
312 $config{'osm_format'} = 'KML';
314 my %formats = map { $_ => 1 } split(/, */, $config{'osm_format'});
315 if ($formats{'GeoJSON'}) {
316 writejson(\%waypoints, \%linestrings);
318 if ($formats{'CSV'}) {
319 writecsvs(\%waypoints, \%linestrings);
321 if ($formats{'KML'}) {
322 writekml(\%waypoints, \%linestrings);
327 my %waypoints = %{$_[0]};
328 my %linestrings = %{$_[1]};
331 foreach my $map (keys %waypoints) {
332 my %geojson = ( "type" => "FeatureCollection", "features" => []);
333 foreach my $name (keys %{$waypoints{$map}}) {
334 my %marker = ( "type" => "Feature",
335 "geometry" => { "type" => "Point", "coordinates" => [ $waypoints{$map}{$name}{'lon'}, $waypoints{$map}{$name}{'lat'} ] },
336 "properties" => $waypoints{$map}{$name} );
337 push @{$geojson{'features'}}, \%marker;
339 foreach my $linestring (@{$linestrings{$map}}) {
340 my %json = ( "type" => "Feature",
341 "geometry" => { "type" => "LineString", "coordinates" => $linestring });
342 push @{$geojson{'features'}}, \%json;
344 writefile("pois.json", $config{destdir} . "/$map", to_json(\%geojson));
349 my %waypoints = %{$_[0]};
350 my %linestrings = %{$_[1]};
351 eval q{use XML::Writer};
353 foreach my $map (keys %waypoints) {
358 <?xml version="1.0" encoding="UTF-8"?>
359 <kml xmlns="http://www.opengis.net/kml/2.2">
361 <name>Simple placemark</name>
362 <description>Attached to the ground. Intelligently places itself
363 at the height of the underlying terrain.</description>
365 <coordinates>-122.0822035425683,37.42228990140251,0</coordinates>
373 <Style id="sh_sunny_copy69">
377 <href>http://waypoints.google.com/mapfiles/kml/shapes/sunny.png</href>
379 <hotSpot x="0.5" y="0.5" xunits="fraction" yunits="fraction"/>
382 <color>ff00aaff</color>
390 my $writer = XML::Writer->new( OUTPUT => \$output,
391 DATA_MODE => 1, ENCODING => 'UTF-8');
393 $writer->startTag("kml", "xmlns" => "http://www.opengis.net/kml/2.2");
395 # first pass: get the icons
396 foreach my $name (keys %{$waypoints{$map}}) {
397 my %options = %{$waypoints{$map}{$name}};
398 $writer->startTag("Style", id => $options{tag});
399 $writer->startTag("IconStyle");
400 $writer->startTag("Icon");
401 $writer->startTag("href");
402 $writer->characters($options{icon});
409 foreach my $name (keys %{$waypoints{$map}}) {
410 my %options = %{$waypoints{$map}{$name}};
411 $writer->startTag("Placemark");
412 $writer->startTag("name");
413 $writer->characters($name);
415 $writer->startTag("styleUrl");
416 $writer->characters('#' . $options{tag});
418 #$writer->emptyTag('atom:link', href => $options{href});
419 # to make it easier for us as the atom:link parameter is
420 # hard to access from javascript
421 $writer->startTag('href');
422 $writer->characters($options{href});
424 $writer->startTag("description");
425 $writer->characters($options{desc});
427 $writer->startTag("Point");
428 $writer->startTag("coordinates");
429 $writer->characters($options{lon} . "," . $options{lat});
436 foreach my $linestring (@{$linestrings{$map}}) {
437 $writer->startTag("Placemark");
438 $writer->startTag("name");
439 $writer->characters("linestring " . $i++);
441 $writer->startTag("LineString");
442 $writer->startTag("coordinates");
444 foreach my $coord (@{$linestring}) {
445 $str .= join(',', @{$coord}) . " \n";
447 $writer->characters($str);
455 writefile("pois.kmp", $config{destdir} . "/$map", $output);
460 my %waypoints = %{$_[0]};
461 foreach my $map (keys %waypoints) {
462 my $poisf = "lat\tlon\ttitle\tdescription\ticon\ticonSize\ticonOffset\n";
463 foreach my $name (keys %{$waypoints{$map}}) {
464 my %options = %{$waypoints{$map}{$name}};
466 $options{'lat'} . "\t" .
467 $options{'lon'} . "\t" .
469 $options{'desc'} . '<br /><a href="' . $options{'page'} . '">' . $name . "</a>\t" .
470 $options{'icon'} . "\n";
473 writefile("pois.txt", $config{destdir} . "/$map", $poisf);
477 # pipe some data through the HTML scrubber
479 # code taken from the meta.pm plugin
481 if (IkiWiki::Plugin::htmlscrubber->can("sanitize")) {
482 return IkiWiki::Plugin::htmlscrubber::sanitize(
483 content => shift, page => shift, destpage => shift);
490 # taken from toggle.pm
494 if ($params{content}=~m!<div[^>]*id="mapdiv-[^"]*"[^>]*>!g) {
495 if (! ($params{content}=~s!</body>!include_javascript($params{page})."</body>"!em)) {
496 # no <body> tag, probably in preview mode
497 $params{content}=$params{content} . include_javascript($params{page});
500 return $params{content};
503 sub prefered_format() {
504 if (!defined($config{'osm_format'}) || !$config{'osm_format'}) {
505 $config{'osm_format'} = 'KML';
507 my @spl = split(/, */, $config{'osm_format'});
511 sub include_javascript ($) {
517 if (exists $pagestate{$page}{'osm'}) {
518 foreach my $map (keys %{$pagestate{$page}{'osm'}}) {
519 foreach my $name (keys %{$pagestate{$page}{'osm'}{$map}{'displays'}}) {
520 my %options = %{$pagestate{$page}{'osm'}{$map}{'displays'}{$name}};
521 $options{'map'} = $map;
522 $options{'format'} = prefered_format();
523 $loader .= "mapsetup(\"mapdiv-$name\", " . to_json(\%options) . ");\n";
528 return embed_map_code($page) . "<script type=\"text/javascript\" charset=\"utf-8\">$loader</script>";
538 return unless defined $cgi->param('do') &&
539 $cgi->param("do") eq "osm";
541 IkiWiki::decode_cgi_utf8($cgi);
543 my $map = $cgi->param('map');
544 if (!defined $map || $map !~ /^[a-z]*$/) {
545 error("invalid map parameter");
548 print "Content-Type: text/html\r\n";
550 print "<html><body>";
551 print "<div id=\"mapdiv-$map\"></div>";
552 print embed_map_code();
553 print "<script type=\"text/javascript\" charset=\"utf-8\">mapsetup( 'mapdiv-$map', { 'map': '$map', 'lat': urlParams['lat'], 'lon': urlParams['lon'], 'zoom': urlParams['zoom'], 'fullscreen': 1, 'editable': 1, 'format': '" . prefered_format() . "'});</script>";
554 print "</body></html>";
559 sub embed_map_code(;$) {
561 return '<script src="http://www.openlayers.org/api/OpenLayers.js" type="text/javascript" charset="utf-8"></script>'.
562 '<script src="'.urlto("ikiwiki/osm.js", $page).
563 '" type="text/javascript" charset="utf-8"></script>'."\n";