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