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