need to use CGI in rcs_recentchanges to get escapeHTML
[ikiwiki] / ikiwiki
1 #!/usr/bin/perl -T
2 $ENV{PATH}="/usr/local/bin:/usr/bin:/bin";
3
4 use warnings;
5 use strict;
6 use Memoize;
7 use File::Spec;
8 use HTML::Template;
9 use Getopt::Long;
10
11 my (%links, %oldlinks, %oldpagemtime, %renderedfiles, %pagesources);
12
13 # Holds global config settings, also used by some modules.
14 our %config=( #{{{
15         wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.html?$)},
16         wiki_link_regexp => qr/\[\[([^\s]+)\]\]/,
17         wiki_file_regexp => qr/(^[-A-Za-z0-9_.:\/+]+$)/,
18         verbose => 0,
19         wikiname => "wiki",
20         default_pageext => ".mdwn",
21         cgi => 0,
22         svn => 1,
23         url => '',
24         cgiurl => '',
25         historyurl => '',
26         anonok => 0,
27         rebuild => 0,
28         wrapper => undef,
29         wrappermode => undef,
30         srcdir => undef,
31         destdir => undef,
32         templatedir => undef,
33         setup => undef,
34 ); #}}}
35
36 GetOptions( #{{{
37         "setup=s" => \$config{setup},
38         "wikiname=s" => \$config{wikiname},
39         "verbose|v!" => \$config{verbose},
40         "rebuild!" => \$config{rebuild},
41         "wrapper=s" => sub { $config{wrapper}=$_[1] ? $_[1] : "ikiwiki-wrap" },
42         "wrappermode=i" => \$config{wrappermode},
43         "svn!" => \$config{svn},
44         "anonok!" => \$config{anonok},
45         "cgi!" => \$config{cgi},
46         "url=s" => \$config{url},
47         "cgiurl=s" => \$config{cgiurl},
48         "historyurl=s" => \$config{historyurl},
49         "exclude=s@" => sub {
50                 $config{wiki_file_prune_regexp}=qr/$config{wiki_file_prune_regexp}|$_[1]/;
51         },
52 ) || usage();
53
54 if (! $config{setup}) {
55         usage() unless @ARGV == 3;
56         $config{srcdir} = possibly_foolish_untaint(shift);
57         $config{templatedir} = possibly_foolish_untaint(shift);
58         $config{destdir} = possibly_foolish_untaint(shift);
59         if ($config{cgi} && ! length $config{url}) {
60                 error("Must specify url to wiki with --url when using --cgi");
61         }
62 }
63 #}}}
64
65 sub usage { #{{{
66         die "usage: ikiwiki [options] source templates dest\n";
67 } #}}}
68
69 sub error { #{{{
70         if ($config{cgi}) {
71                 print "Content-type: text/html\n\n";
72                 print misctemplate("Error", "<p>Error: @_</p>");
73         }
74         die @_;
75 } #}}}
76
77 sub debug ($) { #{{{
78         return unless $config{verbose};
79         if (! $config{cgi}) {
80                 print "@_\n";
81         }
82         else {
83                 print STDERR "@_\n";
84         }
85 } #}}}
86
87 sub mtime ($) { #{{{
88         my $page=shift;
89         
90         return (stat($page))[9];
91 } #}}}
92
93 sub possibly_foolish_untaint { #{{{
94         my $tainted=shift;
95         my ($untainted)=$tainted=~/(.*)/;
96         return $untainted;
97 } #}}}
98
99 sub basename ($) { #{{{
100         my $file=shift;
101
102         $file=~s!.*/!!;
103         return $file;
104 } #}}}
105
106 sub dirname ($) { #{{{
107         my $file=shift;
108
109         $file=~s!/?[^/]+$!!;
110         return $file;
111 } #}}}
112
113 sub pagetype ($) { #{{{
114         my $page=shift;
115         
116         if ($page =~ /\.mdwn$/) {
117                 return ".mdwn";
118         }
119         else {
120                 return "unknown";
121         }
122 } #}}}
123
124 sub pagename ($) { #{{{
125         my $file=shift;
126
127         my $type=pagetype($file);
128         my $page=$file;
129         $page=~s/\Q$type\E*$// unless $type eq 'unknown';
130         return $page;
131 } #}}}
132
133 sub htmlpage ($) { #{{{
134         my $page=shift;
135
136         return $page.".html";
137 } #}}}
138
139 sub readfile ($) { #{{{
140         my $file=shift;
141
142         local $/=undef;
143         open (IN, "$file") || error("failed to read $file: $!");
144         my $ret=<IN>;
145         close IN;
146         return $ret;
147 } #}}}
148
149 sub writefile ($$) { #{{{
150         my $file=shift;
151         my $content=shift;
152
153         my $dir=dirname($file);
154         if (! -d $dir) {
155                 my $d="";
156                 foreach my $s (split(m!/+!, $dir)) {
157                         $d.="$s/";
158                         if (! -d $d) {
159                                 mkdir($d) || error("failed to create directory $d: $!");
160                         }
161                 }
162         }
163         
164         open (OUT, ">$file") || error("failed to write $file: $!");
165         print OUT $content;
166         close OUT;
167 } #}}}
168
169 sub findlinks ($$) { #{{{
170         my $content=shift;
171         my $page=shift;
172
173         my @links;
174         while ($content =~ /(?<!\\)$config{wiki_link_regexp}/g) {
175                 push @links, lc($1);
176         }
177         # Discussion links are a special case since they're not in the text
178         # of the page, but on its template.
179         return @links, "$page/discussion";
180 } #}}}
181
182 sub bestlink ($$) { #{{{
183         # Given a page and the text of a link on the page, determine which
184         # existing page that link best points to. Prefers pages under a
185         # subdirectory with the same name as the source page, failing that
186         # goes down the directory tree to the base looking for matching
187         # pages.
188         my $page=shift;
189         my $link=lc(shift);
190         
191         my $cwd=$page;
192         do {
193                 my $l=$cwd;
194                 $l.="/" if length $l;
195                 $l.=$link;
196
197                 if (exists $links{$l}) {
198                         #debug("for $page, \"$link\", use $l");
199                         return $l;
200                 }
201         } while $cwd=~s!/?[^/]+$!!;
202
203         #print STDERR "warning: page $page, broken link: $link\n";
204         return "";
205 } #}}}
206
207 sub isinlinableimage ($) { #{{{
208         my $file=shift;
209         
210         $file=~/\.(png|gif|jpg|jpeg)$/;
211 } #}}}
212
213 sub htmllink { #{{{
214         my $page=shift;
215         my $link=shift;
216         my $noimageinline=shift; # don't turn links into inline html images
217         my $forcesubpage=shift; # force a link to a subpage
218
219         my $bestlink;
220         if (! $forcesubpage) {
221                 $bestlink=bestlink($page, $link);
222         }
223         else {
224                 $bestlink="$page/".lc($link);
225         }
226
227         return $link if length $bestlink && $page eq $bestlink;
228         
229         # TODO BUG: %renderedfiles may not have it, if the linked to page
230         # was also added and isn't yet rendered! Note that this bug is
231         # masked by the bug mentioned below that makes all new files
232         # be rendered twice.
233         if (! grep { $_ eq $bestlink } values %renderedfiles) {
234                 $bestlink=htmlpage($bestlink);
235         }
236         if (! grep { $_ eq $bestlink } values %renderedfiles) {
237                 return "<a href=\"$config{cgiurl}?do=create&page=$link&from=$page\">?</a>$link"
238         }
239         
240         $bestlink=File::Spec->abs2rel($bestlink, dirname($page));
241         
242         if (! $noimageinline && isinlinableimage($bestlink)) {
243                 return "<img src=\"$bestlink\">";
244         }
245         return "<a href=\"$bestlink\">$link</a>";
246 } #}}}
247
248 sub linkify ($$) { #{{{
249         my $content=shift;
250         my $page=shift;
251
252         $content =~ s{(\\?)$config{wiki_link_regexp}}{
253                 $1 ? "[[$2]]" : htmllink($page, $2)
254         }eg;
255         
256         return $content;
257 } #}}}
258
259 sub htmlize ($$) { #{{{
260         my $type=shift;
261         my $content=shift;
262         
263         if (! $INC{"/usr/bin/markdown"}) {
264                 no warnings 'once';
265                 $blosxom::version="is a proper perl module too much to ask?";
266                 use warnings 'all';
267                 do "/usr/bin/markdown";
268         }
269         
270         if ($type eq '.mdwn') {
271                 return Markdown::Markdown($content);
272         }
273         else {
274                 error("htmlization of $type not supported");
275         }
276 } #}}}
277
278 sub backlinks ($) { #{{{
279         my $page=shift;
280
281         my @links;
282         foreach my $p (keys %links) {
283                 next if bestlink($page, $p) eq $page;
284                 if (grep { length $_ && bestlink($p, $_) eq $page } @{$links{$p}}) {
285                         my $href=File::Spec->abs2rel(htmlpage($p), dirname($page));
286                         
287                         # Trim common dir prefixes from both pages.
288                         my $p_trimmed=$p;
289                         my $page_trimmed=$page;
290                         my $dir;
291                         1 while (($dir)=$page_trimmed=~m!^([^/]+/)!) &&
292                                 defined $dir &&
293                                 $p_trimmed=~s/^\Q$dir\E// &&
294                                 $page_trimmed=~s/^\Q$dir\E//;
295                                        
296                         push @links, { url => $href, page => $p_trimmed };
297                 }
298         }
299
300         return sort { $a->{page} cmp $b->{page} } @links;
301 } #}}}
302         
303 sub parentlinks ($) { #{{{
304         my $page=shift;
305         
306         my @ret;
307         my $pagelink="";
308         my $path="";
309         my $skip=1;
310         foreach my $dir (reverse split("/", $page)) {
311                 if (! $skip) {
312                         $path.="../";
313                         unshift @ret, { url => "$path$dir.html", page => $dir };
314                 }
315                 else {
316                         $skip=0;
317                 }
318         }
319         unshift @ret, { url => length $path ? $path : ".", page => $config{wikiname} };
320         return @ret;
321 } #}}}
322
323 sub indexlink () { #{{{
324         return "<a href=\"$config{url}\">$config{wikiname}</a>";
325 } #}}}
326
327 sub finalize ($$) { #{{{
328         my $content=shift;
329         my $page=shift;
330
331         my $title=basename($page);
332         $title=~s/_/ /g;
333         
334         my $template=HTML::Template->new(blind_cache => 1,
335                 filename => "$config{templatedir}/page.tmpl");
336         
337         if (length $config{cgiurl}) {
338                 $template->param(editurl => "$config{cgiurl}?do=edit&page=$page");
339                 if ($config{svn}) {
340                         $template->param(recentchangesurl => "$config{cgiurl}?do=recentchanges");
341                 }
342         }
343
344         if (length $config{historyurl}) {
345                 my $u=$config{historyurl};
346                 $u=~s/\[\[\]\]/$pagesources{$page}/g;
347                 $template->param(historyurl => $u);
348         }
349         
350         $template->param(
351                 title => $title,
352                 wikiname => $config{wikiname},
353                 parentlinks => [parentlinks($page)],
354                 content => $content,
355                 backlinks => [backlinks($page)],
356                 discussionlink => htmllink($page, "Discussion", 1, 1),
357         );
358         
359         return $template->output;
360 } #}}}
361
362 sub check_overwrite ($$) { #{{{
363         # Important security check. Make sure to call this before saving
364         # any files to the source directory.
365         my $dest=shift;
366         my $src=shift;
367         
368         if (! exists $renderedfiles{$src} && -e $dest && ! $config{rebuild}) {
369                 error("$dest already exists and was rendered from ".
370                         join(" ",(grep { $renderedfiles{$_} eq $dest } keys
371                                 %renderedfiles)).
372                         ", before, so not rendering from $src");
373         }
374 } #}}}
375
376 sub render ($) { #{{{
377         my $file=shift;
378         
379         my $type=pagetype($file);
380         my $content=readfile("$config{srcdir}/$file");
381         if ($type ne 'unknown') {
382                 my $page=pagename($file);
383                 
384                 $links{$page}=[findlinks($content, $page)];
385                 
386                 $content=linkify($content, $page);
387                 $content=htmlize($type, $content);
388                 $content=finalize($content, $page);
389                 
390                 check_overwrite("$config{destdir}/".htmlpage($page), $page);
391                 writefile("$config{destdir}/".htmlpage($page), $content);
392                 $oldpagemtime{$page}=time;
393                 $renderedfiles{$page}=htmlpage($page);
394         }
395         else {
396                 $links{$file}=[];
397                 check_overwrite("$config{destdir}/$file", $file);
398                 writefile("$config{destdir}/$file", $content);
399                 $oldpagemtime{$file}=time;
400                 $renderedfiles{$file}=$file;
401         }
402 } #}}}
403
404 sub lockwiki () { #{{{
405         # Take an exclusive lock on the wiki to prevent multiple concurrent
406         # run issues. The lock will be dropped on program exit.
407         if (! -d "$config{srcdir}/.ikiwiki") {
408                 mkdir("$config{srcdir}/.ikiwiki");
409         }
410         open(WIKILOCK, ">$config{srcdir}/.ikiwiki/lockfile") || error ("cannot write to lockfile: $!");
411         if (! flock(WIKILOCK, 2 | 4)) {
412                 debug("wiki seems to be locked, waiting for lock");
413                 my $wait=600; # arbitrary, but don't hang forever to 
414                               # prevent process pileup
415                 for (1..600) {
416                         return if flock(WIKILOCK, 2 | 4);
417                         sleep 1;
418                 }
419                 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
420         }
421 } #}}}
422
423 sub loadindex () { #{{{
424         open (IN, "$config{srcdir}/.ikiwiki/index") || return;
425         while (<IN>) {
426                 $_=possibly_foolish_untaint($_);
427                 chomp;
428                 my ($mtime, $file, $rendered, @links)=split(' ', $_);
429                 my $page=pagename($file);
430                 $pagesources{$page}=$file;
431                 $oldpagemtime{$page}=$mtime;
432                 $oldlinks{$page}=[@links];
433                 $links{$page}=[@links];
434                 $renderedfiles{$page}=$rendered;
435         }
436         close IN;
437 } #}}}
438
439 sub saveindex () { #{{{
440         if (! -d "$config{srcdir}/.ikiwiki") {
441                 mkdir("$config{srcdir}/.ikiwiki");
442         }
443         open (OUT, ">$config{srcdir}/.ikiwiki/index") || error("cannot write to index: $!");
444         foreach my $page (keys %oldpagemtime) {
445                 print OUT "$oldpagemtime{$page} $pagesources{$page} $renderedfiles{$page} ".
446                         join(" ", @{$links{$page}})."\n"
447                                 if $oldpagemtime{$page};
448         }
449         close OUT;
450 } #}}}
451
452 sub rcs_update () { #{{{
453         if (-d "$config{srcdir}/.svn") {
454                 if (system("svn", "update", "--quiet", $config{srcdir}) != 0) {
455                         warn("svn update failed\n");
456                 }
457         }
458 } #}}}
459
460 sub rcs_commit ($) { #{{{
461         my $message=shift;
462
463         if (-d "$config{srcdir}/.svn") {
464                 if (system("svn", "commit", "--quiet", "-m",
465                            possibly_foolish_untaint($message),
466                            $config{srcdir}) != 0) {
467                         warn("svn commit failed\n");
468                 }
469         }
470 } #}}}
471
472 sub rcs_add ($) { #{{{
473         my $file=shift;
474
475         if (-d "$config{srcdir}/.svn") {
476                 my $parent=dirname($file);
477                 while (! -d "$config{srcdir}/$parent/.svn") {
478                         $file=$parent;
479                         $parent=dirname($file);
480                 }
481                 
482                 if (system("svn", "add", "--quiet", "$config{srcdir}/$file") != 0) {
483                         warn("svn add failed\n");
484                 }
485         }
486 } #}}}
487
488 sub rcs_recentchanges ($) { #{{{
489         my $num=shift;
490         my @ret;
491         
492         eval q{use CGI 'escapeHTML'};
493         eval q{use Date::Parse};
494         eval q{use Time::Duration};
495         
496         if (-d "$config{srcdir}/.svn") {
497                 my $info=`LANG=C svn info $config{srcdir}`;
498                 my ($svn_url)=$info=~/^URL: (.*)$/m;
499
500                 # FIXME: currently assumes that the wiki is somewhere
501                 # under trunk in svn, doesn't support other layouts.
502                 my ($svn_base)=$svn_url=~m!(/trunk(?:/.*)?)$!;
503                 
504                 my $div=qr/^--------------------+$/;
505                 my $infoline=qr/^r(\d+)\s+\|\s+([^\s]+)\s+\|\s+(\d+-\d+-\d+\s+\d+:\d+:\d+\s+[-+]?\d+).*/;
506                 my $state='start';
507                 my ($rev, $user, $when, @pages, @message);
508                 foreach (`LANG=C svn log --limit $num -v '$svn_url'`) {
509                         chomp;
510                         if ($state eq 'start' && /$div/) {
511                                 $state='header';
512                         }
513                         elsif ($state eq 'header' && /$infoline/) {
514                                 $rev=$1;
515                                 $user=$2;
516                                 $when=concise(ago(time - str2time($3)));
517                         }
518                         elsif ($state eq 'header' && /^\s+[A-Z]\s+\Q$svn_base\E\/(.+)$/) {
519                                 push @pages, { link => htmllink("", pagename($1), 1) }
520                                         if length $1;
521                         }
522                         elsif ($state eq 'header' && /^$/) {
523                                 $state='body';
524                         }
525                         elsif ($state eq 'body' && /$div/) {
526                                 my $committype="web";
527                                 if (defined $message[0] &&
528                                     $message[0]->{line}=~/^web commit by (\w+):?(.*)/) {
529                                         $user="$1";
530                                         $message[0]->{line}=$2;
531                                 }
532                                 else {
533                                         $committype="svn";
534                                 }
535                                 
536                                 push @ret, { rev => $rev,
537                                         user => htmllink("", $user, 1),
538                                         committype => $committype,
539                                         when => $when, message => [@message],
540                                         pages => [@pages] } if @pages;
541                                 return @ret if @ret >= $num;
542                                 
543                                 $state='header';
544                                 $rev=$user=$when=undef;
545                                 @pages=@message=();
546                         }
547                         elsif ($state eq 'body') {
548                                 push @message, {line => escapeHTML($_)},
549                         }
550                 }
551         }
552
553         return @ret;
554 } #}}}
555
556 sub prune ($) { #{{{
557         my $file=shift;
558
559         unlink($file);
560         my $dir=dirname($file);
561         while (rmdir($dir)) {
562                 $dir=dirname($dir);
563         }
564 } #}}}
565
566 sub refresh () { #{{{
567         # Find existing pages.
568         my %exists;
569         my @files;
570         
571         eval q{use File::Find};
572         find({
573                 no_chdir => 1,
574                 wanted => sub {
575                         if (/$config{wiki_file_prune_regexp}/) {
576                                 no warnings 'once';
577                                 $File::Find::prune=1;
578                                 use warnings "all";
579                         }
580                         elsif (! -d $_ && ! -l $_) {
581                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
582                                 if (! defined $f) {
583                                         warn("skipping bad filename $_\n");
584                                 }
585                                 else {
586                                         $f=~s/^\Q$config{srcdir}\E\/?//;
587                                         push @files, $f;
588                                         $exists{pagename($f)}=1;
589                                 }
590                         }
591                 },
592         }, $config{srcdir});
593
594         my %rendered;
595
596         # check for added or removed pages
597         my @add;
598         foreach my $file (@files) {
599                 my $page=pagename($file);
600                 if (! $oldpagemtime{$page}) {
601                         debug("new page $page");
602                         push @add, $file;
603                         $links{$page}=[];
604                         $pagesources{$page}=$file;
605                 }
606         }
607         my @del;
608         foreach my $page (keys %oldpagemtime) {
609                 if (! $exists{$page}) {
610                         debug("removing old page $page");
611                         push @del, $renderedfiles{$page};
612                         prune($config{destdir}."/".$renderedfiles{$page});
613                         delete $renderedfiles{$page};
614                         $oldpagemtime{$page}=0;
615                         delete $pagesources{$page};
616                 }
617         }
618         
619         # render any updated files
620         foreach my $file (@files) {
621                 my $page=pagename($file);
622                 
623                 if (! exists $oldpagemtime{$page} ||
624                     mtime("$config{srcdir}/$file") > $oldpagemtime{$page}) {
625                         debug("rendering changed file $file");
626                         render($file);
627                         $rendered{$file}=1;
628                 }
629         }
630         
631         # if any files were added or removed, check to see if each page
632         # needs an update due to linking to them
633         # TODO: inefficient; pages may get rendered above and again here;
634         # problem is the bestlink may have changed and we won't know until
635         # now
636         if (@add || @del) {
637 FILE:           foreach my $file (@files) {
638                         my $page=pagename($file);
639                         foreach my $f (@add, @del) {
640                                 my $p=pagename($f);
641                                 foreach my $link (@{$links{$page}}) {
642                                         if (bestlink($page, $link) eq $p) {
643                                                 debug("rendering $file, which links to $p");
644                                                 render($file);
645                                                 $rendered{$file}=1;
646                                                 next FILE;
647                                         }
648                                 }
649                         }
650                 }
651         }
652
653         # handle backlinks; if a page has added/removed links, update the
654         # pages it links to
655         # TODO: inefficient; pages may get rendered above and again here;
656         # problem is the backlinks could be wrong in the first pass render
657         # above
658         if (%rendered) {
659                 my %linkchanged;
660                 foreach my $file (keys %rendered, @del) {
661                         my $page=pagename($file);
662                         if (exists $links{$page}) {
663                                 foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
664                                         if (length $link &&
665                                             ! exists $oldlinks{$page} ||
666                                             ! grep { $_ eq $link } @{$oldlinks{$page}}) {
667                                                 $linkchanged{$link}=1;
668                                         }
669                                 }
670                         }
671                         if (exists $oldlinks{$page}) {
672                                 foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
673                                         if (length $link &&
674                                             ! exists $links{$page} ||
675                                             ! grep { $_ eq $link } @{$links{$page}}) {
676                                                 $linkchanged{$link}=1;
677                                         }
678                                 }
679                         }
680                 }
681                 foreach my $link (keys %linkchanged) {
682                         my $linkfile=$pagesources{$link};
683                         if (defined $linkfile) {
684                                 debug("rendering $linkfile, to update its backlinks");
685                                 render($linkfile);
686                         }
687                 }
688         }
689 } #}}}
690
691 sub gen_wrapper (@) { #{{{
692         my %config=(@_);
693         eval q{use Cwd 'abs_path'};
694         $config{srcdir}=abs_path($config{srcdir});
695         $config{destdir}=abs_path($config{destdir});
696         my $this=abs_path($0);
697         if (! -x $this) {
698                 error("$this doesn't seem to be executable");
699         }
700
701         if ($config{setup}) {
702                 error("cannot create a wrapper that uses a setup file");
703         }
704         
705         my @params=($config{srcdir}, $config{templatedir}, $config{destdir},
706                 "--wikiname=$config{wikiname}");
707         push @params, "--verbose" if $config{verbose};
708         push @params, "--rebuild" if $config{rebuild};
709         push @params, "--nosvn" if !$config{svn};
710         push @params, "--cgi" if $config{cgi};
711         push @params, "--url=$config{url}" if length $config{url};
712         push @params, "--cgiurl=$config{cgiurl}" if length $config{cgiurl};
713         push @params, "--historyurl=$config{historyurl}" if length $config{historyurl};
714         push @params, "--anonok" if $config{anonok};
715         my $params=join(" ", @params);
716         my $call='';
717         foreach my $p ($this, $this, @params) {
718                 $call.=qq{"$p", };
719         }
720         $call.="NULL";
721         
722         my @envsave;
723         push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
724                        CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
725                        HTTP_COOKIE} if $config{cgi};
726         my $envsave="";
727         foreach my $var (@envsave) {
728                 $envsave.=<<"EOF"
729         if ((s=getenv("$var")))
730                 asprintf(&newenviron[i++], "%s=%s", "$var", s);
731 EOF
732         }
733         
734         open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
735         print OUT <<"EOF";
736 /* A wrapper for ikiwiki, can be safely made suid. */
737 #define _GNU_SOURCE
738 #include <stdio.h>
739 #include <unistd.h>
740 #include <stdlib.h>
741 #include <string.h>
742
743 extern char **environ;
744
745 int main (int argc, char **argv) {
746         /* Sanitize environment. */
747         char *s;
748         char *newenviron[$#envsave+3];
749         int i=0;
750 $envsave
751         newenviron[i++]="HOME=$ENV{HOME}";
752         newenviron[i]=NULL;
753         environ=newenviron;
754
755         if (argc == 2 && strcmp(argv[1], "--params") == 0) {
756                 printf("$params\\n");
757                 exit(0);
758         }
759         
760         execl($call);
761         perror("failed to run $this");
762         exit(1);
763 }
764 EOF
765         close OUT;
766         if (system("gcc", "ikiwiki-wrap.c", "-o", possibly_foolish_untaint($config{wrapper})) != 0) {
767                 error("failed to compile ikiwiki-wrap.c");
768         }
769         unlink("ikiwiki-wrap.c");
770         if (defined $config{wrappermode} &&
771             ! chmod(oct($config{wrappermode}), possibly_foolish_untaint($config{wrapper}))) {
772                 error("chmod $config{wrapper}: $!");
773         }
774         print "successfully generated $config{wrapper}\n";
775 } #}}}
776                 
777 sub misctemplate ($$) { #{{{
778         my $title=shift;
779         my $pagebody=shift;
780         
781         my $template=HTML::Template->new(
782                 filename => "$config{templatedir}/misc.tmpl"
783         );
784         $template->param(
785                 title => $title,
786                 indexlink => indexlink(),
787                 wikiname => $config{wikiname},
788                 pagebody => $pagebody,
789         );
790         return $template->output;
791 }#}}}
792
793 sub cgi_recentchanges ($) { #{{{
794         my $q=shift;
795         
796         my $template=HTML::Template->new(
797                 filename => "$config{templatedir}/recentchanges.tmpl"
798         );
799         $template->param(
800                 title => "RecentChanges",
801                 indexlink => indexlink(),
802                 wikiname => $config{wikiname},
803                 changelog => [rcs_recentchanges(100)],
804         );
805         print $q->header, $template->output;
806 } #}}}
807
808 sub userinfo_get ($$) { #{{{
809         my $user=shift;
810         my $field=shift;
811
812         eval q{use Storable};
813         my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
814         if (! defined $userdata || ! ref $userdata || 
815             ! exists $userdata->{$user} || ! ref $userdata->{$user}) {
816                 return "";
817         }
818         return $userdata->{$user}->{$field};
819 } #}}}
820
821 sub userinfo_set ($$) { #{{{
822         my $user=shift;
823         my $info=shift;
824         
825         eval q{use Storable};
826         my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
827         if (! defined $userdata || ! ref $userdata) {
828                 $userdata={};
829         }
830         $userdata->{$user}=$info;
831         my $oldmask=umask(077);
832         my $ret=Storable::lock_store($userdata, "$config{srcdir}/.ikiwiki/userdb");
833         umask($oldmask);
834         return $ret;
835 } #}}}
836
837 sub cgi_signin ($$) { #{{{
838         my $q=shift;
839         my $session=shift;
840
841         eval q{use CGI::FormBuilder};
842         my $form = CGI::FormBuilder->new(
843                 title => "$config{wikiname} signin",
844                 fields => [qw(do page from name password confirm_password email)],
845                 header => 1,
846                 method => 'POST',
847                 validate => {
848                         confirm_password => {
849                                 perl => q{eq $form->field("password")},
850                         },
851                         email => 'EMAIL',
852                 },
853                 required => 'NONE',
854                 javascript => 0,
855                 params => $q,
856                 action => $q->request_uri,
857                 header => 0,
858                 template => (-e "$config{templatedir}/signin.tmpl" ?
859                               "$config{templatedir}/signin.tmpl" : "")
860         );
861         
862         $form->field(name => "name", required => 0);
863         $form->field(name => "do", type => "hidden");
864         $form->field(name => "page", type => "hidden");
865         $form->field(name => "from", type => "hidden");
866         $form->field(name => "password", type => "password", required => 0);
867         $form->field(name => "confirm_password", type => "password", required => 0);
868         $form->field(name => "email", required => 0);
869         if ($q->param("do") ne "signin") {
870                 $form->text("You need to log in before you can edit pages.");
871         }
872         
873         if ($form->submitted) {
874                 # Set required fields based on how form was submitted.
875                 my %required=(
876                         "Login" => [qw(name password)],
877                         "Register" => [qw(name password confirm_password email)],
878                         "Mail Password" => [qw(name)],
879                 );
880                 foreach my $opt (@{$required{$form->submitted}}) {
881                         $form->field(name => $opt, required => 1);
882                 }
883         
884                 # Validate password differently depending on how
885                 # form was submitted.
886                 if ($form->submitted eq 'Login') {
887                         $form->field(
888                                 name => "password",
889                                 validate => sub {
890                                         length $form->field("name") &&
891                                         shift eq userinfo_get($form->field("name"), 'password');
892                                 },
893                         );
894                         $form->field(name => "name", validate => '/^\w+$/');
895                 }
896                 else {
897                         $form->field(name => "password", validate => 'VALUE');
898                 }
899                 # And make sure the entered name exists when logging
900                 # in or sending email, and does not when registering.
901                 if ($form->submitted eq 'Register') {
902                         $form->field(
903                                 name => "name",
904                                 validate => sub {
905                                         my $name=shift;
906                                         length $name &&
907                                         ! userinfo_get($name, "regdate");
908                                 },
909                         );
910                 }
911                 else {
912                         $form->field(
913                                 name => "name",
914                                 validate => sub {
915                                         my $name=shift;
916                                         length $name &&
917                                         userinfo_get($name, "regdate");
918                                 },
919                         );
920                 }
921         }
922         else {
923                 # First time settings.
924                 $form->field(name => "name", comment => "use FirstnameLastName");
925                 $form->field(name => "confirm_password", comment => "(only needed");
926                 $form->field(name => "email",            comment => "for registration)");
927                 if ($session->param("name")) {
928                         $form->field(name => "name", value => $session->param("name"));
929                 }
930         }
931
932         if ($form->submitted && $form->validate) {
933                 if ($form->submitted eq 'Login') {
934                         $session->param("name", $form->field("name"));
935                         if (defined $form->field("do") && 
936                             $form->field("do") ne 'signin') {
937                                 print $q->redirect(
938                                         "$config{cgiurl}?do=".$form->field("do").
939                                         "&page=".$form->field("page").
940                                         "&from=".$form->field("from"));;
941                         }
942                         else {
943                                 print $q->redirect($config{url});
944                         }
945                 }
946                 elsif ($form->submitted eq 'Register') {
947                         my $user_name=$form->field('name');
948                         if (userinfo_set($user_name, {
949                                            'email' => $form->field('email'),
950                                            'password' => $form->field('password'),
951                                            'regdate' => time
952                                          })) {
953                                 $form->field(name => "confirm_password", type => "hidden");
954                                 $form->field(name => "email", type => "hidden");
955                                 $form->text("Registration successful. Now you can Login.");
956                                 print $session->header();
957                                 print misctemplate($form->title, $form->render(submit => ["Login"]));
958                         }
959                         else {
960                                 error("Error saving registration.");
961                         }
962                 }
963                 elsif ($form->submitted eq 'Mail Password') {
964                         my $user_name=$form->field("name");
965                         my $template=HTML::Template->new(
966                                 filename => "$config{templatedir}/passwordmail.tmpl"
967                         );
968                         $template->param(
969                                 user_name => $user_name,
970                                 user_password => userinfo_get($user_name, "password"),
971                                 wikiurl => $config{url},
972                                 wikiname => $config{wikiname},
973                                 REMOTE_ADDR => $ENV{REMOTE_ADDR},
974                         );
975                         
976                         eval q{use Mail::Sendmail};
977                         my ($fromhost) = $config{cgiurl} =~ m!/([^/]+)!;
978                         sendmail(
979                                 To => userinfo_get($user_name, "email"),
980                                 From => "$config{wikiname} admin <".(getpwuid($>))[0]."@".$fromhost.">",
981                                 Subject => "$config{wikiname} information",
982                                 Message => $template->output,
983                         ) or error("Failed to send mail");
984                         
985                         $form->text("Your password has been emailed to you.");
986                         $form->field(name => "name", required => 0);
987                         print $session->header();
988                         print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
989                 }
990         }
991         else {
992                 print $session->header();
993                 print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
994         }
995 } #}}}
996
997 sub cgi_editpage ($$) { #{{{
998         my $q=shift;
999         my $session=shift;
1000
1001         eval q{use CGI::FormBuilder};
1002         my $form = CGI::FormBuilder->new(
1003                 fields => [qw(do from page content comments)],
1004                 header => 1,
1005                 method => 'POST',
1006                 validate => {
1007                         content => '/.+/',
1008                 },
1009                 required => [qw{content}],
1010                 javascript => 0,
1011                 params => $q,
1012                 action => $q->request_uri,
1013                 table => 0,
1014                 template => "$config{templatedir}/editpage.tmpl"
1015         );
1016         
1017         my ($page)=$form->param('page')=~/$config{wiki_file_regexp}/;
1018         if (! defined $page || ! length $page || $page ne $q->param('page') ||
1019             $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
1020                 error("bad page name");
1021         }
1022         $page=lc($page);
1023
1024         $form->field(name => "do", type => 'hidden');
1025         $form->field(name => "from", type => 'hidden');
1026         $form->field(name => "page", value => "$page", force => 1);
1027         $form->field(name => "comments", type => "text", size => 80);
1028         $form->field(name => "content", type => "textarea", rows => 20,
1029                 cols => 80);
1030         
1031         if ($form->submitted eq "Cancel") {
1032                 print $q->redirect("$config{url}/".htmlpage($page));
1033                 return;
1034         }
1035         elsif ($form->submitted eq "Preview") {
1036                 $form->tmpl_param("page_preview",
1037                         htmlize($config{default_pageext},
1038                                 linkify($form->field('content'), $page)));
1039         }
1040         else {
1041                 $form->tmpl_param("page_preview", "");
1042         }
1043         
1044         if (! $form->submitted || $form->submitted eq "Preview" || 
1045             ! $form->validate) {
1046                 if ($form->field("do") eq "create") {
1047                         if (exists $pagesources{lc($page)}) {
1048                                 # hmm, someone else made the page in the
1049                                 # meantime?
1050                                 print $q->redirect("$config{url}/".htmlpage($page));
1051                                 return;
1052                         }
1053                         
1054                         my @page_locs;
1055                         my $best_loc;
1056                         my ($from)=$form->param('from')=~/$config{wiki_file_regexp}/;
1057                         if (! defined $from || ! length $from ||
1058                             $from ne $form->param('from') ||
1059                             $from=~/$config{wiki_file_prune_regexp}/ || $from=~/^\//) {
1060                                 @page_locs=$best_loc=$page;
1061                         }
1062                         else {
1063                                 my $dir=$from."/";
1064                                 $dir=~s![^/]+/$!!;
1065                                 push @page_locs, $dir.$page;
1066                                 push @page_locs, "$from/$page";
1067                                 $best_loc="$from/$page";
1068                                 while (length $dir) {
1069                                         $dir=~s![^/]+/$!!;
1070                                         push @page_locs, $dir.$page;
1071                                 }
1072
1073                                 @page_locs = grep { ! exists
1074                                         $pagesources{lc($_)} } @page_locs;
1075                         }
1076
1077                         $form->tmpl_param("page_select", 1);
1078                         $form->field(name => "page", type => 'select',
1079                                 options => \@page_locs, value => $best_loc);
1080                         $form->title("creating $page");
1081                 }
1082                 elsif ($form->field("do") eq "edit") {
1083                         if (! length $form->field('content')) {
1084                                 my $content="";
1085                                 if (exists $pagesources{lc($page)}) {
1086                                                 $content=readfile("$config{srcdir}/$pagesources{lc($page)}");
1087                                         $content=~s/\n/\r\n/g;
1088                                 }
1089                                 $form->field(name => "content", value => $content,
1090                                         force => 1);
1091                         }
1092                         $form->tmpl_param("page_select", 0);
1093                         $form->field(name => "page", type => 'hidden');
1094                         $form->title("editing $page");
1095                 }
1096                 
1097                 $form->tmpl_param("can_commit", $config{svn});
1098                 $form->tmpl_param("indexlink", indexlink());
1099                 print $form->render(submit => ["Save Page", "Preview", "Cancel"]);
1100         }
1101         else {
1102                 # save page
1103                 my $file=$page.$config{default_pageext};
1104                 my $newfile=1;
1105                 if (exists $pagesources{lc($page)}) {
1106                         $file=$pagesources{lc($page)};
1107                         $newfile=0;
1108                 }
1109                 
1110                 my $content=$form->field('content');
1111                 $content=~s/\r\n/\n/g;
1112                 $content=~s/\r/\n/g;
1113                 writefile("$config{srcdir}/$file", $content);
1114                 
1115                 my $message="web commit ";
1116                 if ($session->param("name")) {
1117                         $message.="by ".$session->param("name");
1118                 }
1119                 else {
1120                         $message.="from $ENV{REMOTE_ADDR}";
1121                 }
1122                 if (defined $form->field('comments') &&
1123                     length $form->field('comments')) {
1124                         $message.=": ".$form->field('comments');
1125                 }
1126                 
1127                 if ($config{svn}) {
1128                         if ($newfile) {
1129                                 rcs_add($file);
1130                         }
1131                         # presumably the commit will trigger an update
1132                         # of the wiki
1133                         rcs_commit($message);
1134                 }
1135                 else {
1136                         loadindex();
1137                         refresh();
1138                         saveindex();
1139                 }
1140                 
1141                 # The trailing question mark tries to avoid broken
1142                 # caches and get the most recent version of the page.
1143                 print $q->redirect("$config{url}/".htmlpage($page)."?updated");
1144         }
1145 } #}}}
1146
1147 sub cgi () { #{{{
1148         eval q{use CGI};
1149         eval q{use CGI::Session};
1150         
1151         my $q=CGI->new;
1152         
1153         my $do=$q->param('do');
1154         if (! defined $do || ! length $do) {
1155                 error("\"do\" parameter missing");
1156         }
1157         
1158         # This does not need a session.
1159         if ($do eq 'recentchanges') {
1160                 cgi_recentchanges($q);
1161                 return;
1162         }
1163         
1164         CGI::Session->name("ikiwiki_session");
1165
1166         my $oldmask=umask(077);
1167         my $session = CGI::Session->new("driver:db_file", $q,
1168                 { FileName => "$config{srcdir}/.ikiwiki/sessions.db" });
1169         umask($oldmask);
1170         
1171         # Everything below this point needs the user to be signed in.
1172         if ((! $config{anonok} && ! defined $session->param("name") ||
1173                 ! userinfo_get($session->param("name"), "regdate")) || $do eq 'signin') {
1174                 cgi_signin($q, $session);
1175         
1176                 # Force session flush with safe umask.
1177                 my $oldmask=umask(077);
1178                 $session->flush;
1179                 umask($oldmask);
1180                 
1181                 return;
1182         }
1183         
1184         if ($do eq 'create' || $do eq 'edit') {
1185                 cgi_editpage($q, $session);
1186         }
1187         else {
1188                 error("unknown do parameter");
1189         }
1190 } #}}}
1191
1192 sub setup () { # {{{
1193         my $setup=possibly_foolish_untaint($config{setup});
1194         delete $config{setup};
1195         open (IN, $setup) || error("read $setup: $!\n");
1196         local $/=undef;
1197         my $code=<IN>;
1198         ($code)=$code=~/(.*)/s;
1199         close IN;
1200
1201         eval $code;
1202         error($@) if $@;
1203         exit;
1204 } #}}}
1205
1206 # main {{{
1207 lockwiki();
1208 setup() if $config{setup};
1209 if ($config{wrapper}) {
1210         gen_wrapper(%config);
1211         exit;
1212 }
1213 memoize('pagename');
1214 memoize('bestlink');
1215 loadindex() unless $config{rebuild};
1216 if ($config{cgi}) {
1217         cgi();
1218 }
1219 else {
1220         rcs_update() if $config{svn};
1221         refresh();
1222         saveindex();
1223 }
1224 #}}}