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