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