]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - ikiwiki
*warning* any wrappers built with a previous version of ikiwiki need to be
[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 => "/usr/share/ikiwiki/templates",
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         "templatedir=s" => sub { $config{templatedir}=possibly_foolish_untaint($_[1]) },
60 ) || usage();
62 if (! $config{setup}) {
63         usage() unless @ARGV == 2;
64         $config{srcdir} = 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 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{destdir},
776                 "--wikiname=$config{wikiname}",
777                 "--templatedir=$config{templatedir}");
778         push @params, "--verbose" if $config{verbose};
779         push @params, "--rebuild" if $config{rebuild};
780         push @params, "--nosvn" if !$config{svn};
781         push @params, "--cgi" if $config{cgi};
782         push @params, "--url=$config{url}" if length $config{url};
783         push @params, "--cgiurl=$config{cgiurl}" if length $config{cgiurl};
784         push @params, "--historyurl=$config{historyurl}" if length $config{historyurl};
785         push @params, "--diffurl=$config{diffurl}" if length $config{diffurl};
786         push @params, "--anonok" if $config{anonok};
787         push @params, "--adminuser=$_" foreach @{$config{adminuser}};
788         my $params=join(" ", @params);
789         my $call='';
790         foreach my $p ($this, $this, @params) {
791                 $call.=qq{"$p", };
792         }
793         $call.="NULL";
794         
795         my @envsave;
796         push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
797                        CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
798                        HTTP_COOKIE} if $config{cgi};
799         my $envsave="";
800         foreach my $var (@envsave) {
801                 $envsave.=<<"EOF"
802         if ((s=getenv("$var")))
803                 asprintf(&newenviron[i++], "%s=%s", "$var", s);
804 EOF
805         }
806         
807         open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
808         print OUT <<"EOF";
809 /* A wrapper for ikiwiki, can be safely made suid. */
810 #define _GNU_SOURCE
811 #include <stdio.h>
812 #include <unistd.h>
813 #include <stdlib.h>
814 #include <string.h>
816 extern char **environ;
818 int main (int argc, char **argv) {
819         /* Sanitize environment. */
820         char *s;
821         char *newenviron[$#envsave+3];
822         int i=0;
823 $envsave
824         newenviron[i++]="HOME=$ENV{HOME}";
825         newenviron[i]=NULL;
826         environ=newenviron;
828         if (argc == 2 && strcmp(argv[1], "--params") == 0) {
829                 printf("$params\\n");
830                 exit(0);
831         }
832         
833         execl($call);
834         perror("failed to run $this");
835         exit(1);
837 EOF
838         close OUT;
839         if (system("gcc", "ikiwiki-wrap.c", "-o", possibly_foolish_untaint($config{wrapper})) != 0) {
840                 error("failed to compile ikiwiki-wrap.c");
841         }
842         unlink("ikiwiki-wrap.c");
843         if (defined $config{wrappermode} &&
844             ! chmod(oct($config{wrappermode}), possibly_foolish_untaint($config{wrapper}))) {
845                 error("chmod $config{wrapper}: $!");
846         }
847         print "successfully generated $config{wrapper}\n";
848 } #}}}
849                 
850 sub misctemplate ($$) { #{{{
851         my $title=shift;
852         my $pagebody=shift;
853         
854         my $template=HTML::Template->new(
855                 filename => "$config{templatedir}/misc.tmpl"
856         );
857         $template->param(
858                 title => $title,
859                 indexlink => indexlink(),
860                 wikiname => $config{wikiname},
861                 pagebody => $pagebody,
862         );
863         return $template->output;
864 }#}}}
866 sub cgi_recentchanges ($) { #{{{
867         my $q=shift;
868         
869         my $template=HTML::Template->new(
870                 filename => "$config{templatedir}/recentchanges.tmpl"
871         );
872         $template->param(
873                 title => "RecentChanges",
874                 indexlink => indexlink(),
875                 wikiname => $config{wikiname},
876                 changelog => [rcs_recentchanges(100)],
877         );
878         print $q->header, $template->output;
879 } #}}}
881 sub userinfo_get ($$) { #{{{
882         my $user=shift;
883         my $field=shift;
885         eval q{use Storable};
886         my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
887         if (! defined $userdata || ! ref $userdata || 
888             ! exists $userdata->{$user} || ! ref $userdata->{$user} ||
889             ! exists $userdata->{$user}->{$field}) {
890                 return "";
891         }
892         return $userdata->{$user}->{$field};
893 } #}}}
895 sub userinfo_set ($$$) { #{{{
896         my $user=shift;
897         my $field=shift;
898         my $value=shift;
899         
900         eval q{use Storable};
901         my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
902         if (! defined $userdata || ! ref $userdata || 
903             ! exists $userdata->{$user} || ! ref $userdata->{$user}) {
904                 return "";
905         }
906         
907         $userdata->{$user}->{$field}=$value;
908         my $oldmask=umask(077);
909         my $ret=Storable::lock_store($userdata, "$config{srcdir}/.ikiwiki/userdb");
910         umask($oldmask);
911         return $ret;
912 } #}}}
914 sub userinfo_setall ($$) { #{{{
915         my $user=shift;
916         my $info=shift;
917         
918         eval q{use Storable};
919         my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
920         if (! defined $userdata || ! ref $userdata) {
921                 $userdata={};
922         }
923         $userdata->{$user}=$info;
924         my $oldmask=umask(077);
925         my $ret=Storable::lock_store($userdata, "$config{srcdir}/.ikiwiki/userdb");
926         umask($oldmask);
927         return $ret;
928 } #}}}
930 sub cgi_signin ($$) { #{{{
931         my $q=shift;
932         my $session=shift;
934         eval q{use CGI::FormBuilder};
935         my $form = CGI::FormBuilder->new(
936                 title => "signin",
937                 fields => [qw(do page from name password confirm_password email)],
938                 header => 1,
939                 method => 'POST',
940                 validate => {
941                         confirm_password => {
942                                 perl => q{eq $form->field("password")},
943                         },
944                         email => 'EMAIL',
945                 },
946                 required => 'NONE',
947                 javascript => 0,
948                 params => $q,
949                 action => $q->request_uri,
950                 header => 0,
951                 template => (-e "$config{templatedir}/signin.tmpl" ?
952                               "$config{templatedir}/signin.tmpl" : "")
953         );
954         
955         $form->field(name => "name", required => 0);
956         $form->field(name => "do", type => "hidden");
957         $form->field(name => "page", type => "hidden");
958         $form->field(name => "from", type => "hidden");
959         $form->field(name => "password", type => "password", required => 0);
960         $form->field(name => "confirm_password", type => "password", required => 0);
961         $form->field(name => "email", required => 0);
962         if ($q->param("do") ne "signin") {
963                 $form->text("You need to log in first.");
964         }
965         
966         if ($form->submitted) {
967                 # Set required fields based on how form was submitted.
968                 my %required=(
969                         "Login" => [qw(name password)],
970                         "Register" => [qw(name password confirm_password email)],
971                         "Mail Password" => [qw(name)],
972                 );
973                 foreach my $opt (@{$required{$form->submitted}}) {
974                         $form->field(name => $opt, required => 1);
975                 }
976         
977                 # Validate password differently depending on how
978                 # form was submitted.
979                 if ($form->submitted eq 'Login') {
980                         $form->field(
981                                 name => "password",
982                                 validate => sub {
983                                         length $form->field("name") &&
984                                         shift eq userinfo_get($form->field("name"), 'password');
985                                 },
986                         );
987                         $form->field(name => "name", validate => '/^\w+$/');
988                 }
989                 else {
990                         $form->field(name => "password", validate => 'VALUE');
991                 }
992                 # And make sure the entered name exists when logging
993                 # in or sending email, and does not when registering.
994                 if ($form->submitted eq 'Register') {
995                         $form->field(
996                                 name => "name",
997                                 validate => sub {
998                                         my $name=shift;
999                                         length $name &&
1000                                         ! userinfo_get($name, "regdate");
1001                                 },
1002                         );
1003                 }
1004                 else {
1005                         $form->field(
1006                                 name => "name",
1007                                 validate => sub {
1008                                         my $name=shift;
1009                                         length $name &&
1010                                         userinfo_get($name, "regdate");
1011                                 },
1012                         );
1013                 }
1014         }
1015         else {
1016                 # First time settings.
1017                 $form->field(name => "name", comment => "use FirstnameLastName");
1018                 $form->field(name => "confirm_password", comment => "(only needed");
1019                 $form->field(name => "email",            comment => "for registration)");
1020                 if ($session->param("name")) {
1021                         $form->field(name => "name", value => $session->param("name"));
1022                 }
1023         }
1025         if ($form->submitted && $form->validate) {
1026                 if ($form->submitted eq 'Login') {
1027                         $session->param("name", $form->field("name"));
1028                         if (defined $form->field("do") && 
1029                             $form->field("do") ne 'signin') {
1030                                 print $q->redirect(
1031                                         "$config{cgiurl}?do=".$form->field("do").
1032                                         "&page=".$form->field("page").
1033                                         "&from=".$form->field("from"));;
1034                         }
1035                         else {
1036                                 print $q->redirect($config{url});
1037                         }
1038                 }
1039                 elsif ($form->submitted eq 'Register') {
1040                         my $user_name=$form->field('name');
1041                         if (userinfo_setall($user_name, {
1042                                            'email' => $form->field('email'),
1043                                            'password' => $form->field('password'),
1044                                            'regdate' => time
1045                                          })) {
1046                                 $form->field(name => "confirm_password", type => "hidden");
1047                                 $form->field(name => "email", type => "hidden");
1048                                 $form->text("Registration successful. Now you can Login.");
1049                                 print $session->header();
1050                                 print misctemplate($form->title, $form->render(submit => ["Login"]));
1051                         }
1052                         else {
1053                                 error("Error saving registration.");
1054                         }
1055                 }
1056                 elsif ($form->submitted eq 'Mail Password') {
1057                         my $user_name=$form->field("name");
1058                         my $template=HTML::Template->new(
1059                                 filename => "$config{templatedir}/passwordmail.tmpl"
1060                         );
1061                         $template->param(
1062                                 user_name => $user_name,
1063                                 user_password => userinfo_get($user_name, "password"),
1064                                 wikiurl => $config{url},
1065                                 wikiname => $config{wikiname},
1066                                 REMOTE_ADDR => $ENV{REMOTE_ADDR},
1067                         );
1068                         
1069                         eval q{use Mail::Sendmail};
1070                         my ($fromhost) = $config{cgiurl} =~ m!/([^/]+)!;
1071                         sendmail(
1072                                 To => userinfo_get($user_name, "email"),
1073                                 From => "$config{wikiname} admin <".(getpwuid($>))[0]."@".$fromhost.">",
1074                                 Subject => "$config{wikiname} information",
1075                                 Message => $template->output,
1076                         ) or error("Failed to send mail");
1077                         
1078                         $form->text("Your password has been emailed to you.");
1079                         $form->field(name => "name", required => 0);
1080                         print $session->header();
1081                         print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
1082                 }
1083         }
1084         else {
1085                 print $session->header();
1086                 print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
1087         }
1088 } #}}}
1090 sub is_admin ($) { #{{{
1091         my $user_name=shift;
1093         return grep { $_ eq $user_name } @{$config{adminuser}};
1094 } #}}}
1096 sub glob_match ($$) { #{{{
1097         my $page=shift;
1098         my $glob=shift;
1100         # turn glob into safe regexp
1101         $glob=quotemeta($glob);
1102         $glob=~s/\\\*/.*/g;
1103         $glob=~s/\\\?/./g;
1104         $glob=~s!\\/!/!g;
1105         
1106         $page=~/^$glob$/i;
1107 } #}}}
1109 sub globlist_match ($$) { #{{{
1110         my $page=shift;
1111         my @globlist=split(" ", shift);
1113         # check any negated globs first
1114         foreach my $glob (@globlist) {
1115                 return 0 if $glob=~/^!(.*)/ && glob_match($page, $1);
1116         }
1118         foreach my $glob (@globlist) {
1119                 return 1 if glob_match($page, $glob);
1120         }
1121         
1122         return 0;
1123 } #}}}
1125 sub page_locked ($$;$) { #{{{
1126         my $page=shift;
1127         my $session=shift;
1128         my $nonfatal=shift;
1129         
1130         my $user=$session->param("name");
1131         return if length $user && is_admin($user);
1133         foreach my $admin (@{$config{adminuser}}) {
1134                 my $locked_pages=userinfo_get($admin, "locked_pages");
1135                 if (globlist_match($page, userinfo_get($admin, "locked_pages"))) {
1136                         return 1 if $nonfatal;
1137                         error(htmllink("", $page, 1)." is locked by ".
1138                               htmllink("", $admin, 1)." and cannot be edited.");
1139                 }
1140         }
1142         return 0;
1143 } #}}}
1145 sub cgi_prefs ($$) { #{{{
1146         my $q=shift;
1147         my $session=shift;
1149         eval q{use CGI::FormBuilder};
1150         my $form = CGI::FormBuilder->new(
1151                 title => "preferences",
1152                 fields => [qw(do name password confirm_password email locked_pages)],
1153                 header => 0,
1154                 method => 'POST',
1155                 validate => {
1156                         confirm_password => {
1157                                 perl => q{eq $form->field("password")},
1158                         },
1159                         email => 'EMAIL',
1160                 },
1161                 required => 'NONE',
1162                 javascript => 0,
1163                 params => $q,
1164                 action => $q->request_uri,
1165                 template => (-e "$config{templatedir}/prefs.tmpl" ?
1166                               "$config{templatedir}/prefs.tmpl" : "")
1167         );
1168         my @buttons=("Save Preferences", "Logout", "Cancel");
1169         
1170         my $user_name=$session->param("name");
1171         $form->field(name => "do", type => "hidden");
1172         $form->field(name => "name", disabled => 1,
1173                 value => $user_name, force => 1);
1174         $form->field(name => "password", type => "password");
1175         $form->field(name => "confirm_password", type => "password");
1176         $form->field(name => "locked_pages", size => 50,
1177                 comment => "(".htmllink("", "GlobList", 1).")");
1178         
1179         if (! is_admin($user_name)) {
1180                 $form->field(name => "locked_pages", type => "hidden");
1181         }
1182         
1183         if (! $form->submitted) {
1184                 $form->field(name => "email", force => 1,
1185                         value => userinfo_get($user_name, "email"));
1186                 $form->field(name => "locked_pages", force => 1,
1187                         value => userinfo_get($user_name, "locked_pages"));
1188         }
1189         
1190         if ($form->submitted eq 'Logout') {
1191                 $session->delete();
1192                 print $q->redirect($config{url});
1193                 return;
1194         }
1195         elsif ($form->submitted eq 'Cancel') {
1196                 print $q->redirect($config{url});
1197                 return;
1198         }
1199         elsif ($form->submitted eq "Save Preferences" && $form->validate) {
1200                 foreach my $field (qw(password email locked_pages)) {
1201                         if (length $form->field($field)) {
1202                                 userinfo_set($user_name, $field, $form->field($field)) || error("failed to set $field");
1203                         }
1204                 }
1205                 $form->text("Preferences saved.");
1206         }
1207         
1208         print $session->header();
1209         print misctemplate($form->title, $form->render(submit => \@buttons));
1210 } #}}}
1212 sub cgi_editpage ($$) { #{{{
1213         my $q=shift;
1214         my $session=shift;
1216         eval q{use CGI::FormBuilder};
1217         my $form = CGI::FormBuilder->new(
1218                 fields => [qw(do rcsinfo from page content comments)],
1219                 header => 1,
1220                 method => 'POST',
1221                 validate => {
1222                         content => '/.+/',
1223                 },
1224                 required => [qw{content}],
1225                 javascript => 0,
1226                 params => $q,
1227                 action => $q->request_uri,
1228                 table => 0,
1229                 template => "$config{templatedir}/editpage.tmpl"
1230         );
1231         my @buttons=("Save Page", "Preview", "Cancel");
1232         
1233         my ($page)=$form->param('page')=~/$config{wiki_file_regexp}/;
1234         if (! defined $page || ! length $page || $page ne $q->param('page') ||
1235             $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
1236                 error("bad page name");
1237         }
1238         $page=lc($page);
1239         
1240         my $file=$page.$config{default_pageext};
1241         my $newfile=1;
1242         if (exists $pagesources{lc($page)}) {
1243                 $file=$pagesources{lc($page)};
1244                 $newfile=0;
1245         }
1247         $form->field(name => "do", type => 'hidden');
1248         $form->field(name => "from", type => 'hidden');
1249         $form->field(name => "rcsinfo", type => 'hidden');
1250         $form->field(name => "page", value => "$page", force => 1);
1251         $form->field(name => "comments", type => "text", size => 80);
1252         $form->field(name => "content", type => "textarea", rows => 20,
1253                 cols => 80);
1254         $form->tmpl_param("can_commit", $config{svn});
1255         $form->tmpl_param("indexlink", indexlink());
1256         $form->tmpl_param("helponformattinglink",
1257                 htmllink("", "HelpOnFormatting", 1));
1258         if (! $form->submitted) {
1259                 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
1260                         force => 1);
1261         }
1262         
1263         if ($form->submitted eq "Cancel") {
1264                 print $q->redirect("$config{url}/".htmlpage($page));
1265                 return;
1266         }
1267         elsif ($form->submitted eq "Preview") {
1268                 $form->tmpl_param("page_preview",
1269                         htmlize($config{default_pageext},
1270                                 linkify($form->field('content'), $page)));
1271         }
1272         else {
1273                 $form->tmpl_param("page_preview", "");
1274         }
1275         $form->tmpl_param("page_conflict", "");
1276         
1277         if (! $form->submitted || $form->submitted eq "Preview" || 
1278             ! $form->validate) {
1279                 if ($form->field("do") eq "create") {
1280                         if (exists $pagesources{lc($page)}) {
1281                                 # hmm, someone else made the page in the
1282                                 # meantime?
1283                                 print $q->redirect("$config{url}/".htmlpage($page));
1284                                 return;
1285                         }
1286                         
1287                         my @page_locs;
1288                         my $best_loc;
1289                         my ($from)=$form->param('from')=~/$config{wiki_file_regexp}/;
1290                         if (! defined $from || ! length $from ||
1291                             $from ne $form->param('from') ||
1292                             $from=~/$config{wiki_file_prune_regexp}/ || $from=~/^\//) {
1293                                 @page_locs=$best_loc=$page;
1294                         }
1295                         else {
1296                                 my $dir=$from."/";
1297                                 $dir=~s![^/]+/$!!;
1298                                 
1299                                 if ($page eq 'discussion') {
1300                                         $best_loc="$from/$page";
1301                                 }
1302                                 else {
1303                                         $best_loc=$dir.$page;
1304                                 }
1305                                 
1306                                 push @page_locs, $dir.$page;
1307                                 push @page_locs, "$from/$page";
1308                                 while (length $dir) {
1309                                         $dir=~s![^/]+/$!!;
1310                                         push @page_locs, $dir.$page;
1311                                 }
1313                                 @page_locs = grep {
1314                                         ! exists $pagesources{lc($_)} &&
1315                                         ! page_locked($_, $session, 1)
1316                                 } @page_locs;
1317                         }
1319                         $form->tmpl_param("page_select", 1);
1320                         $form->field(name => "page", type => 'select',
1321                                 options => \@page_locs, value => $best_loc);
1322                         $form->title("creating $page");
1323                 }
1324                 elsif ($form->field("do") eq "edit") {
1325                         page_locked($page, $session);
1326                         if (! defined $form->field('content') || 
1327                             ! length $form->field('content')) {
1328                                 my $content="";
1329                                 if (exists $pagesources{lc($page)}) {
1330                                                 $content=readfile("$config{srcdir}/$pagesources{lc($page)}");
1331                                         $content=~s/\n/\r\n/g;
1332                                 }
1333                                 $form->field(name => "content", value => $content,
1334                                         force => 1);
1335                         }
1336                         $form->tmpl_param("page_select", 0);
1337                         $form->field(name => "page", type => 'hidden');
1338                         $form->title("editing $page");
1339                 }
1340                 
1341                 print $form->render(submit => \@buttons);
1342         }
1343         else {
1344                 # save page
1345                 page_locked($page, $session);
1346                 
1347                 my $content=$form->field('content');
1348                 $content=~s/\r\n/\n/g;
1349                 $content=~s/\r/\n/g;
1350                 writefile("$config{srcdir}/$file", $content);
1351                 
1352                 my $message="web commit ";
1353                 if (length $session->param("name")) {
1354                         $message.="by ".$session->param("name");
1355                 }
1356                 else {
1357                         $message.="from $ENV{REMOTE_ADDR}";
1358                 }
1359                 if (defined $form->field('comments') &&
1360                     length $form->field('comments')) {
1361                         $message.=": ".$form->field('comments');
1362                 }
1363                 
1364                 if ($config{svn}) {
1365                         if ($newfile) {
1366                                 rcs_add($file);
1367                         }
1368                         # prevent deadlock with post-commit hook
1369                         unlockwiki();
1370                         # presumably the commit will trigger an update
1371                         # of the wiki
1372                         my $conflict=rcs_commit($file, $message,
1373                                 $form->field("rcsinfo"));
1374                 
1375                         if (defined $conflict) {
1376                                 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
1377                                         force => 1);
1378                                 $form->tmpl_param("page_conflict", 1);
1379                                 $form->field("content", value => $conflict, force => 1);
1380                                 $form->field("do", "edit)");
1381                                 $form->tmpl_param("page_select", 0);
1382                                 $form->field(name => "page", type => 'hidden');
1383                                 $form->title("editing $page");
1384                                 print $form->render(submit => \@buttons);
1385                                 return;
1386                         }
1387                 }
1388                 else {
1389                         loadindex();
1390                         refresh();
1391                         saveindex();
1392                 }
1393                 
1394                 # The trailing question mark tries to avoid broken
1395                 # caches and get the most recent version of the page.
1396                 print $q->redirect("$config{url}/".htmlpage($page)."?updated");
1397         }
1398 } #}}}
1400 sub cgi () { #{{{
1401         eval q{use CGI};
1402         eval q{use CGI::Session};
1403         
1404         my $q=CGI->new;
1405         
1406         my $do=$q->param('do');
1407         if (! defined $do || ! length $do) {
1408                 error("\"do\" parameter missing");
1409         }
1410         
1411         # This does not need a session.
1412         if ($do eq 'recentchanges') {
1413                 cgi_recentchanges($q);
1414                 return;
1415         }
1416         
1417         CGI::Session->name("ikiwiki_session");
1419         my $oldmask=umask(077);
1420         my $session = CGI::Session->new("driver:db_file", $q,
1421                 { FileName => "$config{srcdir}/.ikiwiki/sessions.db" });
1422         umask($oldmask);
1423         
1424         # Everything below this point needs the user to be signed in.
1425         if ((! $config{anonok} && ! defined $session->param("name") ||
1426              ! defined $session->param("name") ||
1427              ! userinfo_get($session->param("name"), "regdate")) || $do eq 'signin') {
1428                 cgi_signin($q, $session);
1429         
1430                 # Force session flush with safe umask.
1431                 my $oldmask=umask(077);
1432                 $session->flush;
1433                 umask($oldmask);
1434                 
1435                 return;
1436         }
1437         
1438         if ($do eq 'create' || $do eq 'edit') {
1439                 cgi_editpage($q, $session);
1440         }
1441         elsif ($do eq 'prefs') {
1442                 cgi_prefs($q, $session);
1443         }
1444         else {
1445                 error("unknown do parameter");
1446         }
1447 } #}}}
1449 sub setup () { # {{{
1450         my $setup=possibly_foolish_untaint($config{setup});
1451         delete $config{setup};
1452         open (IN, $setup) || error("read $setup: $!\n");
1453         local $/=undef;
1454         my $code=<IN>;
1455         ($code)=$code=~/(.*)/s;
1456         close IN;
1458         eval $code;
1459         error($@) if $@;
1460         exit;
1461 } #}}}
1463 # main {{{
1464 setup() if $config{setup};
1465 lockwiki();
1466 if ($config{wrapper}) {
1467         gen_wrapper(%config);
1468         exit;
1470 memoize('pagename');
1471 memoize('bestlink');
1472 loadindex() unless $config{rebuild};
1473 if ($config{cgi}) {
1474         cgi();
1476 else {
1477         rcs_update() if $config{svn};
1478         refresh();
1479         saveindex();
1481 #}}}