unlock wiki during svn commit to prevent deadlock with post-commit hook
[ikiwiki.git] / 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 lockwiki () { #{{{
424         close WIKILOCK;
425 } #}}}
426
427 sub loadindex () { #{{{
428         open (IN, "$config{srcdir}/.ikiwiki/index") || return;
429         while (<IN>) {
430                 $_=possibly_foolish_untaint($_);
431                 chomp;
432                 my ($mtime, $file, $rendered, @links)=split(' ', $_);
433                 my $page=pagename($file);
434                 $pagesources{$page}=$file;
435                 $oldpagemtime{$page}=$mtime;
436                 $oldlinks{$page}=[@links];
437                 $links{$page}=[@links];
438                 $renderedfiles{$page}=$rendered;
439         }
440         close IN;
441 } #}}}
442
443 sub saveindex () { #{{{
444         if (! -d "$config{srcdir}/.ikiwiki") {
445                 mkdir("$config{srcdir}/.ikiwiki");
446         }
447         open (OUT, ">$config{srcdir}/.ikiwiki/index") || error("cannot write to index: $!");
448         foreach my $page (keys %oldpagemtime) {
449                 print OUT "$oldpagemtime{$page} $pagesources{$page} $renderedfiles{$page} ".
450                         join(" ", @{$links{$page}})."\n"
451                                 if $oldpagemtime{$page};
452         }
453         close OUT;
454 } #}}}
455
456 sub rcs_update () { #{{{
457         if (-d "$config{srcdir}/.svn") {
458                 if (system("svn", "update", "--quiet", $config{srcdir}) != 0) {
459                         warn("svn update failed\n");
460                 }
461         }
462 } #}}}
463
464 sub rcs_commit ($) { #{{{
465         my $message=shift;
466
467         if (-d "$config{srcdir}/.svn") {
468                 if (system("svn", "commit", "--quiet", "-m",
469                            possibly_foolish_untaint($message),
470                            $config{srcdir}) != 0) {
471                         warn("svn commit failed\n");
472                 }
473         }
474 } #}}}
475
476 sub rcs_add ($) { #{{{
477         my $file=shift;
478
479         if (-d "$config{srcdir}/.svn") {
480                 my $parent=dirname($file);
481                 while (! -d "$config{srcdir}/$parent/.svn") {
482                         $file=$parent;
483                         $parent=dirname($file);
484                 }
485                 
486                 if (system("svn", "add", "--quiet", "$config{srcdir}/$file") != 0) {
487                         warn("svn add failed\n");
488                 }
489         }
490 } #}}}
491
492 sub rcs_recentchanges ($) { #{{{
493         my $num=shift;
494         my @ret;
495         
496         eval q{use CGI 'escapeHTML'};
497         eval q{use Date::Parse};
498         eval q{use Time::Duration};
499         
500         if (-d "$config{srcdir}/.svn") {
501                 my $info=`LANG=C svn info $config{srcdir}`;
502                 my ($svn_url)=$info=~/^URL: (.*)$/m;
503
504                 # FIXME: currently assumes that the wiki is somewhere
505                 # under trunk in svn, doesn't support other layouts.
506                 my ($svn_base)=$svn_url=~m!(/trunk(?:/.*)?)$!;
507                 
508                 my $div=qr/^--------------------+$/;
509                 my $infoline=qr/^r(\d+)\s+\|\s+([^\s]+)\s+\|\s+(\d+-\d+-\d+\s+\d+:\d+:\d+\s+[-+]?\d+).*/;
510                 my $state='start';
511                 my ($rev, $user, $when, @pages, @message);
512                 foreach (`LANG=C svn log --limit $num -v '$svn_url'`) {
513                         chomp;
514                         if ($state eq 'start' && /$div/) {
515                                 $state='header';
516                         }
517                         elsif ($state eq 'header' && /$infoline/) {
518                                 $rev=$1;
519                                 $user=$2;
520                                 $when=concise(ago(time - str2time($3)));
521                         }
522                         elsif ($state eq 'header' && /^\s+[A-Z]\s+\Q$svn_base\E\/(.+)$/) {
523                                 push @pages, { link => htmllink("", pagename($1), 1) }
524                                         if length $1;
525                         }
526                         elsif ($state eq 'header' && /^$/) {
527                                 $state='body';
528                         }
529                         elsif ($state eq 'body' && /$div/) {
530                                 my $committype="web";
531                                 if (defined $message[0] &&
532                                     $message[0]->{line}=~/^web commit by (\w+):?(.*)/) {
533                                         $user="$1";
534                                         $message[0]->{line}=$2;
535                                 }
536                                 else {
537                                         $committype="svn";
538                                 }
539                                 
540                                 push @ret, { rev => $rev,
541                                         user => htmllink("", $user, 1),
542                                         committype => $committype,
543                                         when => $when, message => [@message],
544                                         pages => [@pages] } if @pages;
545                                 return @ret if @ret >= $num;
546                                 
547                                 $state='header';
548                                 $rev=$user=$when=undef;
549                                 @pages=@message=();
550                         }
551                         elsif ($state eq 'body') {
552                                 push @message, {line => escapeHTML($_)},
553                         }
554                 }
555         }
556
557         return @ret;
558 } #}}}
559
560 sub prune ($) { #{{{
561         my $file=shift;
562
563         unlink($file);
564         my $dir=dirname($file);
565         while (rmdir($dir)) {
566                 $dir=dirname($dir);
567         }
568 } #}}}
569
570 sub refresh () { #{{{
571         # find existing pages
572         my %exists;
573         my @files;
574         eval q{use File::Find};
575         find({
576                 no_chdir => 1,
577                 wanted => sub {
578                         if (/$config{wiki_file_prune_regexp}/) {
579                                 no warnings 'once';
580                                 $File::Find::prune=1;
581                                 use warnings "all";
582                         }
583                         elsif (! -d $_ && ! -l $_) {
584                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
585                                 if (! defined $f) {
586                                         warn("skipping bad filename $_\n");
587                                 }
588                                 else {
589                                         $f=~s/^\Q$config{srcdir}\E\/?//;
590                                         push @files, $f;
591                                         $exists{pagename($f)}=1;
592                                 }
593                         }
594                 },
595         }, $config{srcdir});
596
597         my %rendered;
598
599         # check for added or removed pages
600         my @add;
601         foreach my $file (@files) {
602                 my $page=pagename($file);
603                 if (! $oldpagemtime{$page}) {
604                         debug("new page $page");
605                         push @add, $file;
606                         $links{$page}=[];
607                         $pagesources{$page}=$file;
608                 }
609         }
610         my @del;
611         foreach my $page (keys %oldpagemtime) {
612                 if (! $exists{$page}) {
613                         debug("removing old page $page");
614                         push @del, $pagesources{$page};
615                         prune($config{destdir}."/".$renderedfiles{$page});
616                         delete $renderedfiles{$page};
617                         $oldpagemtime{$page}=0;
618                         delete $pagesources{$page};
619                 }
620         }
621         
622         # render any updated files
623         foreach my $file (@files) {
624                 my $page=pagename($file);
625                 
626                 if (! exists $oldpagemtime{$page} ||
627                     mtime("$config{srcdir}/$file") > $oldpagemtime{$page}) {
628                         debug("rendering changed file $file");
629                         render($file);
630                         $rendered{$file}=1;
631                 }
632         }
633         
634         # if any files were added or removed, check to see if each page
635         # needs an update due to linking to them
636         # TODO: inefficient; pages may get rendered above and again here;
637         # problem is the bestlink may have changed and we won't know until
638         # now
639         if (@add || @del) {
640 FILE:           foreach my $file (@files) {
641                         my $page=pagename($file);
642                         foreach my $f (@add, @del) {
643                                 my $p=pagename($f);
644                                 foreach my $link (@{$links{$page}}) {
645                                         if (bestlink($page, $link) eq $p) {
646                                                 debug("rendering $file, which links to $p");
647                                                 render($file);
648                                                 $rendered{$file}=1;
649                                                 next FILE;
650                                         }
651                                 }
652                         }
653                 }
654         }
655
656         # handle backlinks; if a page has added/removed links, update the
657         # pages it links to
658         # TODO: inefficient; pages may get rendered above and again here;
659         # problem is the backlinks could be wrong in the first pass render
660         # above
661         if (%rendered) {
662                 my %linkchanged;
663                 foreach my $file (keys %rendered, @del) {
664                         my $page=pagename($file);
665                         if (exists $links{$page}) {
666                                 foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
667                                         if (length $link &&
668                                             ! exists $oldlinks{$page} ||
669                                             ! grep { $_ eq $link } @{$oldlinks{$page}}) {
670                                                 $linkchanged{$link}=1;
671                                         }
672                                 }
673                         }
674                         if (exists $oldlinks{$page}) {
675                                 foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
676                                         if (length $link &&
677                                             ! exists $links{$page} ||
678                                             ! grep { $_ eq $link } @{$links{$page}}) {
679                                                 $linkchanged{$link}=1;
680                                         }
681                                 }
682                         }
683                 }
684                 foreach my $link (keys %linkchanged) {
685                         my $linkfile=$pagesources{$link};
686                         if (defined $linkfile) {
687                                 debug("rendering $linkfile, to update its backlinks");
688                                 render($linkfile);
689                         }
690                 }
691         }
692 } #}}}
693
694 sub gen_wrapper (@) { #{{{
695         my %config=(@_);
696         eval q{use Cwd 'abs_path'};
697         $config{srcdir}=abs_path($config{srcdir});
698         $config{destdir}=abs_path($config{destdir});
699         my $this=abs_path($0);
700         if (! -x $this) {
701                 error("$this doesn't seem to be executable");
702         }
703
704         if ($config{setup}) {
705                 error("cannot create a wrapper that uses a setup file");
706         }
707         
708         my @params=($config{srcdir}, $config{templatedir}, $config{destdir},
709                 "--wikiname=$config{wikiname}");
710         push @params, "--verbose" if $config{verbose};
711         push @params, "--rebuild" if $config{rebuild};
712         push @params, "--nosvn" if !$config{svn};
713         push @params, "--cgi" if $config{cgi};
714         push @params, "--url=$config{url}" if length $config{url};
715         push @params, "--cgiurl=$config{cgiurl}" if length $config{cgiurl};
716         push @params, "--historyurl=$config{historyurl}" if length $config{historyurl};
717         push @params, "--anonok" if $config{anonok};
718         my $params=join(" ", @params);
719         my $call='';
720         foreach my $p ($this, $this, @params) {
721                 $call.=qq{"$p", };
722         }
723         $call.="NULL";
724         
725         my @envsave;
726         push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
727                        CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
728                        HTTP_COOKIE} if $config{cgi};
729         my $envsave="";
730         foreach my $var (@envsave) {
731                 $envsave.=<<"EOF"
732         if ((s=getenv("$var")))
733                 asprintf(&newenviron[i++], "%s=%s", "$var", s);
734 EOF
735         }
736         
737         open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
738         print OUT <<"EOF";
739 /* A wrapper for ikiwiki, can be safely made suid. */
740 #define _GNU_SOURCE
741 #include <stdio.h>
742 #include <unistd.h>
743 #include <stdlib.h>
744 #include <string.h>
745
746 extern char **environ;
747
748 int main (int argc, char **argv) {
749         /* Sanitize environment. */
750         char *s;
751         char *newenviron[$#envsave+3];
752         int i=0;
753 $envsave
754         newenviron[i++]="HOME=$ENV{HOME}";
755         newenviron[i]=NULL;
756         environ=newenviron;
757
758         if (argc == 2 && strcmp(argv[1], "--params") == 0) {
759                 printf("$params\\n");
760                 exit(0);
761         }
762         
763         execl($call);
764         perror("failed to run $this");
765         exit(1);
766 }
767 EOF
768         close OUT;
769         if (system("gcc", "ikiwiki-wrap.c", "-o", possibly_foolish_untaint($config{wrapper})) != 0) {
770                 error("failed to compile ikiwiki-wrap.c");
771         }
772         unlink("ikiwiki-wrap.c");
773         if (defined $config{wrappermode} &&
774             ! chmod(oct($config{wrappermode}), possibly_foolish_untaint($config{wrapper}))) {
775                 error("chmod $config{wrapper}: $!");
776         }
777         print "successfully generated $config{wrapper}\n";
778 } #}}}
779                 
780 sub misctemplate ($$) { #{{{
781         my $title=shift;
782         my $pagebody=shift;
783         
784         my $template=HTML::Template->new(
785                 filename => "$config{templatedir}/misc.tmpl"
786         );
787         $template->param(
788                 title => $title,
789                 indexlink => indexlink(),
790                 wikiname => $config{wikiname},
791                 pagebody => $pagebody,
792         );
793         return $template->output;
794 }#}}}
795
796 sub cgi_recentchanges ($) { #{{{
797         my $q=shift;
798         
799         my $template=HTML::Template->new(
800                 filename => "$config{templatedir}/recentchanges.tmpl"
801         );
802         $template->param(
803                 title => "RecentChanges",
804                 indexlink => indexlink(),
805                 wikiname => $config{wikiname},
806                 changelog => [rcs_recentchanges(100)],
807         );
808         print $q->header, $template->output;
809 } #}}}
810
811 sub userinfo_get ($$) { #{{{
812         my $user=shift;
813         my $field=shift;
814
815         eval q{use Storable};
816         my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
817         if (! defined $userdata || ! ref $userdata || 
818             ! exists $userdata->{$user} || ! ref $userdata->{$user}) {
819                 return "";
820         }
821         return $userdata->{$user}->{$field};
822 } #}}}
823
824 sub userinfo_set ($$) { #{{{
825         my $user=shift;
826         my $info=shift;
827         
828         eval q{use Storable};
829         my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
830         if (! defined $userdata || ! ref $userdata) {
831                 $userdata={};
832         }
833         $userdata->{$user}=$info;
834         my $oldmask=umask(077);
835         my $ret=Storable::lock_store($userdata, "$config{srcdir}/.ikiwiki/userdb");
836         umask($oldmask);
837         return $ret;
838 } #}}}
839
840 sub cgi_signin ($$) { #{{{
841         my $q=shift;
842         my $session=shift;
843
844         eval q{use CGI::FormBuilder};
845         my $form = CGI::FormBuilder->new(
846                 title => "$config{wikiname} signin",
847                 fields => [qw(do page from name password confirm_password email)],
848                 header => 1,
849                 method => 'POST',
850                 validate => {
851                         confirm_password => {
852                                 perl => q{eq $form->field("password")},
853                         },
854                         email => 'EMAIL',
855                 },
856                 required => 'NONE',
857                 javascript => 0,
858                 params => $q,
859                 action => $q->request_uri,
860                 header => 0,
861                 template => (-e "$config{templatedir}/signin.tmpl" ?
862                               "$config{templatedir}/signin.tmpl" : "")
863         );
864         
865         $form->field(name => "name", required => 0);
866         $form->field(name => "do", type => "hidden");
867         $form->field(name => "page", type => "hidden");
868         $form->field(name => "from", type => "hidden");
869         $form->field(name => "password", type => "password", required => 0);
870         $form->field(name => "confirm_password", type => "password", required => 0);
871         $form->field(name => "email", required => 0);
872         if ($q->param("do") ne "signin") {
873                 $form->text("You need to log in before you can edit pages.");
874         }
875         
876         if ($form->submitted) {
877                 # Set required fields based on how form was submitted.
878                 my %required=(
879                         "Login" => [qw(name password)],
880                         "Register" => [qw(name password confirm_password email)],
881                         "Mail Password" => [qw(name)],
882                 );
883                 foreach my $opt (@{$required{$form->submitted}}) {
884                         $form->field(name => $opt, required => 1);
885                 }
886         
887                 # Validate password differently depending on how
888                 # form was submitted.
889                 if ($form->submitted eq 'Login') {
890                         $form->field(
891                                 name => "password",
892                                 validate => sub {
893                                         length $form->field("name") &&
894                                         shift eq userinfo_get($form->field("name"), 'password');
895                                 },
896                         );
897                         $form->field(name => "name", validate => '/^\w+$/');
898                 }
899                 else {
900                         $form->field(name => "password", validate => 'VALUE');
901                 }
902                 # And make sure the entered name exists when logging
903                 # in or sending email, and does not when registering.
904                 if ($form->submitted eq 'Register') {
905                         $form->field(
906                                 name => "name",
907                                 validate => sub {
908                                         my $name=shift;
909                                         length $name &&
910                                         ! userinfo_get($name, "regdate");
911                                 },
912                         );
913                 }
914                 else {
915                         $form->field(
916                                 name => "name",
917                                 validate => sub {
918                                         my $name=shift;
919                                         length $name &&
920                                         userinfo_get($name, "regdate");
921                                 },
922                         );
923                 }
924         }
925         else {
926                 # First time settings.
927                 $form->field(name => "name", comment => "use FirstnameLastName");
928                 $form->field(name => "confirm_password", comment => "(only needed");
929                 $form->field(name => "email",            comment => "for registration)");
930                 if ($session->param("name")) {
931                         $form->field(name => "name", value => $session->param("name"));
932                 }
933         }
934
935         if ($form->submitted && $form->validate) {
936                 if ($form->submitted eq 'Login') {
937                         $session->param("name", $form->field("name"));
938                         if (defined $form->field("do") && 
939                             $form->field("do") ne 'signin') {
940                                 print $q->redirect(
941                                         "$config{cgiurl}?do=".$form->field("do").
942                                         "&page=".$form->field("page").
943                                         "&from=".$form->field("from"));;
944                         }
945                         else {
946                                 print $q->redirect($config{url});
947                         }
948                 }
949                 elsif ($form->submitted eq 'Register') {
950                         my $user_name=$form->field('name');
951                         if (userinfo_set($user_name, {
952                                            'email' => $form->field('email'),
953                                            'password' => $form->field('password'),
954                                            'regdate' => time
955                                          })) {
956                                 $form->field(name => "confirm_password", type => "hidden");
957                                 $form->field(name => "email", type => "hidden");
958                                 $form->text("Registration successful. Now you can Login.");
959                                 print $session->header();
960                                 print misctemplate($form->title, $form->render(submit => ["Login"]));
961                         }
962                         else {
963                                 error("Error saving registration.");
964                         }
965                 }
966                 elsif ($form->submitted eq 'Mail Password') {
967                         my $user_name=$form->field("name");
968                         my $template=HTML::Template->new(
969                                 filename => "$config{templatedir}/passwordmail.tmpl"
970                         );
971                         $template->param(
972                                 user_name => $user_name,
973                                 user_password => userinfo_get($user_name, "password"),
974                                 wikiurl => $config{url},
975                                 wikiname => $config{wikiname},
976                                 REMOTE_ADDR => $ENV{REMOTE_ADDR},
977                         );
978                         
979                         eval q{use Mail::Sendmail};
980                         my ($fromhost) = $config{cgiurl} =~ m!/([^/]+)!;
981                         sendmail(
982                                 To => userinfo_get($user_name, "email"),
983                                 From => "$config{wikiname} admin <".(getpwuid($>))[0]."@".$fromhost.">",
984                                 Subject => "$config{wikiname} information",
985                                 Message => $template->output,
986                         ) or error("Failed to send mail");
987                         
988                         $form->text("Your password has been emailed to you.");
989                         $form->field(name => "name", required => 0);
990                         print $session->header();
991                         print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
992                 }
993         }
994         else {
995                 print $session->header();
996                 print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
997         }
998 } #}}}
999
1000 sub cgi_editpage ($$) { #{{{
1001         my $q=shift;
1002         my $session=shift;
1003
1004         eval q{use CGI::FormBuilder};
1005         my $form = CGI::FormBuilder->new(
1006                 fields => [qw(do from page content comments)],
1007                 header => 1,
1008                 method => 'POST',
1009                 validate => {
1010                         content => '/.+/',
1011                 },
1012                 required => [qw{content}],
1013                 javascript => 0,
1014                 params => $q,
1015                 action => $q->request_uri,
1016                 table => 0,
1017                 template => "$config{templatedir}/editpage.tmpl"
1018         );
1019         
1020         my ($page)=$form->param('page')=~/$config{wiki_file_regexp}/;
1021         if (! defined $page || ! length $page || $page ne $q->param('page') ||
1022             $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
1023                 error("bad page name");
1024         }
1025         $page=lc($page);
1026
1027         $form->field(name => "do", type => 'hidden');
1028         $form->field(name => "from", type => 'hidden');
1029         $form->field(name => "page", value => "$page", force => 1);
1030         $form->field(name => "comments", type => "text", size => 80);
1031         $form->field(name => "content", type => "textarea", rows => 20,
1032                 cols => 80);
1033         
1034         if ($form->submitted eq "Cancel") {
1035                 print $q->redirect("$config{url}/".htmlpage($page));
1036                 return;
1037         }
1038         elsif ($form->submitted eq "Preview") {
1039                 $form->tmpl_param("page_preview",
1040                         htmlize($config{default_pageext},
1041                                 linkify($form->field('content'), $page)));
1042         }
1043         else {
1044                 $form->tmpl_param("page_preview", "");
1045         }
1046         
1047         if (! $form->submitted || $form->submitted eq "Preview" || 
1048             ! $form->validate) {
1049                 if ($form->field("do") eq "create") {
1050                         if (exists $pagesources{lc($page)}) {
1051                                 # hmm, someone else made the page in the
1052                                 # meantime?
1053                                 print $q->redirect("$config{url}/".htmlpage($page));
1054                                 return;
1055                         }
1056                         
1057                         my @page_locs;
1058                         my $best_loc;
1059                         my ($from)=$form->param('from')=~/$config{wiki_file_regexp}/;
1060                         if (! defined $from || ! length $from ||
1061                             $from ne $form->param('from') ||
1062                             $from=~/$config{wiki_file_prune_regexp}/ || $from=~/^\//) {
1063                                 @page_locs=$best_loc=$page;
1064                         }
1065                         else {
1066                                 my $dir=$from."/";
1067                                 $dir=~s![^/]+/$!!;
1068                                 push @page_locs, $dir.$page;
1069                                 push @page_locs, "$from/$page";
1070                                 $best_loc="$from/$page";
1071                                 while (length $dir) {
1072                                         $dir=~s![^/]+/$!!;
1073                                         push @page_locs, $dir.$page;
1074                                 }
1075
1076                                 @page_locs = grep { ! exists
1077                                         $pagesources{lc($_)} } @page_locs;
1078                         }
1079
1080                         $form->tmpl_param("page_select", 1);
1081                         $form->field(name => "page", type => 'select',
1082                                 options => \@page_locs, value => $best_loc);
1083                         $form->title("creating $page");
1084                 }
1085                 elsif ($form->field("do") eq "edit") {
1086                         if (! length $form->field('content')) {
1087                                 my $content="";
1088                                 if (exists $pagesources{lc($page)}) {
1089                                                 $content=readfile("$config{srcdir}/$pagesources{lc($page)}");
1090                                         $content=~s/\n/\r\n/g;
1091                                 }
1092                                 $form->field(name => "content", value => $content,
1093                                         force => 1);
1094                         }
1095                         $form->tmpl_param("page_select", 0);
1096                         $form->field(name => "page", type => 'hidden');
1097                         $form->title("editing $page");
1098                 }
1099                 
1100                 $form->tmpl_param("can_commit", $config{svn});
1101                 $form->tmpl_param("indexlink", indexlink());
1102                 print $form->render(submit => ["Save Page", "Preview", "Cancel"]);
1103         }
1104         else {
1105                 # save page
1106                 my $file=$page.$config{default_pageext};
1107                 my $newfile=1;
1108                 if (exists $pagesources{lc($page)}) {
1109                         $file=$pagesources{lc($page)};
1110                         $newfile=0;
1111                 }
1112                 
1113                 my $content=$form->field('content');
1114                 $content=~s/\r\n/\n/g;
1115                 $content=~s/\r/\n/g;
1116                 writefile("$config{srcdir}/$file", $content);
1117                 
1118                 my $message="web commit ";
1119                 if ($session->param("name")) {
1120                         $message.="by ".$session->param("name");
1121                 }
1122                 else {
1123                         $message.="from $ENV{REMOTE_ADDR}";
1124                 }
1125                 if (defined $form->field('comments') &&
1126                     length $form->field('comments')) {
1127                         $message.=": ".$form->field('comments');
1128                 }
1129                 
1130                 if ($config{svn}) {
1131                         if ($newfile) {
1132                                 rcs_add($file);
1133                         }
1134                         # presumably the commit will trigger an update
1135                         # of the wiki
1136                         rcs_commit($message);
1137                         unlock_wiki();
1138                 }
1139                 else {
1140                         loadindex();
1141                         refresh();
1142                         saveindex();
1143                 }
1144                 
1145                 # The trailing question mark tries to avoid broken
1146                 # caches and get the most recent version of the page.
1147                 print $q->redirect("$config{url}/".htmlpage($page)."?updated");
1148         }
1149 } #}}}
1150
1151 sub cgi () { #{{{
1152         eval q{use CGI};
1153         eval q{use CGI::Session};
1154         
1155         my $q=CGI->new;
1156         
1157         my $do=$q->param('do');
1158         if (! defined $do || ! length $do) {
1159                 error("\"do\" parameter missing");
1160         }
1161         
1162         # This does not need a session.
1163         if ($do eq 'recentchanges') {
1164                 cgi_recentchanges($q);
1165                 return;
1166         }
1167         
1168         CGI::Session->name("ikiwiki_session");
1169
1170         my $oldmask=umask(077);
1171         my $session = CGI::Session->new("driver:db_file", $q,
1172                 { FileName => "$config{srcdir}/.ikiwiki/sessions.db" });
1173         umask($oldmask);
1174         
1175         # Everything below this point needs the user to be signed in.
1176         if ((! $config{anonok} && ! defined $session->param("name") ||
1177                 ! userinfo_get($session->param("name"), "regdate")) || $do eq 'signin') {
1178                 cgi_signin($q, $session);
1179         
1180                 # Force session flush with safe umask.
1181                 my $oldmask=umask(077);
1182                 $session->flush;
1183                 umask($oldmask);
1184                 
1185                 return;
1186         }
1187         
1188         if ($do eq 'create' || $do eq 'edit') {
1189                 cgi_editpage($q, $session);
1190         }
1191         else {
1192                 error("unknown do parameter");
1193         }
1194 } #}}}
1195
1196 sub setup () { # {{{
1197         my $setup=possibly_foolish_untaint($config{setup});
1198         delete $config{setup};
1199         open (IN, $setup) || error("read $setup: $!\n");
1200         local $/=undef;
1201         my $code=<IN>;
1202         ($code)=$code=~/(.*)/s;
1203         close IN;
1204
1205         eval $code;
1206         error($@) if $@;
1207         exit;
1208 } #}}}
1209
1210 # main {{{
1211 lockwiki();
1212 setup() if $config{setup};
1213 if ($config{wrapper}) {
1214         gen_wrapper(%config);
1215         exit;
1216 }
1217 memoize('pagename');
1218 memoize('bestlink');
1219 loadindex() unless $config{rebuild};
1220 if ($config{cgi}) {
1221         cgi();
1222 }
1223 else {
1224         rcs_update() if $config{svn};
1225         refresh();
1226         saveindex();
1227 }
1228 #}}}