661f72bab0ef1a5cc6773b92ae0a37feca4bb4c8
[ikiwiki.git] / 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 }
64
65 sub preprocess {
66         my %params=@_;
67         my $page = $params{'page'};
68         my $dest = $params{'destpage'};
69         my $loc = $params{'loc'}; # sanitized below
70         my $lat = $params{'lat'}; # sanitized below
71         my $lon = $params{'lon'}; # sanitized below
72         my $href = $params{'href'};
73
74         my $fullscreen = defined($params{'fullscreen'}); # sanitized here
75         my ($width, $height, $float);
76         if ($fullscreen) {
77                 $height = '100%';
78                 $width = '100%';
79                 $float = 0;
80         }
81         else {
82                 $height = scrub($params{'height'} || "300px", $page, $dest); # sanitized here
83                 $width = scrub($params{'width'} || "500px", $page, $dest); # sanitized here
84                 $float = (defined($params{'right'}) && 'right') || (defined($params{'left'}) && 'left'); # sanitized here
85         }
86         my $zoom = scrub($params{'zoom'} // $config{'osm_default_zoom'} // 15, $page, $dest); # sanitized below
87         my $map;
88         if ($fullscreen) {
89                 $map = $params{'map'} || $page;
90         }
91         else {
92                 $map = $params{'map'} || 'map';
93         }
94         $map = scrub($map, $page, $dest); # sanitized here
95         my $name = scrub($params{'name'} || $map, $page, $dest);
96
97         if (defined($lon) || defined($lat) || defined($loc)) {
98                 ($lon, $lat) = scrub_lonlat($loc, $lon, $lat);
99         }
100
101         if ($zoom !~ /^\d\d?$/ || $zoom < 2 || $zoom > 18) {
102                 error("Bad zoom");
103         }
104         $pagestate{$page}{'osm'}{$map}{'displays'}{$name} = {
105                 height => $height,
106                 width => $width,
107                 float => $float,
108                 zoom => $zoom,
109                 fullscreen => $fullscreen,
110                 editable => defined($params{'editable'}),
111                 lat => $lat,
112                 lon => $lon,
113                 href => $href,
114         };
115         return "<div id=\"mapdiv-$name\"></div>";
116 }
117
118 sub process_waypoint {
119         my %params=@_;
120         my $loc = $params{'loc'}; # sanitized below
121         my $lat = $params{'lat'}; # sanitized below
122         my $lon = $params{'lon'}; # sanitized below
123         my $page = $params{'page'}; # not sanitized?
124         my $dest = $params{'destpage'}; # not sanitized?
125         my $hidden = defined($params{'hidden'}); # sanitized here
126         my ($p) = $page =~ /(?:^|\/)([^\/]+)\/?$/; # shorter page name
127         my $name = scrub($params{'name'} || $p, $page, $dest); # sanitized here
128         my $desc = scrub($params{'desc'} || '', $page, $dest); # sanitized here
129         my $zoom = scrub($params{'zoom'} // $config{'osm_default_zoom'} // 15, $page, $dest); # sanitized below
130         my $icon = $config{'osm_default_icon'} || "ikiwiki/images/osm.png"; # sanitized: we trust $config
131         my $map = scrub($params{'map'} || 'map', $page, $dest); # sanitized here
132         my $alt = $config{'osm_alt'} ? "alt=\"$config{'osm_alt'}\"" : ''; # sanitized: we trust $config
133         if ($zoom !~ /^\d\d?$/ || $zoom < 2 || $zoom > 18) {
134                 error("Bad zoom");
135         }
136
137         ($lon, $lat) = scrub_lonlat($loc, $lon, $lat);
138         if (!defined($lat) || !defined($lon)) {
139                 error("Must specify lat and lon");
140         }
141
142         my $tag = $params{'tag'};
143         foreach my $t (keys %{$typedlinks{$page}{'tag'}}) {
144                 if ($icon = get_tag_icon($t)) {
145                         $tag = $t;
146                         last;
147                 }
148                 $t =~ s!/$config{'tagbase'}/!!;
149                 if ($icon = get_tag_icon($t)) {
150                         $tag = $t;
151                         last;
152                 }
153         }
154         $icon = urlto($icon, $dest, 1);
155         $tag = '' unless $tag;
156         if ($page eq $dest) {
157                 my %formats = get_formats();
158                 if ($formats{'GeoJSON'}) {
159                         will_render($page, "$map/pois.json");
160                 }
161                 if ($formats{'CSV'}) {
162                         will_render($page, "$map/pois.txt");
163                 }
164                 if ($formats{'KML'}) {
165                         will_render($page, "$map/pois.kml");
166                 }
167         }
168         my $href = IkiWiki::cgiurl(
169                 do => "osm",
170                 map => $map,
171                 lat => $lat,
172                 lon => $lon,
173                 zoom => $zoom,
174         );
175         if (defined($destsources{htmlpage($map)})) {
176                 $href = urlto($map,$page) . "?lat=$lat&amp;lon=$lon&amp;zoom=$zoom";
177                 $href =~ s!&!&amp;!g;
178         }
179         $pagestate{$page}{'osm'}{$map}{'waypoints'}{$name} = {
180                 page => $page,
181                 desc => $desc,
182                 icon => $icon,
183                 tag => $tag,
184                 lat => $lat,
185                 lon => $lon,
186                 # how to link back to the page from the map, not to be
187                 # confused with the URL of the map itself sent to the
188                 # embeded map below
189                 href => urlto($page,$map),
190         };
191         my $output = '';
192         if (defined($params{'embed'})) {
193                 $params{'href'} = $href; # propagate down to embeded
194                 $output .= preprocess(%params);
195         }
196         if (!$hidden) {
197                 $output .= "<a href=\"$href\"><img class=\"img\" src=\"$icon\" $alt /></a>";
198         }
199         return $output;
200 }
201
202 # get the icon from the given tag
203 sub get_tag_icon($) {
204         my $tag = shift;
205         # look for an icon attached to the tag
206         my $attached = $tag . '/' . $config{'osm_tag_default_icon'};
207         if (srcfile($attached)) {
208                 return $attached;
209         }
210         else {
211                 return undef;
212         }
213 }
214
215 sub scrub_lonlat($$$) {
216         my ($loc, $lon, $lat) = @_;
217         if ($loc) {
218                 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*$/) {
219                         $lat = $1;
220                         $lon = $2;
221                 }
222                 else {
223                         error("Bad loc");
224                 }
225         }
226         if (defined($lat)) {
227                 if ($lat =~ /^(\-?)(\d+)(?:(\.\d*)°?|(?:°|\s)\s*(\d+)(?:(\.\d*)\'?|(?:\'|\s)\s*(\d+(?:\.\d*)?\"?)|\'?)|°?)\s*([NS])?\s*$/) {
228                         $lat = $2 + ($3//0) + ((($4//0) + (($5//0) + (($6//0)/60.)))/60.);
229                         if (($1 eq '-') || (($7//'') eq 'S')) {
230                                 $lat = - $lat;
231                         }
232                 }
233                 else {
234                         error("Bad lat");
235                 }
236         }
237         if (defined($lon)) {
238                 if ($lon =~ /^(\-?)(\d+)(?:(\.\d*)°?|(?:°|\s)\s*(\d+)(?:(\.\d*)\'?|(?:\'|\s)\s*(\d+(?:\.\d*)?\"?)|\'?)|°?)\s*([EW])?$/) {
239                         $lon = $2 + ($3//0) + ((($4//0) + (($5//0) + (($6//0)/60.)))/60.);
240                         if (($1 eq '-') || (($7//'') eq 'W')) {
241                                 $lon = - $lon;
242                         }
243                 }
244                 else {
245                         error("Bad lon");
246                 }
247         }
248         if ($lat < -90 || $lat > 90 || $lon < -180 || $lon > 180) {
249                 error("Location out of range");
250         }
251         return ($lon, $lat);
252 }
253
254 sub savestate {
255         my %waypoints = ();
256         my %linestrings = ();
257
258         foreach my $page (keys %pagestate) {
259                 if (exists $pagestate{$page}{'osm'}) {
260                         foreach my $map (keys %{$pagestate{$page}{'osm'}}) {
261                                 foreach my $name (keys %{$pagestate{$page}{'osm'}{$map}{'waypoints'}}) {
262                                         debug("found waypoint $name");
263                                         $waypoints{$map}{$name} = $pagestate{$page}{'osm'}{$map}{'waypoints'}{$name};
264                                 }
265                         }
266                 }
267         }
268
269         foreach my $page (keys %pagestate) {
270                 if (exists $pagestate{$page}{'osm'}) {
271                         foreach my $map (keys %{$pagestate{$page}{'osm'}}) {
272                                 # examine the links on this page
273                                 foreach my $name (keys %{$pagestate{$page}{'osm'}{$map}{'waypoints'}}) {
274                                         if (exists $links{$page}) {
275                                                 foreach my $otherpage (@{$links{$page}}) {
276                                                         if (exists $waypoints{$map}{$otherpage}) {
277                                                                 push(@{$linestrings{$map}}, [
278                                                                         [ $waypoints{$map}{$name}{'lon'}, $waypoints{$map}{$name}{'lat'} ],
279                                                                         [ $waypoints{$map}{$otherpage}{'lon'}, $waypoints{$map}{$otherpage}{'lat'} ]
280                                                                 ]);
281                                                         }
282                                                 }
283                                         }
284                                 }
285                         }
286                         # clear the state, it will be regenerated on the next parse
287                         # the idea here is to clear up removed waypoints...
288                         $pagestate{$page}{'osm'} = ();
289                 }
290         }
291
292         my %formats = get_formats();
293         if ($formats{'GeoJSON'}) {
294                 writejson(\%waypoints, \%linestrings);
295         }
296         if ($formats{'CSV'}) {
297                 writecsvs(\%waypoints, \%linestrings);
298         }
299         if ($formats{'KML'}) {
300                 writekml(\%waypoints, \%linestrings);
301         }
302 }
303
304 sub writejson($;$) {
305         my %waypoints = %{$_[0]};
306         my %linestrings = %{$_[1]};
307         eval q{use JSON};
308         error $@ if $@;
309         foreach my $map (keys %waypoints) {
310                 my %geojson = ( "type" => "FeatureCollection", "features" => []);
311                 foreach my $name (keys %{$waypoints{$map}}) {
312                         my %marker = ( "type" => "Feature",
313                                 "geometry" => { "type" => "Point", "coordinates" => [ $waypoints{$map}{$name}{'lon'}, $waypoints{$map}{$name}{'lat'} ] },
314                                 "properties" => $waypoints{$map}{$name} );
315                         push @{$geojson{'features'}}, \%marker;
316                 }
317                 foreach my $linestring (@{$linestrings{$map}}) {
318                         my %json  = ( "type" => "Feature",
319                                 "geometry" => { "type" => "LineString", "coordinates" => $linestring });
320                         push @{$geojson{'features'}}, \%json;
321                 }
322                 writefile("pois.json", $config{destdir} . "/$map", to_json(\%geojson));
323         }
324 }
325
326 sub writekml($;$) {
327         my %waypoints = %{$_[0]};
328         my %linestrings = %{$_[1]};
329         eval q{use XML::Writer};
330         error $@ if $@;
331         foreach my $map (keys %waypoints) {
332
333 =pod
334 Sample placemark:
335
336 <?xml version="1.0" encoding="UTF-8"?>
337 <kml xmlns="http://www.opengis.net/kml/2.2">
338   <Placemark>
339     <name>Simple placemark</name>
340     <description>Attached to the ground. Intelligently places itself 
341        at the height of the underlying terrain.</description>
342     <Point>
343       <coordinates>-122.0822035425683,37.42228990140251,0</coordinates>
344     </Point>
345   </Placemark>
346 </kml>
347
348 Sample style:
349
350
351         <Style id="sh_sunny_copy69">
352                 <IconStyle>
353                         <scale>1.4</scale>
354                         <Icon>
355                                 <href>http://waypoints.google.com/mapfiles/kml/shapes/sunny.png</href>
356                         </Icon>
357                         <hotSpot x="0.5" y="0.5" xunits="fraction" yunits="fraction"/>
358                 </IconStyle>
359                 <LabelStyle>
360                         <color>ff00aaff</color>
361                 </LabelStyle>
362         </Style>
363
364
365 =cut
366
367                 my $output;
368                 my $writer = XML::Writer->new( OUTPUT => \$output,
369                         DATA_MODE => 1, ENCODING => 'UTF-8');
370                 $writer->xmlDecl();
371                 $writer->startTag("kml", "xmlns" => "http://www.opengis.net/kml/2.2");
372
373                 # first pass: get the icons
374                 foreach my $name (keys %{$waypoints{$map}}) {
375                         my %options = %{$waypoints{$map}{$name}};
376                         $writer->startTag("Style", id => $options{tag});
377                         $writer->startTag("IconStyle");
378                         $writer->startTag("Icon");
379                         $writer->startTag("href");
380                         $writer->characters($options{icon});
381                         $writer->endTag();
382                         $writer->endTag();
383                         $writer->endTag();
384                         $writer->endTag();
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->end();
432
433                 writefile("pois.kml", $config{destdir} . "/$map", $output);
434         }
435 }
436
437 sub writecsvs($;$) {
438         my %waypoints = %{$_[0]};
439         foreach my $map (keys %waypoints) {
440                 my $poisf = "lat\tlon\ttitle\tdescription\ticon\ticonSize\ticonOffset\n";
441                 foreach my $name (keys %{$waypoints{$map}}) {
442                         my %options = %{$waypoints{$map}{$name}};
443                         my $line = 
444                                 $options{'lat'} . "\t" .
445                                 $options{'lon'} . "\t" .
446                                 $name . "\t" .
447                                 $options{'desc'} . '<br /><a href="' . $options{'page'} . '">' . $name . "</a>\t" .
448                                 $options{'icon'} . "\n";
449                         $poisf .= $line;
450                 }
451                 writefile("pois.txt", $config{destdir} . "/$map", $poisf);
452         }
453 }
454
455 # pipe some data through the HTML scrubber
456 #
457 # code taken from the meta.pm plugin
458 sub scrub($$$) {
459         if (IkiWiki::Plugin::htmlscrubber->can("sanitize")) {
460                 return IkiWiki::Plugin::htmlscrubber::sanitize(
461                         content => shift, page => shift, destpage => shift);
462         }
463         else {
464                 return shift;
465         }
466 }
467
468 # taken from toggle.pm
469 sub format (@) {
470         my %params=@_;
471
472         if ($params{content}=~m!<div[^>]*id="mapdiv-[^"]*"[^>]*>!g) {
473                 if (! ($params{content}=~s!</body>!include_javascript($params{page})."</body>"!em)) {
474                         # no <body> tag, probably in preview mode
475                         $params{content}=$params{content} . include_javascript($params{page});
476                 }
477         }
478         return $params{content};
479 }
480
481 sub preferred_format() {
482         if (!defined($config{'osm_format'}) || !$config{'osm_format'}) {
483                 $config{'osm_format'} = 'KML';
484         }
485         my @spl = split(/, */, $config{'osm_format'});
486         return shift @spl;
487 }
488
489 sub get_formats() {
490         if (!defined($config{'osm_format'}) || !$config{'osm_format'}) {
491                 $config{'osm_format'} = 'KML';
492         }
493         map { $_ => 1 } split(/, */, $config{'osm_format'});
494 }
495
496 sub include_javascript ($) {
497         my $page=shift;
498         my $loader;
499
500         if (exists $pagestate{$page}{'osm'}) {
501                 foreach my $map (keys %{$pagestate{$page}{'osm'}}) {
502                         foreach my $name (keys %{$pagestate{$page}{'osm'}{$map}{'displays'}}) {
503                                 $loader .= map_setup_code($map, $name, %{$pagestate{$page}{'osm'}{$map}{'displays'}{$name}});
504                         }
505                 }
506         }
507         if ($loader) {
508                 return embed_map_code($page) . "<script type=\"text/javascript\" charset=\"utf-8\">$loader</script>";
509         }
510         else {
511                 return '';
512         }
513 }
514
515 sub cgi($) {
516         my $cgi=shift;
517
518         return unless defined $cgi->param('do') &&
519                 $cgi->param("do") eq "osm";
520         
521         IkiWiki::loadindex();
522
523         IkiWiki::decode_cgi_utf8($cgi);
524
525         my $map = $cgi->param('map');
526         if (!defined $map || $map !~ /^[a-z]*$/) {
527                 error("invalid map parameter");
528         }
529
530         print "Content-Type: text/html\r\n";
531         print ("\r\n");
532         print "<html><body>";
533         print "<div id=\"mapdiv-$map\"></div>";
534         print embed_map_code();
535         print "<script type=\"text/javascript\" charset=\"utf-8\">";
536         print map_setup_code($map, $map,
537                 lat => "urlParams['lat']",
538                 lon => "urlParams['lon']",
539                 zoom => "urlParams['zoom']",
540                 fullscreen => 1,
541                 editable => 1,
542         );
543         print "</script>";
544         print "</body></html>";
545
546         exit 0;
547 }
548
549 sub embed_map_code(;$) {
550         my $page=shift;
551         return '<script src="http://www.openlayers.org/api/OpenLayers.js" type="text/javascript" charset="utf-8"></script>'.
552                 '<script src="'.urlto("ikiwiki/osm.js", $page).
553                 '" type="text/javascript" charset="utf-8"></script>'."\n";
554 }
555
556 sub map_setup_code($;@) {
557         my $map=shift;
558         my $name=shift;
559         my %options=@_;
560
561         eval q{use JSON};
562         error $@ if $@;
563                                 
564         $options{'format'} = preferred_format();
565
566         my %formats = get_formats();
567         if ($formats{'GeoJSON'}) {
568                 $options{'jsonurl'} = urlto($map."/pois.json");
569         }
570         if ($formats{'CSV'}) {
571                 $options{'csvurl'} = urlto($map."/pois.txt");
572         }
573         if ($formats{'KML'}) {
574                 $options{'kmlurl'} = urlto($map."/pois.kml");
575         }
576
577         return "mapsetup('mapdiv-$name', " . to_json(\%options) . ");";
578 }
579
580 1;