Merge branch 'master' into fancypodcast
[ikiwiki] / IkiWiki / Plugin / osm.pm
1 #!/usr/bin/perl
2 # Copyright 2011 Blars Blarson
3 # Released under GPL version 2
4
5 package IkiWiki::Plugin::osm;
6 use utf8;
7 use strict;
8 use warnings;
9 use IkiWiki 3.0;
10
11 sub import {
12         add_underlay("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);
19 }
20
21 sub getsetup () {
22         return
23                 plugin => {
24                         safe => 1,
25                         rebuild => 1,
26                         section => "special-purpose",
27                 },
28                 osm_default_zoom => {
29                         type => "integer",
30                         example => "15",
31                         description => "the default zoom when you click on the map link",
32                         safe => 1,
33                         rebuild => 1,
34                 },
35                 osm_default_icon => {
36                         type => "string",
37                         example => "ikiwiki/images/osm.png",
38                         description => "the icon shown on links and on the main map",
39                         safe => 0,
40                         rebuild => 1,
41                 },
42                 osm_alt => {
43                         type => "string",
44                         example => "",
45                         description => "the alt tag of links, defaults to empty",
46                         safe => 0,
47                         rebuild => 1,
48                 },
49                 osm_format => {
50                         type => "string",
51                         example => "KML",
52                         description => "the output format for waypoints, can be KML, GeoJSON or CSV (one or many, comma-separated)",
53                         safe => 1,
54                         rebuild => 1,
55                 },
56                 osm_tag_default_icon => {
57                         type => "string",
58                         example => "icon.png",
59                         description => "the icon attached to a tag, displayed on the map for tagged pages",
60                         safe => 0,
61                         rebuild => 1,
62                 },
63                 osm_openlayers_url => {
64                         type => "string",
65                         example => "http://www.openlayers.org/api/OpenLayers.js",
66                         description => "Url for the OpenLayers.js file",
67                         safe => 0,
68                         rebuild => 1,
69                 },
70                 osm_layers => {
71                         type => "string",
72                         example => { 'OSM', 'GoogleSatellite' },
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.",
74                         safe => 0,
75                         rebuild => 1,
76                 },
77                 osm_google_apikey => {
78                         type => "string",
79                         example => "",
80                         description => "Google maps API key, Google layer not used if missing, see https://code.google.com/apis/console/ to get an API key",
81                         safe => 1,
82                         rebuild => 1,
83                 },
84 }
85
86 sub register_rendered_files {
87         my $map = shift;
88         my $page = shift;
89         my $dest = shift;
90
91         if ($page eq $dest) {
92                 my %formats = get_formats();
93                 if ($formats{'GeoJSON'}) {
94                         will_render($page, "$map/pois.json");
95                 }
96                 if ($formats{'CSV'}) {
97                         will_render($page, "$map/pois.txt");
98                 }
99                 if ($formats{'KML'}) {
100                         will_render($page, "$map/pois.kml");
101                 }
102         }
103 }
104
105 sub preprocess {
106         my %params=@_;
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};
113
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
118         
119         my $zoom = scrub($params{'zoom'} // $config{'osm_default_zoom'} // 15, $page, $dest); # sanitized below
120         my $map;
121         $map = $params{'map'} || 'map';
122         
123         $map = scrub($map, $page, $dest); # sanitized here
124         my $name = scrub($params{'name'} || $map, $page, $dest);
125
126         if (defined($lon) || defined($lat) || defined($loc)) {
127                 ($lon, $lat) = scrub_lonlat($loc, $lon, $lat);
128         }
129
130         if ($zoom !~ /^\d\d?$/ || $zoom < 2 || $zoom > 18) {
131                 error("Bad zoom");
132         }
133
134         if (! defined $href || ! length $href) {
135                 $href=IkiWiki::cgiurl(
136                         do => "osm",
137                         map => $map,
138                 );
139         }
140
141         register_rendered_files($map, $page, $dest);
142
143         $pagestate{$page}{'osm'}{$map}{'displays'}{$name} = {
144                 height => $height,
145                 width => $width,
146                 float => $float,
147                 zoom => $zoom,
148                 fullscreen => 0,
149                 editable => defined($params{'editable'}),
150                 lat => $lat,
151                 lon => $lon,
152                 href => $href,
153                 google_apikey => $config{'osm_google_apikey'},
154         };
155         return "<div id=\"mapdiv-$name\"></div>";
156 }
157
158 sub process_waypoint {
159         my %params=@_;
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) {
174                 error("Bad zoom");
175         }
176
177         ($lon, $lat) = scrub_lonlat($loc, $lon, $lat);
178         if (!defined($lat) || !defined($lon)) {
179                 error("Must specify lat and lon");
180         }
181
182         my $tag = $params{'tag'};
183         foreach my $t (keys %{$typedlinks{$page}{'tag'}}) {
184                 if ($icon = get_tag_icon($t)) {
185                         $tag = $t;
186                         last;
187                 }
188                 $t =~ s!/$config{'tagbase'}/!!;
189                 if ($icon = get_tag_icon($t)) {
190                         $tag = $t;
191                         last;
192                 }
193         }
194         $icon = urlto($icon, $dest, 1);
195         $tag = '' unless $tag;
196         register_rendered_files($map, $page, $dest);
197         $pagestate{$page}{'osm'}{$map}{'waypoints'}{$name} = {
198                 page => $page,
199                 desc => $desc,
200                 icon => $icon,
201                 tag => $tag,
202                 lat => $lat,
203                 lon => $lon,
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),
209         };
210
211         my $mapurl = IkiWiki::cgiurl(
212                 do => "osm",
213                 map => $map,
214                 lat => $lat,
215                 lon => $lon,
216                 zoom => $zoom,
217         );
218         my $output = '';
219         if (defined($params{'embed'})) {
220                 $output .= preprocess(%params,
221                         href => $mapurl,
222                 );
223         }
224         if (!$hidden) {
225                 $output .= "<a href=\"$mapurl\"><img class=\"img\" src=\"$icon\" $alt /></a>";
226         }
227         return $output;
228 }
229
230 # get the icon from the given tag
231 sub get_tag_icon($) {
232         my $tag = shift;
233         # look for an icon attached to the tag
234         my $attached = $tag . '/' . $config{'osm_tag_default_icon'};
235         if (srcfile($attached)) {
236                 return $attached;
237         }
238         else {
239                 return undef;
240         }
241 }
242
243 sub scrub_lonlat($$$) {
244         my ($loc, $lon, $lat) = @_;
245         if ($loc) {
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*$/) {
247                         $lat = $1;
248                         $lon = $2;
249                 }
250                 else {
251                         error("Bad loc");
252                 }
253         }
254         if (defined($lat)) {
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')) {
258                                 $lat = - $lat;
259                         }
260                 }
261                 else {
262                         error("Bad lat");
263                 }
264         }
265         if (defined($lon)) {
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')) {
269                                 $lon = - $lon;
270                         }
271                 }
272                 else {
273                         error("Bad lon");
274                 }
275         }
276         if ($lat < -90 || $lat > 90 || $lon < -180 || $lon > 180) {
277                 error("Location out of range");
278         }
279         return ($lon, $lat);
280 }
281
282 sub savestate {
283         my %waypoints = ();
284         my %linestrings = ();
285
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};
292                                 }
293                         }
294                 }
295         }
296
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'} ]
308                                                                 ]);
309                                                         }
310                                                 }
311                                         }
312                                 }
313                         }
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'} = ();
317                 }
318         }
319
320         my %formats = get_formats();
321         if ($formats{'GeoJSON'}) {
322                 writejson(\%waypoints, \%linestrings);
323         }
324         if ($formats{'CSV'}) {
325                 writecsvs(\%waypoints, \%linestrings);
326         }
327         if ($formats{'KML'}) {
328                 writekml(\%waypoints, \%linestrings);
329         }
330 }
331
332 sub writejson($;$) {
333         my %waypoints = %{$_[0]};
334         my %linestrings = %{$_[1]};
335         eval q{use JSON};
336         error $@ if $@;
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;
344                 }
345                 foreach my $linestring (@{$linestrings{$map}}) {
346                         my %json  = ( "type" => "Feature",
347                                 "geometry" => { "type" => "LineString", "coordinates" => $linestring });
348                         push @{$geojson{'features'}}, \%json;
349                 }
350                 writefile("pois.json", $config{destdir} . "/$map", to_json(\%geojson));
351         }
352 }
353
354 sub writekml($;$) {
355         my %waypoints = %{$_[0]};
356         my %linestrings = %{$_[1]};
357         eval q{use XML::Writer};
358         error $@ if $@;
359         foreach my $map (keys %waypoints) {
360                 my $output;
361                 my $writer = XML::Writer->new( OUTPUT => \$output,
362                         DATA_MODE => 1, DATA_INDENT => ' ', ENCODING => 'UTF-8');
363                 $writer->xmlDecl();
364                 $writer->startTag("kml", "xmlns" => "http://www.opengis.net/kml/2.2");
365                 $writer->startTag("Document");
366
367                 # first pass: get the icons
368                 my %tags_map = (); # keep track of tags seen
369                 foreach my $name (keys %{$waypoints{$map}}) {
370                         my %options = %{$waypoints{$map}{$name}};
371                         if (!$tags_map{$options{tag}}) {
372                             debug("found new style " . $options{tag});
373                             $tags_map{$options{tag}} = ();
374                             $writer->startTag("Style", id => $options{tag});
375                             $writer->startTag("IconStyle");
376                             $writer->startTag("Icon");
377                             $writer->startTag("href");
378                             $writer->characters($options{icon});
379                             $writer->endTag();
380                             $writer->endTag();
381                             $writer->endTag();
382                             $writer->endTag();
383                         }
384                         $tags_map{$options{tag}}{$name} = \%options;
385                 }
386         
387                 foreach my $name (keys %{$waypoints{$map}}) {
388                         my %options = %{$waypoints{$map}{$name}};
389                         $writer->startTag("Placemark");
390                         $writer->startTag("name");
391                         $writer->characters($name);
392                         $writer->endTag();
393                         $writer->startTag("styleUrl");
394                         $writer->characters('#' . $options{tag});
395                         $writer->endTag();
396                         #$writer->emptyTag('atom:link', href => $options{href});
397                         # to make it easier for us as the atom:link parameter is
398                         # hard to access from javascript
399                         $writer->startTag('href');
400                         $writer->characters($options{href});
401                         $writer->endTag();
402                         $writer->startTag("description");
403                         $writer->characters($options{desc});
404                         $writer->endTag();
405                         $writer->startTag("Point");
406                         $writer->startTag("coordinates");
407                         $writer->characters($options{lon} . "," . $options{lat});
408                         $writer->endTag();
409                         $writer->endTag();
410                         $writer->endTag();
411                 }
412                 
413                 my $i = 0;
414                 foreach my $linestring (@{$linestrings{$map}}) {
415                         $writer->startTag("Placemark");
416                         $writer->startTag("name");
417                         $writer->characters("linestring " . $i++);
418                         $writer->endTag();
419                         $writer->startTag("LineString");
420                         $writer->startTag("coordinates");
421                         my $str = '';
422                         foreach my $coord (@{$linestring}) {
423                                 $str .= join(',', @{$coord}) . " \n";
424                         }
425                         $writer->characters($str);
426                         $writer->endTag();
427                         $writer->endTag();
428                         $writer->endTag();
429                 }
430                 $writer->endTag();
431                 $writer->endTag();
432                 $writer->end();
433
434                 writefile("pois.kml", $config{destdir} . "/$map", $output);
435         }
436 }
437
438 sub writecsvs($;$) {
439         my %waypoints = %{$_[0]};
440         foreach my $map (keys %waypoints) {
441                 my $poisf = "lat\tlon\ttitle\tdescription\ticon\ticonSize\ticonOffset\n";
442                 foreach my $name (keys %{$waypoints{$map}}) {
443                         my %options = %{$waypoints{$map}{$name}};
444                         my $line = 
445                                 $options{'lat'} . "\t" .
446                                 $options{'lon'} . "\t" .
447                                 $name . "\t" .
448                                 $options{'desc'} . '<br /><a href="' . $options{'page'} . '">' . $name . "</a>\t" .
449                                 $options{'icon'} . "\n";
450                         $poisf .= $line;
451                 }
452                 writefile("pois.txt", $config{destdir} . "/$map", $poisf);
453         }
454 }
455
456 # pipe some data through the HTML scrubber
457 #
458 # code taken from the meta.pm plugin
459 sub scrub($$$) {
460         if (IkiWiki::Plugin::htmlscrubber->can("sanitize")) {
461                 return IkiWiki::Plugin::htmlscrubber::sanitize(
462                         content => shift, page => shift, destpage => shift);
463         }
464         else {
465                 return shift;
466         }
467 }
468
469 # taken from toggle.pm
470 sub format (@) {
471         my %params=@_;
472
473         if ($params{content}=~m!<div[^>]*id="mapdiv-[^"]*"[^>]*>!g) {
474                 if (! ($params{content}=~s!</body>!include_javascript($params{page})."</body>"!em)) {
475                         # no <body> tag, probably in preview mode
476                         $params{content}=$params{content} . include_javascript($params{page});
477                 }
478         }
479         return $params{content};
480 }
481
482 sub preferred_format() {
483         if (!defined($config{'osm_format'}) || !$config{'osm_format'}) {
484                 $config{'osm_format'} = 'KML';
485         }
486         my @spl = split(/, */, $config{'osm_format'});
487         return shift @spl;
488 }
489
490 sub get_formats() {
491         if (!defined($config{'osm_format'}) || !$config{'osm_format'}) {
492                 $config{'osm_format'} = 'KML';
493         }
494         map { $_ => 1 } split(/, */, $config{'osm_format'});
495 }
496
497 sub include_javascript ($) {
498         my $page=shift;
499         my $loader;
500
501         if (exists $pagestate{$page}{'osm'}) {
502                 foreach my $map (keys %{$pagestate{$page}{'osm'}}) {
503                         foreach my $name (keys %{$pagestate{$page}{'osm'}{$map}{'displays'}}) {
504                                 $loader .= map_setup_code($map, $name, %{$pagestate{$page}{'osm'}{$map}{'displays'}{$name}});
505                         }
506                 }
507         }
508         if ($loader) {
509                 return embed_map_code($page) . "<script type=\"text/javascript\" charset=\"utf-8\">$loader</script>";
510         }
511         else {
512                 return '';
513         }
514 }
515
516 sub cgi($) {
517         my $cgi=shift;
518
519         return unless defined $cgi->param('do') &&
520                 $cgi->param("do") eq "osm";
521         
522         IkiWiki::loadindex();
523
524         IkiWiki::decode_cgi_utf8($cgi);
525
526         my $map = $cgi->param('map');
527         if (!defined $map || $map !~ /^[a-z]*$/) {
528                 error("invalid map parameter");
529         }
530
531         print "Content-Type: text/html\r\n";
532         print ("\r\n");
533         print "<html><body>";
534         print "<div id=\"mapdiv-$map\"></div>";
535         print embed_map_code();
536         print "<script type=\"text/javascript\" charset=\"utf-8\">";
537         print map_setup_code($map, $map,
538                 lat => "urlParams['lat']",
539                 lon => "urlParams['lon']",
540                 zoom => "urlParams['zoom']",
541                 fullscreen => 1,
542                 editable => 1,
543                 google_apikey => $config{'osm_google_apikey'},
544         );
545         print "</script>";
546         print "</body></html>";
547
548         exit 0;
549 }
550
551 sub embed_map_code(;$) {
552         my $page=shift;
553         my $olurl = $config{osm_openlayers_url} || "http://www.openlayers.org/api/OpenLayers.js";
554         my $code = '<script src="'.$olurl.'" type="text/javascript" charset="utf-8"></script>'."\n".
555                 '<script src="'.urlto("ikiwiki/osm.js", $page).
556                 '" type="text/javascript" charset="utf-8"></script>'."\n";
557         if ($config{'osm_google_apikey'}) {
558             $code .= '<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key='.$config{'osm_google_apikey'}.'&sensor=false" type="text/javascript" charset="utf-8"></script>';
559         }
560         return $code;
561 }
562
563 sub map_setup_code($;@) {
564         my $map=shift;
565         my $name=shift;
566         my %options=@_;
567
568         my $mapurl = $config{osm_map_url};
569
570         eval q{use JSON};
571         error $@ if $@;
572                                 
573         $options{'format'} = preferred_format();
574
575         my %formats = get_formats();
576         if ($formats{'GeoJSON'}) {
577                 $options{'jsonurl'} = urlto($map."/pois.json");
578         }
579         if ($formats{'CSV'}) {
580                 $options{'csvurl'} = urlto($map."/pois.txt");
581         }
582         if ($formats{'KML'}) {
583                 $options{'kmlurl'} = urlto($map."/pois.kml");
584         }
585
586         if ($mapurl) {
587                 $options{'mapurl'} = $mapurl;
588         }
589         $options{'layers'} = $config{osm_layers};
590
591         return "mapsetup('mapdiv-$name', " . to_json(\%options) . ");";
592 }
593
594 1;