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