avoid linkifying escaped wikilinks
[ikiwiki] / ikiwiki
1 #!/usr/bin/perl -T
2 $ENV{PATH}="/usr/local/bin:/usr/bin:/bin";
3
4 use warnings;
5 use strict;
6 use Memoize;
7 use File::Spec;
8 use HTML::Template;
9 use Getopt::Long;
10
11 my (%links, %oldlinks, %oldpagemtime, %renderedfiles, %pagesources);
12
13 my %config=( #{{{
14         wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.html?$)},
15         wiki_link_regexp => qr/\[\[([^\s]+)\]\]/,
16         wiki_file_regexp => qr/(^[-A-Za-z0-9_.:\/+]+$)/,
17         verbose => 0,
18         wikiname => "wiki",
19         default_pageext => ".mdwn",
20         cgi => 0,
21         svn => 1,
22         url => '',
23         cgiurl => '',
24         historyurl => '',
25         anonok => 0,
26         rebuild => 0,
27         wrapper => undef,
28         wrappermode => undef,
29         srcdir => undef,
30         destdir => undef,
31         templatedir => undef,
32         setup => undef,
33 ); #}}}
34
35 GetOptions( #{{{
36         "setup=s" => \$config{setup},
37         "wikiname=s" => \$config{wikiname},
38         "verbose|v!" => \$config{verbose},
39         "rebuild!" => \$config{rebuild},
40         "wrapper=s" => sub { $config{wrapper}=$_[1] ? $_[1] : "ikiwiki-wrap" },
41         "wrappermode=i" => \$config{wrappermode},
42         "svn!" => \$config{svn},
43         "anonok!" => \$config{anonok},
44         "cgi!" => \$config{cgi},
45         "url=s" => \$config{url},
46         "cgiurl=s" => \$config{cgiurl},
47         "historyurl=s" => \$config{historyurl},
48         "exclude=s@" => sub {
49                 $config{wiki_file_prune_regexp}=qr/$config{wiki_file_prune_regexp}|$_[1]/;
50         },
51 ) || usage();
52
53 if (! $config{setup}) {
54         usage() unless @ARGV == 3;
55         $config{srcdir} = possibly_foolish_untaint(shift);
56         $config{templatedir} = possibly_foolish_untaint(shift);
57         $config{destdir} = possibly_foolish_untaint(shift);
58         if ($config{cgi} && ! length $config{url}) {
59                 error("Must specify url to wiki with --url when using --cgi");
60         }
61 }
62 #}}}
63
64 sub usage { #{{{
65         die "usage: ikiwiki [options] source templates dest\n";
66 } #}}}
67
68 sub error { #{{{
69         if ($config{cgi}) {
70                 print "Content-type: text/html\n\n";
71                 print misctemplate("Error", "<p>Error: @_</p>");
72                 exit 1;
73         }
74         else {
75                 die @_;
76         }
77 } #}}}
78
79 sub debug ($) { #{{{
80         return unless $config{verbose};
81         if (! $config{cgi}) {
82                 print "@_\n";
83         }
84         else {
85                 print STDERR "@_\n";
86         }
87 } #}}}
88
89 sub mtime ($) { #{{{
90         my $page=shift;
91         
92         return (stat($page))[9];
93 } #}}}
94
95 sub possibly_foolish_untaint { #{{{
96         my $tainted=shift;
97         my ($untainted)=$tainted=~/(.*)/;
98         return $untainted;
99 } #}}}
100
101 sub basename ($) { #{{{
102         my $file=shift;
103
104         $file=~s!.*/!!;
105         return $file;
106 } #}}}
107
108 sub dirname ($) { #{{{
109         my $file=shift;
110
111         $file=~s!/?[^/]+$!!;
112         return $file;
113 } #}}}
114
115 sub pagetype ($) { #{{{
116         my $page=shift;
117         
118         if ($page =~ /\.mdwn$/) {
119                 return ".mdwn";
120         }
121         else {
122                 return "unknown";
123         }
124 } #}}}
125
126 sub pagename ($) { #{{{
127         my $file=shift;
128
129         my $type=pagetype($file);
130         my $page=$file;
131         $page=~s/\Q$type\E*$// unless $type eq 'unknown';
132         return $page;
133 } #}}}
134
135 sub htmlpage ($) { #{{{
136         my $page=shift;
137
138         return $page.".html";
139 } #}}}
140
141 sub readfile ($) { #{{{
142         my $file=shift;
143
144         local $/=undef;
145         open (IN, "$file") || error("failed to read $file: $!");
146         my $ret=<IN>;
147         close IN;
148         return $ret;
149 } #}}}
150
151 sub writefile ($$) { #{{{
152         my $file=shift;
153         my $content=shift;
154
155         my $dir=dirname($file);
156         if (! -d $dir) {
157                 my $d="";
158                 foreach my $s (split(m!/+!, $dir)) {
159                         $d.="$s/";
160                         if (! -d $d) {
161                                 mkdir($d) || error("failed to create directory $d: $!");
162                         }
163                 }
164         }
165         
166         open (OUT, ">$file") || error("failed to write $file: $!");
167         print OUT $content;
168         close OUT;
169 } #}}}
170
171 sub findlinks ($) { #{{{
172         my $content=shift;
173
174         my @links;
175         while ($content =~ /(?<!\\)$config{wiki_link_regexp}/g) {
176                 push @links, lc($1);
177         }
178         return @links;
179 } #}}}
180
181 sub bestlink ($$) { #{{{
182         # Given a page and the text of a link on the page, determine which
183         # existing page that link best points to. Prefers pages under a
184         # subdirectory with the same name as the source page, failing that
185         # goes down the directory tree to the base looking for matching
186         # pages.
187         my $page=shift;
188         my $link=lc(shift);
189         
190         my $cwd=$page;
191         do {
192                 my $l=$cwd;
193                 $l.="/" if length $l;
194                 $l.=$link;
195
196                 if (exists $links{$l}) {
197                         #debug("for $page, \"$link\", use $l");
198                         return $l;
199                 }
200         } while $cwd=~s!/?[^/]+$!!;
201
202         #print STDERR "warning: page $page, broken link: $link\n";
203         return "";
204 } #}}}
205
206 sub isinlinableimage ($) { #{{{
207         my $file=shift;
208         
209         $file=~/\.(png|gif|jpg|jpeg)$/;
210 } #}}}
211
212 sub htmllink { #{{{
213         my $page=shift;
214         my $link=shift;
215         my $noimageinline=shift; # don't turn links into inline html images
216         my $createsubpage=shift; # force creation of a subpage if page DNE
217
218         my $bestlink=bestlink($page, $link);
219
220         return $link if length $bestlink && $page eq $bestlink;
221         
222         # TODO BUG: %renderedfiles may not have it, if the linked to page
223         # was also added and isn't yet rendered! Note that this bug is
224         # masked by the bug mentioned below that makes all new files
225         # be rendered twice.
226         if (! grep { $_ eq $bestlink } values %renderedfiles) {
227                 $bestlink=htmlpage($bestlink);
228         }
229         if (! grep { $_ eq $bestlink } values %renderedfiles) {
230                 if (! $createsubpage) {
231                         return "<a href=\"$config{cgiurl}?do=create&page=$link&from=$page\">?</a>$link"
232                 }
233                 else {
234                         return "<a href=\"$config{cgiurl}?do=create&page=$page/$link\">?</a>$link"
235                 }
236         }
237         
238         $bestlink=File::Spec->abs2rel($bestlink, dirname($page));
239         
240         if (! $noimageinline && isinlinableimage($bestlink)) {
241                 return "<img src=\"$bestlink\">";
242         }
243         return "<a href=\"$bestlink\">$link</a>";
244 } #}}}
245
246 sub linkify ($$) { #{{{
247         my $content=shift;
248         my $file=shift;
249
250         $content =~ s{(\\?)$config{wiki_link_regexp}}{
251                 $1 ? "[[$2]]" : htmllink(pagename($file), $2)
252         }eg;
253         
254         return $content;
255 } #}}}
256
257 sub htmlize ($$) { #{{{
258         my $type=shift;
259         my $content=shift;
260         
261         if (! $INC{"/usr/bin/markdown"}) {
262                 no warnings 'once';
263                 $blosxom::version="is a proper perl module too much to ask?";
264                 use warnings 'all';
265                 do "/usr/bin/markdown";
266         }
267         
268         if ($type eq '.mdwn') {
269                 return Markdown::Markdown($content);
270         }
271         else {
272                 error("htmlization of $type not supported");
273         }
274 } #}}}
275
276 sub backlinks ($) { #{{{
277         my $page=shift;
278
279         my @links;
280         foreach my $p (keys %links) {
281                 next if bestlink($page, $p) eq $page;
282                 if (grep { length $_ && bestlink($p, $_) eq $page } @{$links{$p}}) {
283                         my $href=File::Spec->abs2rel(htmlpage($p), dirname($page));
284                         
285                         # Trim common dir prefixes from both pages.
286                         my $p_trimmed=$p;
287                         my $page_trimmed=$page;
288                         my $dir;
289                         1 while (($dir)=$page_trimmed=~m!^([^/]+/)!) &&
290                                 defined $dir &&
291                                 $p_trimmed=~s/^\Q$dir\E// &&
292                                 $page_trimmed=~s/^\Q$dir\E//;
293                                        
294                         push @links, { url => $href, page => $p_trimmed };
295                 }
296         }
297
298         return sort { $a->{page} cmp $b->{page} } @links;
299 } #}}}
300         
301 sub parentlinks ($) { #{{{
302         my $page=shift;
303         
304         my @ret;
305         my $pagelink="";
306         my $path="";
307         my $skip=1;
308         foreach my $dir (reverse split("/", $page)) {
309                 if (! $skip) {
310                         unshift @ret, { url => "$path$dir.html", page => $dir };
311                 }
312                 else {
313                         $skip=0;
314                 }
315                 $path.="../";
316         }
317         unshift @ret, { url => $path , page => $config{wikiname} };
318         return @ret;
319 } #}}}
320
321 sub indexlink () { #{{{
322         return "<a href=\"$config{url}\">$config{wikiname}</a>";
323 } #}}}
324
325 sub finalize ($$) { #{{{
326         my $content=shift;
327         my $page=shift;
328
329         my $title=basename($page);
330         $title=~s/_/ /g;
331         
332         my $template=HTML::Template->new(blind_cache => 1,
333                 filename => "$config{templatedir}/page.tmpl");
334         
335         if (length $config{cgiurl}) {
336                 $template->param(editurl => "$config{cgiurl}?do=edit&page=$page");
337                 if ($config{svn}) {
338                         $template->param(recentchangesurl => "$config{cgiurl}?do=recentchanges");
339                 }
340         }
341
342         if (length $config{historyurl}) {
343                 my $u=$config{historyurl};
344                 $u=~s/\[\[\]\]/$pagesources{$page}/g;
345                 $template->param(historyurl => $u);
346         }
347         
348         $template->param(
349                 title => $title,
350                 wikiname => $config{wikiname},
351                 parentlinks => [parentlinks($page)],
352                 content => $content,
353                 backlinks => [backlinks($page)],
354                 discussionlink => htmllink($page, "Discussion", 1, 1),
355         );
356         
357         return $template->output;
358 } #}}}
359
360 sub check_overwrite ($$) { #{{{
361         # Important security check. Make sure to call this before saving
362         # any files to the source directory.
363         my $dest=shift;
364         my $src=shift;
365         
366         if (! exists $renderedfiles{$src} && -e $dest && ! $config{rebuild}) {
367                 error("$dest exists and was rendered from ".
368                         join(" ",(grep { $renderedfiles{$_} eq $dest } keys
369                                 %renderedfiles)).
370                         ", not from $src before not overwriting");
371         }
372 } #}}}
373                 
374 sub render ($) { #{{{
375         my $file=shift;
376         
377         my $type=pagetype($file);
378         my $content=readfile("$config{srcdir}/$file");
379         if ($type ne 'unknown') {
380                 my $page=pagename($file);
381                 
382                 $links{$page}=[findlinks($content)];
383                 
384                 $content=linkify($content, $file);
385                 $content=htmlize($type, $content);
386                 $content=finalize($content, $page);
387                 
388                 check_overwrite("$config{destdir}/".htmlpage($page), $page);
389                 writefile("$config{destdir}/".htmlpage($page), $content);
390                 $oldpagemtime{$page}=time;
391                 $renderedfiles{$page}=htmlpage($page);
392         }
393         else {
394                 $links{$file}=[];
395                 check_overwrite("$config{destdir}/$file", $file);
396                 writefile("$config{destdir}/$file", $content);
397                 $oldpagemtime{$file}=time;
398                 $renderedfiles{$file}=$file;
399         }
400 } #}}}
401
402 sub loadindex () { #{{{
403         open (IN, "$config{srcdir}/.ikiwiki/index") || return;
404         while (<IN>) {
405                 $_=possibly_foolish_untaint($_);
406                 chomp;
407                 my ($mtime, $file, $rendered, @links)=split(' ', $_);
408                 my $page=pagename($file);
409                 $pagesources{$page}=$file;
410                 $oldpagemtime{$page}=$mtime;
411                 $oldlinks{$page}=[@links];
412                 $links{$page}=[@links];
413                 $renderedfiles{$page}=$rendered;
414         }
415         close IN;
416 } #}}}
417
418 sub saveindex () { #{{{
419         if (! -d "$config{srcdir}/.ikiwiki") {
420                 mkdir("$config{srcdir}/.ikiwiki");
421         }
422         open (OUT, ">$config{srcdir}/.ikiwiki/index") || error("cannot write to index: $!");
423         foreach my $page (keys %oldpagemtime) {
424                 print OUT "$oldpagemtime{$page} $pagesources{$page} $renderedfiles{$page} ".
425                         join(" ", @{$links{$page}})."\n"
426                                 if $oldpagemtime{$page};
427         }
428         close OUT;
429 } #}}}
430
431 sub rcs_update () { #{{{
432         if (-d "$config{srcdir}/.svn") {
433                 if (system("svn", "update", "--quiet", $config{srcdir}) != 0) {
434                         warn("svn update failed\n");
435                 }
436         }
437 } #}}}
438
439 sub rcs_commit ($) { #{{{
440         my $message=shift;
441
442         if (-d "$config{srcdir}/.svn") {
443                 if (system("svn", "commit", "--quiet", "-m",
444                            possibly_foolish_untaint($message),
445                            $config{srcdir}) != 0) {
446                         warn("svn commit failed\n");
447                 }
448         }
449 } #}}}
450
451 sub rcs_add ($) { #{{{
452         my $file=shift;
453
454         if (-d "$config{srcdir}/.svn") {
455                 my $parent=dirname($file);
456                 while (! -d "$config{srcdir}/$parent/.svn") {
457                         $file=$parent;
458                         $parent=dirname($file);
459                 }
460                 
461                 if (system("svn", "add", "--quiet", "$config{srcdir}/$file") != 0) {
462                         warn("svn add failed\n");
463                 }
464         }
465 } #}}}
466
467 sub rcs_recentchanges ($) { #{{{
468         my $num=shift;
469         my @ret;
470         
471         eval q{use Date::Parse};
472         eval q{use Time::Duration};
473         
474         if (-d "$config{srcdir}/.svn") {
475                 my $info=`LANG=C svn info $config{srcdir}`;
476                 my ($svn_url)=$info=~/^URL: (.*)$/m;
477
478                 # FIXME: currently assumes that the wiki is somewhere
479                 # under trunk in svn, doesn't support other layouts.
480                 my ($svn_base)=$svn_url=~m!(/trunk(?:/.*)?)$!;
481                 
482                 my $div=qr/^--------------------+$/;
483                 my $infoline=qr/^r(\d+)\s+\|\s+([^\s]+)\s+\|\s+(\d+-\d+-\d+\s+\d+:\d+:\d+\s+[-+]?\d+).*/;
484                 my $state='start';
485                 my ($rev, $user, $when, @pages, @message);
486                 foreach (`LANG=C svn log -v '$svn_url'`) {
487                         chomp;
488                         if ($state eq 'start' && /$div/) {
489                                 $state='header';
490                         }
491                         elsif ($state eq 'header' && /$infoline/) {
492                                 $rev=$1;
493                                 $user=$2;
494                                 $when=concise(ago(time - str2time($3)));
495                         }
496                         elsif ($state eq 'header' && /^\s+[A-Z]\s+\Q$svn_base\E\/(.+)$/) {
497                                 push @pages, { link => htmllink("", pagename($1), 1) }
498                                         if length $1;
499                         }
500                         elsif ($state eq 'header' && /^$/) {
501                                 $state='body';
502                         }
503                         elsif ($state eq 'body' && /$div/) {
504                                 my $committype="web";
505                                 if (defined $message[0] &&
506                                     $message[0]->{line}=~/^web commit by (\w+):?(.*)/) {
507                                         $user="$1";
508                                         $message[0]->{line}=$2;
509                                 }
510                                 else {
511                                         $committype="svn";
512                                 }
513                                 
514                                 push @ret, { rev => $rev,
515                                         user => htmllink("", $user, 1),
516                                         committype => $committype,
517                                         when => $when, message => [@message],
518                                         pages => [@pages] } if @pages;
519                                 return @ret if @ret >= $num;
520                                 
521                                 $state='header';
522                                 $rev=$user=$when=undef;
523                                 @pages=@message=();
524                         }
525                         elsif ($state eq 'body') {
526                                 push @message, {line => $_},
527                         }
528                 }
529         }
530
531         return @ret;
532 } #}}}
533
534 sub prune ($) { #{{{
535         my $file=shift;
536
537         unlink($file);
538         my $dir=dirname($file);
539         while (rmdir($dir)) {
540                 $dir=dirname($dir);
541         }
542 } #}}}
543
544 sub refresh () { #{{{
545         # Find existing pages.
546         my %exists;
547         my @files;
548         
549         eval q{use File::Find};
550         find({
551                 no_chdir => 1,
552                 wanted => sub {
553                         if (/$config{wiki_file_prune_regexp}/) {
554                                 no warnings 'once';
555                                 $File::Find::prune=1;
556                                 use warnings "all";
557                         }
558                         elsif (! -d $_) {
559                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
560                                 if (! defined $f) {
561                                         warn("skipping bad filename $_\n");
562                                 }
563                                 else {
564                                         $f=~s/^\Q$config{srcdir}\E\/?//;
565                                         push @files, $f;
566                                         $exists{pagename($f)}=1;
567                                 }
568                         }
569                 },
570         }, $config{srcdir});
571
572         my %rendered;
573
574         # check for added or removed pages
575         my @add;
576         foreach my $file (@files) {
577                 my $page=pagename($file);
578                 if (! $oldpagemtime{$page}) {
579                         debug("new page $page");
580                         push @add, $file;
581                         $links{$page}=[];
582                         $pagesources{$page}=$file;
583                 }
584         }
585         my @del;
586         foreach my $page (keys %oldpagemtime) {
587                 if (! $exists{$page}) {
588                         debug("removing old page $page");
589                         push @del, $renderedfiles{$page};
590                         prune($config{destdir}."/".$renderedfiles{$page});
591                         delete $renderedfiles{$page};
592                         $oldpagemtime{$page}=0;
593                         delete $pagesources{$page};
594                 }
595         }
596         
597         # render any updated files
598         foreach my $file (@files) {
599                 my $page=pagename($file);
600                 
601                 if (! exists $oldpagemtime{$page} ||
602                     mtime("$config{srcdir}/$file") > $oldpagemtime{$page}) {
603                         debug("rendering changed file $file");
604                         render($file);
605                         $rendered{$file}=1;
606                 }
607         }
608         
609         # if any files were added or removed, check to see if each page
610         # needs an update due to linking to them
611         # TODO: inefficient; pages may get rendered above and again here;
612         # problem is the bestlink may have changed and we won't know until
613         # now
614         if (@add || @del) {
615 FILE:           foreach my $file (@files) {
616                         my $page=pagename($file);
617                         foreach my $f (@add, @del) {
618                                 my $p=pagename($f);
619                                 foreach my $link (@{$links{$page}}) {
620                                         if (bestlink($page, $link) eq $p) {
621                                                 debug("rendering $file, which links to $p");
622                                                 render($file);
623                                                 $rendered{$file}=1;
624                                                 next FILE;
625                                         }
626                                 }
627                         }
628                 }
629         }
630
631         # handle backlinks; if a page has added/removed links, update the
632         # pages it links to
633         # TODO: inefficient; pages may get rendered above and again here;
634         # problem is the backlinks could be wrong in the first pass render
635         # above
636         if (%rendered) {
637                 my %linkchanged;
638                 foreach my $file (keys %rendered, @del) {
639                         my $page=pagename($file);
640                         if (exists $links{$page}) {
641                                 foreach my $link (@{$links{$page}}) {
642                                         $link=bestlink($page, $link);
643                                         if (length $link &&
644                                             ! exists $oldlinks{$page} ||
645                                             ! grep { $_ eq $link } @{$oldlinks{$page}}) {
646                                                 $linkchanged{$link}=1;
647                                         }
648                                 }
649                         }
650                         if (exists $oldlinks{$page}) {
651                                 foreach my $link (@{$oldlinks{$page}}) {
652                                         $link=bestlink($page, $link);
653                                         if (length $link &&
654                                             ! exists $links{$page} ||
655                                             ! grep { $_ eq $link } @{$links{$page}}) {
656                                                 $linkchanged{$link}=1;
657                                         }
658                                 }
659                         }
660                 }
661                 foreach my $link (keys %linkchanged) {
662                         my $linkfile=$pagesources{$link};
663                         if (defined $linkfile) {
664                                 debug("rendering $linkfile, to update its backlinks");
665                                 render($linkfile);
666                         }
667                 }
668         }
669 } #}}}
670
671 sub gen_wrapper (@) { #{{{
672         my %config=(@_);
673         eval q{use Cwd 'abs_path'};
674         $config{srcdir}=abs_path($config{srcdir});
675         $config{destdir}=abs_path($config{destdir});
676         my $this=abs_path($0);
677         if (! -x $this) {
678                 error("$this doesn't seem to be executable");
679         }
680
681         if ($config{setup}) {
682                 error("cannot create a wrapper that uses a setup file");
683         }
684         
685         my @params=($config{srcdir}, $config{templatedir}, $config{destdir},
686                 "--wikiname=$config{wikiname}");
687         push @params, "--verbose" if $config{verbose};
688         push @params, "--rebuild" if $config{rebuild};
689         push @params, "--nosvn" if !$config{svn};
690         push @params, "--cgi" if $config{cgi};
691         push @params, "--url=$config{url}" if length $config{url};
692         push @params, "--cgiurl=$config{cgiurl}" if length $config{cgiurl};
693         push @params, "--historyurl=$config{historyurl}" if length $config{historyurl};
694         push @params, "--anonok" if $config{anonok};
695         my $params=join(" ", map { "\'$_\'" } @params);
696         my $call='';
697         foreach my $p ($this, $this, @params) {
698                 $call.=qq{"$p", };
699         }
700         $call.="NULL";
701         
702         my @envsave;
703         push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
704                        CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
705                        HTTP_COOKIE} if $config{cgi};
706         my $envsave="";
707         foreach my $var (@envsave) {
708                 $envsave.=<<"EOF"
709         if ((s=getenv("$var")))
710                 asprintf(&newenviron[i++], "%s=%s", "$var", s);
711 EOF
712         }
713         
714         open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
715         print OUT <<"EOF";
716 /* A wrapper for ikiwiki, can be safely made suid. */
717 #define _GNU_SOURCE
718 #include <stdio.h>
719 #include <unistd.h>
720 #include <stdlib.h>
721 #include <string.h>
722
723 extern char **environ;
724
725 int main (int argc, char **argv) {
726         /* Sanitize environment. */
727         char *s;
728         char *newenviron[$#envsave+3];
729         int i=0;
730 $envsave
731         newenviron[i++]="HOME=$ENV{HOME}";
732         newenviron[i]=NULL;
733         environ=newenviron;
734
735         if (argc == 2 && strcmp(argv[1], "--params") == 0) {
736                 printf("$params\\n");
737                 exit(0);
738         }
739         
740         execl($call);
741         perror("failed to run $this");
742         exit(1);
743 }
744 EOF
745         close OUT;
746         if (system("gcc", "ikiwiki-wrap.c", "-o", possibly_foolish_untaint($config{wrapper})) != 0) {
747                 error("failed to compile ikiwiki-wrap.c");
748         }
749         unlink("ikiwiki-wrap.c");
750         if (defined $config{wrappermode} &&
751             ! chmod(oct($config{wrappermode}), possibly_foolish_untaint($config{wrapper}))) {
752                 error("chmod $config{wrapper}: $!");
753         }
754         print "successfully generated $config{wrapper}\n";
755 } #}}}
756                 
757 sub misctemplate ($$) { #{{{
758         my $title=shift;
759         my $pagebody=shift;
760         
761         my $template=HTML::Template->new(
762                 filename => "$config{templatedir}/misc.tmpl"
763         );
764         $template->param(
765                 title => $title,
766                 indexlink => indexlink(),
767                 wikiname => $config{wikiname},
768                 pagebody => $pagebody,
769         );
770         return $template->output;
771 }#}}}
772
773 sub cgi_recentchanges ($) { #{{{
774         my $q=shift;
775         
776         my $template=HTML::Template->new(
777                 filename => "$config{templatedir}/recentchanges.tmpl"
778         );
779         $template->param(
780                 title => "RecentChanges",
781                 indexlink => indexlink(),
782                 wikiname => $config{wikiname},
783                 changelog => [rcs_recentchanges(100)],
784         );
785         print $q->header, $template->output;
786 } #}}}
787
788 sub userinfo_get ($$) { #{{{
789         my $user=shift;
790         my $field=shift;
791
792         eval q{use Storable};
793         my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
794         if (! defined $userdata || ! ref $userdata || 
795             ! exists $userdata->{$user} || ! ref $userdata->{$user}) {
796                 return "";
797         }
798         return $userdata->{$user}->{$field};
799 } #}}}
800
801 sub userinfo_set ($$) { #{{{
802         my $user=shift;
803         my $info=shift;
804         
805         eval q{use Storable};
806         my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
807         if (! defined $userdata || ! ref $userdata) {
808                 $userdata={};
809         }
810         $userdata->{$user}=$info;
811         my $oldmask=umask(077);
812         my $ret=Storable::lock_store($userdata, "$config{srcdir}/.ikiwiki/userdb");
813         umask($oldmask);
814         return $ret;
815 } #}}}
816
817 sub cgi_signin ($$) { #{{{
818         my $q=shift;
819         my $session=shift;
820
821         eval q{use CGI::FormBuilder};
822         my $form = CGI::FormBuilder->new(
823                 title => "$config{wikiname} signin",
824                 fields => [qw(do page from name password confirm_password email)],
825                 header => 1,
826                 method => 'POST',
827                 validate => {
828                         confirm_password => {
829                                 perl => q{eq $form->field("password")},
830                         },
831                         email => 'EMAIL',
832                 },
833                 required => 'NONE',
834                 javascript => 0,
835                 params => $q,
836                 action => $q->request_uri,
837                 header => 0,
838                 template => (-e "$config{templatedir}/signin.tmpl" ?
839                               "$config{templatedir}/signin.tmpl" : "")
840         );
841         
842         $form->field(name => "name", required => 0);
843         $form->field(name => "do", type => "hidden");
844         $form->field(name => "page", type => "hidden");
845         $form->field(name => "from", type => "hidden");
846         $form->field(name => "password", type => "password", required => 0);
847         $form->field(name => "confirm_password", type => "password", required => 0);
848         $form->field(name => "email", required => 0);
849         if ($q->param("do") ne "signin") {
850                 $form->text("You need to log in before you can edit pages.");
851         }
852         
853         if ($form->submitted) {
854                 # Set required fields based on how form was submitted.
855                 my %required=(
856                         "Login" => [qw(name password)],
857                         "Register" => [qw(name password confirm_password email)],
858                         "Mail Password" => [qw(name)],
859                 );
860                 foreach my $opt (@{$required{$form->submitted}}) {
861                         $form->field(name => $opt, required => 1);
862                 }
863         
864                 # Validate password differently depending on how
865                 # form was submitted.
866                 if ($form->submitted eq 'Login') {
867                         $form->field(
868                                 name => "password",
869                                 validate => sub {
870                                         length $form->field("name") &&
871                                         shift eq userinfo_get($form->field("name"), 'password');
872                                 },
873                         );
874                         $form->field(name => "name", validate => '/^\w+$/');
875                 }
876                 else {
877                         $form->field(name => "password", validate => 'VALUE');
878                 }
879                 # And make sure the entered name exists when logging
880                 # in or sending email, and does not when registering.
881                 if ($form->submitted eq 'Register') {
882                         $form->field(
883                                 name => "name",
884                                 validate => sub {
885                                         my $name=shift;
886                                         length $name &&
887                                         ! userinfo_get($name, "regdate");
888                                 },
889                         );
890                 }
891                 else {
892                         $form->field(
893                                 name => "name",
894                                 validate => sub {
895                                         my $name=shift;
896                                         length $name &&
897                                         userinfo_get($name, "regdate");
898                                 },
899                         );
900                 }
901         }
902         else {
903                 # First time settings.
904                 $form->field(name => "name", comment => "use FirstnameLastName");
905                 $form->field(name => "confirm_password", comment => "(only needed");
906                 $form->field(name => "email",            comment => "for registration)");
907                 if ($session->param("name")) {
908                         $form->field(name => "name", value => $session->param("name"));
909                 }
910         }
911
912         if ($form->submitted && $form->validate) {
913                 if ($form->submitted eq 'Login') {
914                         $session->param("name", $form->field("name"));
915                         if (defined $form->field("do") && 
916                             $form->field("do") ne 'signin') {
917                                 print $q->redirect(
918                                         "$config{cgiurl}?do=".$form->field("do").
919                                         "&page=".$form->field("page").
920                                         "&from=".$form->field("from"));;
921                         }
922                         else {
923                                 print $q->redirect($config{url});
924                         }
925                 }
926                 elsif ($form->submitted eq 'Register') {
927                         my $user_name=$form->field('name');
928                         if (userinfo_set($user_name, {
929                                            'email' => $form->field('email'),
930                                            'password' => $form->field('password'),
931                                            'regdate' => time
932                                          })) {
933                                 $form->field(name => "confirm_password", type => "hidden");
934                                 $form->field(name => "email", type => "hidden");
935                                 $form->text("Registration successful. Now you can Login.");
936                                 print $session->header();
937                                 print misctemplate($form->title, $form->render(submit => ["Login"]));
938                         }
939                         else {
940                                 error("Error saving registration.");
941                         }
942                 }
943                 elsif ($form->submitted eq 'Mail Password') {
944                         my $user_name=$form->field("name");
945                         my $template=HTML::Template->new(
946                                 filename => "$config{templatedir}/passwordmail.tmpl"
947                         );
948                         $template->param(
949                                 user_name => $user_name,
950                                 user_password => userinfo_get($user_name, "password"),
951                                 wikiurl => $config{url},
952                                 wikiname => $config{wikiname},
953                                 REMOTE_ADDR => $ENV{REMOTE_ADDR},
954                         );
955                         
956                         eval q{use Mail::Sendmail};
957                         my ($fromhost) = $config{cgiurl} =~ m!/([^/]+)!;
958                         sendmail(
959                                 To => userinfo_get($user_name, "email"),
960                                 From => "$config{wikiname} admin <".(getpwuid($>))[0]."@".$fromhost.">",
961                                 Subject => "$config{wikiname} information",
962                                 Message => $template->output,
963                         ) or error("Failed to send mail");
964                         
965                         $form->text("Your password has been emailed to you.");
966                         $form->field(name => "name", required => 0);
967                         print $session->header();
968                         print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
969                 }
970         }
971         else {
972                 print $session->header();
973                 print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
974         }
975 } #}}}
976
977 sub cgi_editpage ($$) { #{{{
978         my $q=shift;
979         my $session=shift;
980
981         eval q{use CGI::FormBuilder};
982         my $form = CGI::FormBuilder->new(
983                 fields => [qw(do from page content comments)],
984                 header => 1,
985                 method => 'POST',
986                 validate => {
987                         content => '/.+/',
988                 },
989                 required => [qw{content}],
990                 javascript => 0,
991                 params => $q,
992                 action => $q->request_uri,
993                 table => 0,
994                 template => "$config{templatedir}/editpage.tmpl"
995         );
996         
997         my ($page)=$form->param('page')=~/$config{wiki_file_regexp}/;
998         if (! defined $page || ! length $page || $page ne $q->param('page') ||
999             $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
1000                 error("bad page name");
1001         }
1002         $page=lc($page);
1003
1004         $form->field(name => "do", type => 'hidden');
1005         $form->field(name => "from", type => 'hidden');
1006         $form->field(name => "page", value => "$page", force => 1);
1007         $form->field(name => "comments", type => "text", size => 80);
1008         $form->field(name => "content", type => "textarea", rows => 20,
1009                 cols => 80);
1010         
1011         if ($form->submitted eq "Cancel") {
1012                 print $q->redirect("$config{url}/".htmlpage($page));
1013                 return;
1014         }
1015         if (! $form->submitted || ! $form->validate) {
1016                 if ($form->field("do") eq "create") {
1017                         if (exists $pagesources{lc($page)}) {
1018                                 # hmm, someone else made the page in the
1019                                 # meantime?
1020                                 print $q->redirect("$config{url}/".htmlpage($page));
1021                                 return;
1022                         }
1023                         
1024                         my @page_locs;
1025                         my ($from)=$form->param('from')=~/$config{wiki_file_regexp}/;
1026                         if (! defined $from || ! length $from ||
1027                             $from ne $form->param('from') ||
1028                             $from=~/$config{wiki_file_prune_regexp}/ || $from=~/^\//) {
1029                                 @page_locs=$page;
1030                         }
1031                         else {
1032                                 my $dir=$from."/";
1033                                 $dir=~s![^/]+/$!!;
1034                                 push @page_locs, $dir.$page;
1035                                 push @page_locs, "$from/$page";
1036                                 while (length $dir) {
1037                                         $dir=~s![^/]+/$!!;
1038                                         push @page_locs, $dir.$page;
1039                                 }
1040                         }
1041
1042                         $form->tmpl_param("page_select", 1);
1043                         $form->field(name => "page", type => 'select',
1044                                 options => \@page_locs);
1045                         $form->title("creating $page");
1046                 }
1047                 elsif ($form->field("do") eq "edit") {
1048                         my $content="";
1049                         if (exists $pagesources{lc($page)}) {
1050                                 $content=readfile("$config{srcdir}/$pagesources{lc($page)}");
1051                                 $content=~s/\n/\r\n/g;
1052                         }
1053                         $form->tmpl_param("page_select", 0);
1054                         $form->field(name => "content", value => $content,
1055                                 force => 1);
1056                         $form->field(name => "page", type => 'hidden');
1057                         $form->title("editing $page");
1058                 }
1059                 
1060                 $form->tmpl_param("can_commit", $config{svn});
1061                 $form->tmpl_param("indexlink", indexlink());
1062                 print $form->render(submit => ["Save Page", "Cancel"]);
1063         }
1064         else {
1065                 # save page
1066                 my $file=$page.$config{default_pageext};
1067                 my $newfile=1;
1068                 if (exists $pagesources{lc($page)}) {
1069                         $file=$pagesources{lc($page)};
1070                         $newfile=0;
1071                 }
1072                 
1073                 my $content=$form->field('content');
1074                 $content=~s/\r\n/\n/g;
1075                 $content=~s/\r/\n/g;
1076                 writefile("$config{srcdir}/$file", $content);
1077                 
1078                 my $message="web commit ";
1079                 if ($session->param("name")) {
1080                         $message.="by ".$session->param("name");
1081                 }
1082                 else {
1083                         $message.="from $ENV{REMOTE_ADDR}";
1084                 }
1085                 if (defined $form->field('comments') &&
1086                     length $form->field('comments')) {
1087                         $message.=": ".$form->field('comments');
1088                 }
1089                 
1090                 if ($config{svn}) {
1091                         if ($newfile) {
1092                                 rcs_add($file);
1093                         }
1094                         # presumably the commit will trigger an update
1095                         # of the wiki
1096                         rcs_commit($message);
1097                 }
1098                 else {
1099                         refresh();
1100                 }
1101                 
1102                 # The trailing question mark tries to avoid broken
1103                 # caches and get the most recent version of the page.
1104                 print $q->redirect("$config{url}/".htmlpage($page)."?updated");
1105         }
1106 } #}}}
1107
1108 sub cgi () { #{{{
1109         eval q{use CGI};
1110         eval q{use CGI::Session};
1111         
1112         my $q=CGI->new;
1113         
1114         my $do=$q->param('do');
1115         if (! defined $do || ! length $do) {
1116                 error("\"do\" parameter missing");
1117         }
1118         
1119         # This does not need a session.
1120         if ($do eq 'recentchanges') {
1121                 cgi_recentchanges($q);
1122                 return;
1123         }
1124         
1125         CGI::Session->name("ikiwiki_session");
1126
1127         my $oldmask=umask(077);
1128         my $session = CGI::Session->new("driver:db_file", $q,
1129                 { FileName => "$config{srcdir}/.ikiwiki/sessions.db" });
1130         umask($oldmask);
1131         
1132         # Everything below this point needs the user to be signed in.
1133         if ((! $config{anonok} && ! defined $session->param("name") ||
1134                 ! userinfo_get($session->param("name"), "regdate")) || $do eq 'signin') {
1135                 cgi_signin($q, $session);
1136         
1137                 # Force session flush with safe umask.
1138                 my $oldmask=umask(077);
1139                 $session->flush;
1140                 umask($oldmask);
1141                 
1142                 return;
1143         }
1144         
1145         if ($do eq 'create' || $do eq 'edit') {
1146                 cgi_editpage($q, $session);
1147         }
1148         else {
1149                 error("unknown do parameter");
1150         }
1151 } #}}}
1152
1153 sub setup () { # {{{
1154         my $setup=possibly_foolish_untaint($config{setup});
1155         open (IN, $setup) || error("read $setup: $!\n");
1156         local $/=undef;
1157         my $code=<IN>;
1158         ($code)=$code=~/(.*)/s;
1159         close IN;
1160         eval $code;
1161         error($@) if $@;
1162         print "ikiwiki setup complete\n";
1163         exit;
1164 } #}}}
1165
1166 # main {{{
1167 setup() if $config{setup};
1168 if ($config{wrapper}) {
1169         gen_wrapper(%config);
1170         exit;
1171 }
1172 memoize('pagename');
1173 memoize('bestlink');
1174 loadindex() unless $config{rebuild};
1175 if ($config{cgi}) {
1176         cgi();
1177 }
1178 else {
1179         rcs_update() if $config{svn};
1180         refresh();
1181         saveindex();
1182 }
1183 #}}}