]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - ikiwiki
Fix a bad use of implicit return for admin-less wikis. I got lucky..
[git.ikiwiki.info.git] / ikiwiki
1 #!/usr/bin/perl -T
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";
7 use warnings;
8 use strict;
9 use Memoize;
10 use File::Spec;
11 use HTML::Template;
12 use Getopt::Long;
14 my (%links, %oldlinks, %oldpagemtime, %renderedfiles, %pagesources);
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 ); #}}}
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();
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 #}}}
72 sub usage { #{{{
73         die "usage: ikiwiki [options] source templates dest\n";
74 } #}}}
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 } #}}}
84 sub debug ($) { #{{{
85         return unless $config{verbose};
86         if (! $config{cgi}) {
87                 print "@_\n";
88         }
89         else {
90                 print STDERR "@_\n";
91         }
92 } #}}}
94 sub mtime ($) { #{{{
95         my $page=shift;
96         
97         return (stat($page))[9];
98 } #}}}
100 sub possibly_foolish_untaint { #{{{
101         my $tainted=shift;
102         my ($untainted)=$tainted=~/(.*)/;
103         return $untainted;
104 } #}}}
106 sub basename ($) { #{{{
107         my $file=shift;
109         $file=~s!.*/!!;
110         return $file;
111 } #}}}
113 sub dirname ($) { #{{{
114         my $file=shift;
116         $file=~s!/?[^/]+$!!;
117         return $file;
118 } #}}}
120 sub pagetype ($) { #{{{
121         my $page=shift;
122         
123         if ($page =~ /\.mdwn$/) {
124                 return ".mdwn";
125         }
126         else {
127                 return "unknown";
128         }
129 } #}}}
131 sub pagename ($) { #{{{
132         my $file=shift;
134         my $type=pagetype($file);
135         my $page=$file;
136         $page=~s/\Q$type\E*$// unless $type eq 'unknown';
137         return $page;
138 } #}}}
140 sub htmlpage ($) { #{{{
141         my $page=shift;
143         return $page.".html";
144 } #}}}
146 sub readfile ($) { #{{{
147         my $file=shift;
149         local $/=undef;
150         open (IN, "$file") || error("failed to read $file: $!");
151         my $ret=<IN>;
152         close IN;
153         return $ret;
154 } #}}}
156 sub writefile ($$) { #{{{
157         my $file=shift;
158         my $content=shift;
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 } #}}}
176 sub findlinks ($$) { #{{{
177         my $content=shift;
178         my $page=shift;
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 } #}}}
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;
204                 if (exists $links{$l}) {
205                         #debug("for $page, \"$link\", use $l");
206                         return $l;
207                 }
208         } while $cwd=~s!/?[^/]+$!!;
210         #print STDERR "warning: page $page, broken link: $link\n";
211         return "";
212 } #}}}
214 sub isinlinableimage ($) { #{{{
215         my $file=shift;
216         
217         $file=~/\.(png|gif|jpg|jpeg)$/;
218 } #}}}
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
226         my $bestlink;
227         if (! $forcesubpage) {
228                 $bestlink=bestlink($page, $link);
229         }
230         else {
231                 $bestlink="$page/".lc($link);
232         }
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 } #}}}
255 sub linkify ($$) { #{{{
256         my $content=shift;
257         my $page=shift;
259         $content =~ s{(\\?)$config{wiki_link_regexp}}{
260                 $1 ? "[[$2]]" : htmllink($page, $2)
261         }eg;
262         
263         return $content;
264 } #}}}
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 } #}}}
285 sub backlinks ($) { #{{{
286         my $page=shift;
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         }
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 } #}}}
330 sub indexlink () { #{{{
331         return "<a href=\"$config{url}\">$config{wikiname}</a>";
332 } #}}}
334 sub finalize ($$$) { #{{{
335         my $content=shift;
336         my $page=shift;
337         my $mtime=shift;
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         }
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 } #}}}
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 } #}}}
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 } #}}}
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 } #}}}
434 sub unlockwiki () { #{{{
435         close WIKILOCK;
436 } #}}}
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 } #}}}
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 } #}}}
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 } #}}}
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 } #}}}
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;
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                 }
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 } #}}}
526 sub rcs_add ($) { #{{{
527         # filename is relative to the root of the srcdir
528         my $file=shift;
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 } #}}}
543 sub svn_info ($$) { #{{{
544         my $field=shift;
545         my $file=shift;
547         my $info=`LANG=C svn info $file`;
548         my ($ret)=$info=~/^$field: (.*)$/m;
549         return $ret;
550 } #}}}
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});
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         }
624         return @ret;
625 } #}}}
627 sub prune ($) { #{{{
628         my $file=shift;
630         unlink($file);
631         my $dir=dirname($file);
632         while (rmdir($dir)) {
633                 $dir=dirname($dir);
634         }
635 } #}}}
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});
664         my %rendered;
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         }
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 } #}}}
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         }
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>
815 extern char **environ;
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;
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);
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 }#}}}
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 } #}}}
880 sub userinfo_get ($$) { #{{{
881         my $user=shift;
882         my $field=shift;
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 } #}}}
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 } #}}}
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 } #}}}
929 sub cgi_signin ($$) { #{{{
930         my $q=shift;
931         my $session=shift;
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         }
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 } #}}}
1089 sub is_admin ($) { #{{{
1090         my $user_name=shift;
1092         return grep { $_ eq $user_name } @{$config{adminuser}};
1093 } #}}}
1095 sub glob_match ($$) { #{{{
1096         my $page=shift;
1097         my $glob=shift;
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 } #}}}
1108 sub globlist_match ($$) { #{{{
1109         my $page=shift;
1110         my @globlist=split(" ", shift);
1112         # check any negated globs first
1113         foreach my $glob (@globlist) {
1114                 return 0 if $glob=~/^!(.*)/ && glob_match($page, $1);
1115         }
1117         foreach my $glob (@globlist) {
1118                 return 1 if glob_match($page, $glob);
1119         }
1120         
1121         return 0;
1122 } #}}}
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);
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         }
1141         return 0;
1142 } #}}}
1144 sub cgi_prefs ($$) { #{{{
1145         my $q=shift;
1146         my $session=shift;
1148         eval q{use CGI::FormBuilder};
1149         my $form = CGI::FormBuilder->new(
1150                 title => "preferences",
1151                 fields => [qw(do name password confirm_password email locked_pages)],
1152                 header => 0,
1153                 method => 'POST',
1154                 validate => {
1155                         confirm_password => {
1156                                 perl => q{eq $form->field("password")},
1157                         },
1158                         email => 'EMAIL',
1159                 },
1160                 required => 'NONE',
1161                 javascript => 0,
1162                 params => $q,
1163                 action => $q->request_uri,
1164                 template => (-e "$config{templatedir}/prefs.tmpl" ?
1165                               "$config{templatedir}/prefs.tmpl" : "")
1166         );
1167         my @buttons=("Save Preferences", "Logout", "Cancel");
1168         
1169         my $user_name=$session->param("name");
1170         $form->field(name => "do", type => "hidden");
1171         $form->field(name => "name", disabled => 1,
1172                 value => $user_name, force => 1);
1173         $form->field(name => "password", type => "password");
1174         $form->field(name => "confirm_password", type => "password");
1175         $form->field(name => "locked_pages", size => 50,
1176                 comment => "(".htmllink("", "GlobList", 1).")");
1177         
1178         if (! is_admin($user_name)) {
1179                 $form->field(name => "locked_pages", type => "hidden");
1180         }
1181         
1182         if (! $form->submitted) {
1183                 $form->field(name => "email", force => 1,
1184                         value => userinfo_get($user_name, "email"));
1185                 $form->field(name => "locked_pages", force => 1,
1186                         value => userinfo_get($user_name, "locked_pages"));
1187         }
1188         
1189         if ($form->submitted eq 'Logout') {
1190                 $session->delete();
1191                 print $q->redirect($config{url});
1192                 return;
1193         }
1194         elsif ($form->submitted eq 'Cancel') {
1195                 print $q->redirect($config{url});
1196                 return;
1197         }
1198         elsif ($form->submitted eq "Save Preferences" && $form->validate) {
1199                 foreach my $field (qw(password email locked_pages)) {
1200                         if (length $form->field($field)) {
1201                                 userinfo_set($user_name, $field, $form->field($field)) || error("failed to set $field");
1202                         }
1203                 }
1204                 $form->text("Preferences saved.");
1205         }
1206         
1207         print $session->header();
1208         print misctemplate($form->title, $form->render(submit => \@buttons));
1209 } #}}}
1211 sub cgi_editpage ($$) { #{{{
1212         my $q=shift;
1213         my $session=shift;
1215         eval q{use CGI::FormBuilder};
1216         my $form = CGI::FormBuilder->new(
1217                 fields => [qw(do rcsinfo from page content comments)],
1218                 header => 1,
1219                 method => 'POST',
1220                 validate => {
1221                         content => '/.+/',
1222                 },
1223                 required => [qw{content}],
1224                 javascript => 0,
1225                 params => $q,
1226                 action => $q->request_uri,
1227                 table => 0,
1228                 template => "$config{templatedir}/editpage.tmpl"
1229         );
1230         my @buttons=("Save Page", "Preview", "Cancel");
1231         
1232         my ($page)=$form->param('page')=~/$config{wiki_file_regexp}/;
1233         if (! defined $page || ! length $page || $page ne $q->param('page') ||
1234             $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
1235                 error("bad page name");
1236         }
1237         $page=lc($page);
1238         
1239         my $file=$page.$config{default_pageext};
1240         my $newfile=1;
1241         if (exists $pagesources{lc($page)}) {
1242                 $file=$pagesources{lc($page)};
1243                 $newfile=0;
1244         }
1246         $form->field(name => "do", type => 'hidden');
1247         $form->field(name => "from", type => 'hidden');
1248         $form->field(name => "rcsinfo", type => 'hidden');
1249         $form->field(name => "page", value => "$page", force => 1);
1250         $form->field(name => "comments", type => "text", size => 80);
1251         $form->field(name => "content", type => "textarea", rows => 20,
1252                 cols => 80);
1253         $form->tmpl_param("can_commit", $config{svn});
1254         $form->tmpl_param("indexlink", indexlink());
1255         $form->tmpl_param("helponformattinglink",
1256                 htmllink("", "HelpOnFormatting", 1));
1257         if (! $form->submitted) {
1258                 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
1259                         force => 1);
1260         }
1261         
1262         if ($form->submitted eq "Cancel") {
1263                 print $q->redirect("$config{url}/".htmlpage($page));
1264                 return;
1265         }
1266         elsif ($form->submitted eq "Preview") {
1267                 $form->tmpl_param("page_preview",
1268                         htmlize($config{default_pageext},
1269                                 linkify($form->field('content'), $page)));
1270         }
1271         else {
1272                 $form->tmpl_param("page_preview", "");
1273         }
1274         $form->tmpl_param("page_conflict", "");
1275         
1276         if (! $form->submitted || $form->submitted eq "Preview" || 
1277             ! $form->validate) {
1278                 if ($form->field("do") eq "create") {
1279                         if (exists $pagesources{lc($page)}) {
1280                                 # hmm, someone else made the page in the
1281                                 # meantime?
1282                                 print $q->redirect("$config{url}/".htmlpage($page));
1283                                 return;
1284                         }
1285                         
1286                         my @page_locs;
1287                         my $best_loc;
1288                         my ($from)=$form->param('from')=~/$config{wiki_file_regexp}/;
1289                         if (! defined $from || ! length $from ||
1290                             $from ne $form->param('from') ||
1291                             $from=~/$config{wiki_file_prune_regexp}/ || $from=~/^\//) {
1292                                 @page_locs=$best_loc=$page;
1293                         }
1294                         else {
1295                                 my $dir=$from."/";
1296                                 $dir=~s![^/]+/$!!;
1297                                 
1298                                 if ($page eq 'discussion') {
1299                                         $best_loc="$from/$page";
1300                                 }
1301                                 else {
1302                                         $best_loc=$dir.$page;
1303                                 }
1304                                 
1305                                 push @page_locs, $dir.$page;
1306                                 push @page_locs, "$from/$page";
1307                                 while (length $dir) {
1308                                         $dir=~s![^/]+/$!!;
1309                                         push @page_locs, $dir.$page;
1310                                 }
1312                                 @page_locs = grep {
1313                                         ! exists $pagesources{lc($_)} &&
1314                                         ! page_locked($_, $session, 1)
1315                                 } @page_locs;
1316                         }
1318                         $form->tmpl_param("page_select", 1);
1319                         $form->field(name => "page", type => 'select',
1320                                 options => \@page_locs, value => $best_loc);
1321                         $form->title("creating $page");
1322                 }
1323                 elsif ($form->field("do") eq "edit") {
1324                         page_locked($page, $session);
1325                         if (! defined $form->field('content') || 
1326                             ! length $form->field('content')) {
1327                                 my $content="";
1328                                 if (exists $pagesources{lc($page)}) {
1329                                                 $content=readfile("$config{srcdir}/$pagesources{lc($page)}");
1330                                         $content=~s/\n/\r\n/g;
1331                                 }
1332                                 $form->field(name => "content", value => $content,
1333                                         force => 1);
1334                         }
1335                         $form->tmpl_param("page_select", 0);
1336                         $form->field(name => "page", type => 'hidden');
1337                         $form->title("editing $page");
1338                 }
1339                 
1340                 print $form->render(submit => \@buttons);
1341         }
1342         else {
1343                 # save page
1344                 page_locked($page, $session);
1345                 
1346                 my $content=$form->field('content');
1347                 $content=~s/\r\n/\n/g;
1348                 $content=~s/\r/\n/g;
1349                 writefile("$config{srcdir}/$file", $content);
1350                 
1351                 my $message="web commit ";
1352                 if (length $session->param("name")) {
1353                         $message.="by ".$session->param("name");
1354                 }
1355                 else {
1356                         $message.="from $ENV{REMOTE_ADDR}";
1357                 }
1358                 if (defined $form->field('comments') &&
1359                     length $form->field('comments')) {
1360                         $message.=": ".$form->field('comments');
1361                 }
1362                 
1363                 if ($config{svn}) {
1364                         if ($newfile) {
1365                                 rcs_add($file);
1366                         }
1367                         # prevent deadlock with post-commit hook
1368                         unlockwiki();
1369                         # presumably the commit will trigger an update
1370                         # of the wiki
1371                         my $conflict=rcs_commit($file, $message,
1372                                 $form->field("rcsinfo"));
1373                 
1374                         if (defined $conflict) {
1375                                 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
1376                                         force => 1);
1377                                 $form->tmpl_param("page_conflict", 1);
1378                                 $form->field("content", value => $conflict, force => 1);
1379                                 $form->field("do", "edit)");
1380                                 $form->tmpl_param("page_select", 0);
1381                                 $form->field(name => "page", type => 'hidden');
1382                                 $form->title("editing $page");
1383                                 print $form->render(submit => \@buttons);
1384                                 return;
1385                         }
1386                 }
1387                 else {
1388                         loadindex();
1389                         refresh();
1390                         saveindex();
1391                 }
1392                 
1393                 # The trailing question mark tries to avoid broken
1394                 # caches and get the most recent version of the page.
1395                 print $q->redirect("$config{url}/".htmlpage($page)."?updated");
1396         }
1397 } #}}}
1399 sub cgi () { #{{{
1400         eval q{use CGI};
1401         eval q{use CGI::Session};
1402         
1403         my $q=CGI->new;
1404         
1405         my $do=$q->param('do');
1406         if (! defined $do || ! length $do) {
1407                 error("\"do\" parameter missing");
1408         }
1409         
1410         # This does not need a session.
1411         if ($do eq 'recentchanges') {
1412                 cgi_recentchanges($q);
1413                 return;
1414         }
1415         
1416         CGI::Session->name("ikiwiki_session");
1418         my $oldmask=umask(077);
1419         my $session = CGI::Session->new("driver:db_file", $q,
1420                 { FileName => "$config{srcdir}/.ikiwiki/sessions.db" });
1421         umask($oldmask);
1422         
1423         # Everything below this point needs the user to be signed in.
1424         if ((! $config{anonok} && ! defined $session->param("name") ||
1425              ! defined $session->param("name") ||
1426              ! userinfo_get($session->param("name"), "regdate")) || $do eq 'signin') {
1427                 cgi_signin($q, $session);
1428         
1429                 # Force session flush with safe umask.
1430                 my $oldmask=umask(077);
1431                 $session->flush;
1432                 umask($oldmask);
1433                 
1434                 return;
1435         }
1436         
1437         if ($do eq 'create' || $do eq 'edit') {
1438                 cgi_editpage($q, $session);
1439         }
1440         elsif ($do eq 'prefs') {
1441                 cgi_prefs($q, $session);
1442         }
1443         else {
1444                 error("unknown do parameter");
1445         }
1446 } #}}}
1448 sub setup () { # {{{
1449         my $setup=possibly_foolish_untaint($config{setup});
1450         delete $config{setup};
1451         open (IN, $setup) || error("read $setup: $!\n");
1452         local $/=undef;
1453         my $code=<IN>;
1454         ($code)=$code=~/(.*)/s;
1455         close IN;
1457         eval $code;
1458         error($@) if $@;
1459         exit;
1460 } #}}}
1462 # main {{{
1463 setup() if $config{setup};
1464 lockwiki();
1465 if ($config{wrapper}) {
1466         gen_wrapper(%config);
1467         exit;
1469 memoize('pagename');
1470 memoize('bestlink');
1471 loadindex() unless $config{rebuild};
1472 if ($config{cgi}) {
1473         cgi();
1475 else {
1476         rcs_update() if $config{svn};
1477         refresh();
1478         saveindex();
1480 #}}}