escape html from commit logs
[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 # Holds global config settings, also used by some modules.
14 our %config=( #{{{
15         wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.html?$)},
16         wiki_link_regexp => qr/\[\[([^\s]+)\]\]/,
17         wiki_file_regexp => qr/(^[-A-Za-z0-9_.:\/+]+$)/,
18         verbose => 0,
19         wikiname => "wiki",
20         default_pageext => ".mdwn",
21         cgi => 0,
22         svn => 1,
23         url => '',
24         cgiurl => '',
25         historyurl => '',
26         anonok => 0,
27         rebuild => 0,
28         wrapper => undef,
29         wrappermode => undef,
30         srcdir => undef,
31         destdir => undef,
32         templatedir => undef,
33         setup => undef,
34 ); #}}}
35
36 GetOptions( #{{{
37         "setup=s" => \$config{setup},
38         "wikiname=s" => \$config{wikiname},
39         "verbose|v!" => \$config{verbose},
40         "rebuild!" => \$config{rebuild},
41         "wrapper=s" => sub { $config{wrapper}=$_[1] ? $_[1] : "ikiwiki-wrap" },
42         "wrappermode=i" => \$config{wrappermode},
43         "svn!" => \$config{svn},
44         "anonok!" => \$config{anonok},
45         "cgi!" => \$config{cgi},
46         "url=s" => \$config{url},
47         "cgiurl=s" => \$config{cgiurl},
48         "historyurl=s" => \$config{historyurl},
49         "exclude=s@" => sub {
50                 $config{wiki_file_prune_regexp}=qr/$config{wiki_file_prune_regexp}|$_[1]/;
51         },
52 ) || usage();
53
54 if (! $config{setup}) {
55         usage() unless @ARGV == 3;
56         $config{srcdir} = possibly_foolish_untaint(shift);
57         $config{templatedir} = possibly_foolish_untaint(shift);
58         $config{destdir} = possibly_foolish_untaint(shift);
59         if ($config{cgi} && ! length $config{url}) {
60                 error("Must specify url to wiki with --url when using --cgi");
61         }
62 }
63 #}}}
64
65 sub usage { #{{{
66         die "usage: ikiwiki [options] source templates dest\n";
67 } #}}}
68
69 sub error { #{{{
70         if ($config{cgi}) {
71                 print "Content-type: text/html\n\n";
72                 print misctemplate("Error", "<p>Error: @_</p>");
73         }
74         die @_;
75 } #}}}
76
77 sub debug ($) { #{{{
78         return unless $config{verbose};
79         if (! $config{cgi}) {
80                 print "@_\n";
81         }
82         else {
83                 print STDERR "@_\n";
84         }
85 } #}}}
86
87 sub mtime ($) { #{{{
88         my $page=shift;
89         
90         return (stat($page))[9];
91 } #}}}
92
93 sub possibly_foolish_untaint { #{{{
94         my $tainted=shift;
95         my ($untainted)=$tainted=~/(.*)/;
96         return $untainted;
97 } #}}}
98
99 sub basename ($) { #{{{
100         my $file=shift;
101
102         $file=~s!.*/!!;
103         return $file;
104 } #}}}
105
106 sub dirname ($) { #{{{
107         my $file=shift;
108
109         $file=~s!/?[^/]+$!!;
110         return $file;
111 } #}}}
112
113 sub pagetype ($) { #{{{
114         my $page=shift;
115         
116         if ($page =~ /\.mdwn$/) {
117                 return ".mdwn";
118         }
119         else {
120                 return "unknown";
121         }
122 } #}}}
123
124 sub pagename ($) { #{{{
125         my $file=shift;
126
127         my $type=pagetype($file);
128         my $page=$file;
129         $page=~s/\Q$type\E*$// unless $type eq 'unknown';
130         return $page;
131 } #}}}
132
133 sub htmlpage ($) { #{{{
134         my $page=shift;
135
136         return $page.".html";
137 } #}}}
138
139 sub readfile ($) { #{{{
140         my $file=shift;
141
142         local $/=undef;
143         open (IN, "$file") || error("failed to read $file: $!");
144         my $ret=<IN>;
145         close IN;
146         return $ret;
147 } #}}}
148
149 sub writefile ($$) { #{{{
150         my $file=shift;
151         my $content=shift;
152
153         my $dir=dirname($file);
154         if (! -d $dir) {
155                 my $d="";
156                 foreach my $s (split(m!/+!, $dir)) {
157                         $d.="$s/";
158                         if (! -d $d) {
159                                 mkdir($d) || error("failed to create directory $d: $!");
160                         }
161                 }
162         }
163         
164         open (OUT, ">$file") || error("failed to write $file: $!");
165         print OUT $content;
166         close OUT;
167 } #}}}
168
169 sub findlinks ($$) { #{{{
170         my $content=shift;
171         my $page=shift;
172
173         my @links;
174         while ($content =~ /(?<!\\)$config{wiki_link_regexp}/g) {
175                 push @links, lc($1);
176         }
177         # Discussion links are a special case since they're not in the text
178         # of the page, but on its template.
179         return @links, "$page/discussion";
180 } #}}}
181
182 sub bestlink ($$) { #{{{
183         # Given a page and the text of a link on the page, determine which
184         # existing page that link best points to. Prefers pages under a
185         # subdirectory with the same name as the source page, failing that
186         # goes down the directory tree to the base looking for matching
187         # pages.
188         my $page=shift;
189         my $link=lc(shift);
190         
191         my $cwd=$page;
192         do {
193                 my $l=$cwd;
194                 $l.="/" if length $l;
195                 $l.=$link;
196
197                 if (exists $links{$l}) {
198                         #debug("for $page, \"$link\", use $l");
199                         return $l;
200                 }
201         } while $cwd=~s!/?[^/]+$!!;
202
203         #print STDERR "warning: page $page, broken link: $link\n";
204         return "";
205 } #}}}
206
207 sub isinlinableimage ($) { #{{{
208         my $file=shift;
209         
210         $file=~/\.(png|gif|jpg|jpeg)$/;
211 } #}}}
212
213 sub htmllink { #{{{
214         my $page=shift;
215         my $link=shift;
216         my $noimageinline=shift; # don't turn links into inline html images
217         my $forcesubpage=shift; # force a link to a subpage
218
219         my $bestlink;
220         if (! $forcesubpage) {
221                 $bestlink=bestlink($page, $link);
222         }
223         else {
224                 $bestlink="$page/".lc($link);
225         }
226
227         return $link if length $bestlink && $page eq $bestlink;
228         
229         # TODO BUG: %renderedfiles may not have it, if the linked to page
230         # was also added and isn't yet rendered! Note that this bug is
231         # masked by the bug mentioned below that makes all new files
232         # be rendered twice.
233         if (! grep { $_ eq $bestlink } values %renderedfiles) {
234                 $bestlink=htmlpage($bestlink);
235         }
236         if (! grep { $_ eq $bestlink } values %renderedfiles) {
237                 return "<a href=\"$config{cgiurl}?do=create&page=$link&from=$page\">?</a>$link"
238         }
239         
240         $bestlink=File::Spec->abs2rel($bestlink, dirname($page));
241         
242         if (! $noimageinline && isinlinableimage($bestlink)) {
243                 return "<img src=\"$bestlink\">";
244         }
245         return "<a href=\"$bestlink\">$link</a>";
246 } #}}}
247
248 sub linkify ($$) { #{{{
249         my $content=shift;
250         my $file=shift;
251
252         $content =~ s{(\\?)$config{wiki_link_regexp}}{
253                 $1 ? "[[$2]]" : htmllink(pagename($file), $2)
254         }eg;
255         
256         return $content;
257 } #}}}
258
259 sub htmlize ($$) { #{{{
260         my $type=shift;
261         my $content=shift;
262         
263         if (! $INC{"/usr/bin/markdown"}) {
264                 no warnings 'once';
265                 $blosxom::version="is a proper perl module too much to ask?";
266                 use warnings 'all';
267                 do "/usr/bin/markdown";
268         }
269         
270         if ($type eq '.mdwn') {
271                 return Markdown::Markdown($content);
272         }
273         else {
274                 error("htmlization of $type not supported");
275         }
276 } #}}}
277
278 sub backlinks ($) { #{{{
279         my $page=shift;
280
281         my @links;
282         foreach my $p (keys %links) {
283                 next if bestlink($page, $p) eq $page;
284                 if (grep { length $_ && bestlink($p, $_) eq $page } @{$links{$p}}) {
285                         my $href=File::Spec->abs2rel(htmlpage($p), dirname($page));
286                         
287                         # Trim common dir prefixes from both pages.
288                         my $p_trimmed=$p;
289                         my $page_trimmed=$page;
290                         my $dir;
291                         1 while (($dir)=$page_trimmed=~m!^([^/]+/)!) &&
292                                 defined $dir &&
293                                 $p_trimmed=~s/^\Q$dir\E// &&
294                                 $page_trimmed=~s/^\Q$dir\E//;
295                                        
296                         push @links, { url => $href, page => $p_trimmed };
297                 }
298         }
299
300         return sort { $a->{page} cmp $b->{page} } @links;
301 } #}}}
302         
303 sub parentlinks ($) { #{{{
304         my $page=shift;
305         
306         my @ret;
307         my $pagelink="";
308         my $path="";
309         my $skip=1;
310         foreach my $dir (reverse split("/", $page)) {
311                 if (! $skip) {
312                         $path.="../";
313                         unshift @ret, { url => "$path$dir.html", page => $dir };
314                 }
315                 else {
316                         $skip=0;
317                 }
318         }
319         unshift @ret, { url => length $path ? $path : ".", page => $config{wikiname} };
320         return @ret;
321 } #}}}
322
323 sub indexlink () { #{{{
324         return "<a href=\"$config{url}\">$config{wikiname}</a>";
325 } #}}}
326
327 sub finalize ($$) { #{{{
328         my $content=shift;
329         my $page=shift;
330
331         my $title=basename($page);
332         $title=~s/_/ /g;
333         
334         my $template=HTML::Template->new(blind_cache => 1,
335                 filename => "$config{templatedir}/page.tmpl");
336         
337         if (length $config{cgiurl}) {
338                 $template->param(editurl => "$config{cgiurl}?do=edit&page=$page");
339                 if ($config{svn}) {
340                         $template->param(recentchangesurl => "$config{cgiurl}?do=recentchanges");
341                 }
342         }
343
344         if (length $config{historyurl}) {
345                 my $u=$config{historyurl};
346                 $u=~s/\[\[\]\]/$pagesources{$page}/g;
347                 $template->param(historyurl => $u);
348         }
349         
350         $template->param(
351                 title => $title,
352                 wikiname => $config{wikiname},
353                 parentlinks => [parentlinks($page)],
354                 content => $content,
355                 backlinks => [backlinks($page)],
356                 discussionlink => htmllink($page, "Discussion", 1, 1),
357         );
358         
359         return $template->output;
360 } #}}}
361
362 sub check_overwrite ($$) { #{{{
363         # Important security check. Make sure to call this before saving
364         # any files to the source directory.
365         my $dest=shift;
366         my $src=shift;
367         
368         if (! exists $renderedfiles{$src} && -e $dest && ! $config{rebuild}) {
369                 error("$dest already exists and was rendered from ".
370                         join(" ",(grep { $renderedfiles{$_} eq $dest } keys
371                                 %renderedfiles)).
372                         ", before, so not rendering from $src");
373         }
374 } #}}}
375                 
376 sub render ($) { #{{{
377         my $file=shift;
378         
379         my $type=pagetype($file);
380         my $content=readfile("$config{srcdir}/$file");
381         if ($type ne 'unknown') {
382                 my $page=pagename($file);
383                 
384                 $links{$page}=[findlinks($content, $page)];
385                 
386                 $content=linkify($content, $file);
387                 $content=htmlize($type, $content);
388                 $content=finalize($content, $page);
389                 
390                 check_overwrite("$config{destdir}/".htmlpage($page), $page);
391                 writefile("$config{destdir}/".htmlpage($page), $content);
392                 $oldpagemtime{$page}=time;
393                 $renderedfiles{$page}=htmlpage($page);
394         }
395         else {
396                 $links{$file}=[];
397                 check_overwrite("$config{destdir}/$file", $file);
398                 writefile("$config{destdir}/$file", $content);
399                 $oldpagemtime{$file}=time;
400                 $renderedfiles{$file}=$file;
401         }
402 } #}}}
403
404 sub loadindex () { #{{{
405         open (IN, "$config{srcdir}/.ikiwiki/index") || return;
406         while (<IN>) {
407                 $_=possibly_foolish_untaint($_);
408                 chomp;
409                 my ($mtime, $file, $rendered, @links)=split(' ', $_);
410                 my $page=pagename($file);
411                 $pagesources{$page}=$file;
412                 $oldpagemtime{$page}=$mtime;
413                 $oldlinks{$page}=[@links];
414                 $links{$page}=[@links];
415                 $renderedfiles{$page}=$rendered;
416         }
417         close IN;
418 } #}}}
419
420 sub saveindex () { #{{{
421         if (! -d "$config{srcdir}/.ikiwiki") {
422                 mkdir("$config{srcdir}/.ikiwiki");
423         }
424         open (OUT, ">$config{srcdir}/.ikiwiki/index") || error("cannot write to index: $!");
425         foreach my $page (keys %oldpagemtime) {
426                 print OUT "$oldpagemtime{$page} $pagesources{$page} $renderedfiles{$page} ".
427                         join(" ", @{$links{$page}})."\n"
428                                 if $oldpagemtime{$page};
429         }
430         close OUT;
431 } #}}}
432
433 sub rcs_update () { #{{{
434         if (-d "$config{srcdir}/.svn") {
435                 if (system("svn", "update", "--quiet", $config{srcdir}) != 0) {
436                         warn("svn update failed\n");
437                 }
438         }
439 } #}}}
440
441 sub rcs_commit ($) { #{{{
442         my $message=shift;
443
444         if (-d "$config{srcdir}/.svn") {
445                 if (system("svn", "commit", "--quiet", "-m",
446                            possibly_foolish_untaint($message),
447                            $config{srcdir}) != 0) {
448                         warn("svn commit failed\n");
449                 }
450         }
451 } #}}}
452
453 sub rcs_add ($) { #{{{
454         my $file=shift;
455
456         if (-d "$config{srcdir}/.svn") {
457                 my $parent=dirname($file);
458                 while (! -d "$config{srcdir}/$parent/.svn") {
459                         $file=$parent;
460                         $parent=dirname($file);
461                 }
462                 
463                 if (system("svn", "add", "--quiet", "$config{srcdir}/$file") != 0) {
464                         warn("svn add failed\n");
465                 }
466         }
467 } #}}}
468
469 sub rcs_recentchanges ($) { #{{{
470         my $num=shift;
471         my @ret;
472         
473         eval q{use Date::Parse};
474         eval q{use Time::Duration};
475         
476         if (-d "$config{srcdir}/.svn") {
477                 my $info=`LANG=C svn info $config{srcdir}`;
478                 my ($svn_url)=$info=~/^URL: (.*)$/m;
479
480                 # FIXME: currently assumes that the wiki is somewhere
481                 # under trunk in svn, doesn't support other layouts.
482                 my ($svn_base)=$svn_url=~m!(/trunk(?:/.*)?)$!;
483                 
484                 my $div=qr/^--------------------+$/;
485                 my $infoline=qr/^r(\d+)\s+\|\s+([^\s]+)\s+\|\s+(\d+-\d+-\d+\s+\d+:\d+:\d+\s+[-+]?\d+).*/;
486                 my $state='start';
487                 my ($rev, $user, $when, @pages, @message);
488                 foreach (`LANG=C svn log -v '$svn_url'`) {
489                         chomp;
490                         if ($state eq 'start' && /$div/) {
491                                 $state='header';
492                         }
493                         elsif ($state eq 'header' && /$infoline/) {
494                                 $rev=$1;
495                                 $user=$2;
496                                 $when=concise(ago(time - str2time($3)));
497                         }
498                         elsif ($state eq 'header' && /^\s+[A-Z]\s+\Q$svn_base\E\/(.+)$/) {
499                                 push @pages, { link => htmllink("", pagename($1), 1) }
500                                         if length $1;
501                         }
502                         elsif ($state eq 'header' && /^$/) {
503                                 $state='body';
504                         }
505                         elsif ($state eq 'body' && /$div/) {
506                                 my $committype="web";
507                                 if (defined $message[0] &&
508                                     $message[0]->{line}=~/^web commit by (\w+):?(.*)/) {
509                                         $user="$1";
510                                         $message[0]->{line}=$2;
511                                 }
512                                 else {
513                                         $committype="svn";
514                                 }
515                                 
516                                 push @ret, { rev => $rev,
517                                         user => htmllink("", $user, 1),
518                                         committype => $committype,
519                                         when => $when, message => [@message],
520                                         pages => [@pages] } if @pages;
521                                 return @ret if @ret >= $num;
522                                 
523                                 $state='header';
524                                 $rev=$user=$when=undef;
525                                 @pages=@message=();
526                         }
527                         elsif ($state eq 'body') {
528                                 push @message, {line => escapeHTML($_)},
529                         }
530                 }
531         }
532
533         return @ret;
534 } #}}}
535
536 sub prune ($) { #{{{
537         my $file=shift;
538
539         unlink($file);
540         my $dir=dirname($file);
541         while (rmdir($dir)) {
542                 $dir=dirname($dir);
543         }
544 } #}}}
545
546 sub refresh () { #{{{
547         # Find existing pages.
548         my %exists;
549         my @files;
550         
551         eval q{use File::Find};
552         find({
553                 no_chdir => 1,
554                 wanted => sub {
555                         if (/$config{wiki_file_prune_regexp}/) {
556                                 no warnings 'once';
557                                 $File::Find::prune=1;
558                                 use warnings "all";
559                         }
560                         elsif (! -d $_) {
561                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
562                                 if (! defined $f) {
563                                         warn("skipping bad filename $_\n");
564                                 }
565                                 else {
566                                         $f=~s/^\Q$config{srcdir}\E\/?//;
567                                         push @files, $f;
568                                         $exists{pagename($f)}=1;
569                                 }
570                         }
571                 },
572         }, $config{srcdir});
573
574         my %rendered;
575
576         # check for added or removed pages
577         my @add;
578         foreach my $file (@files) {
579                 my $page=pagename($file);
580                 if (! $oldpagemtime{$page}) {
581                         debug("new page $page");
582                         push @add, $file;
583                         $links{$page}=[];
584                         $pagesources{$page}=$file;
585                 }
586         }
587         my @del;
588         foreach my $page (keys %oldpagemtime) {
589                 if (! $exists{$page}) {
590                         debug("removing old page $page");
591                         push @del, $renderedfiles{$page};
592                         prune($config{destdir}."/".$renderedfiles{$page});
593                         delete $renderedfiles{$page};
594                         $oldpagemtime{$page}=0;
595                         delete $pagesources{$page};
596                 }
597         }
598         
599         # render any updated files
600         foreach my $file (@files) {
601                 my $page=pagename($file);
602                 
603                 if (! exists $oldpagemtime{$page} ||
604                     mtime("$config{srcdir}/$file") > $oldpagemtime{$page}) {
605                         debug("rendering changed file $file");
606                         render($file);
607                         $rendered{$file}=1;
608                 }
609         }
610         
611         # if any files were added or removed, check to see if each page
612         # needs an update due to linking to them
613         # TODO: inefficient; pages may get rendered above and again here;
614         # problem is the bestlink may have changed and we won't know until
615         # now
616         if (@add || @del) {
617 FILE:           foreach my $file (@files) {
618                         my $page=pagename($file);
619                         foreach my $f (@add, @del) {
620                                 my $p=pagename($f);
621                                 foreach my $link (@{$links{$page}}) {
622                                         if (bestlink($page, $link) eq $p) {
623                                                 debug("rendering $file, which links to $p");
624                                                 render($file);
625                                                 $rendered{$file}=1;
626                                                 next FILE;
627                                         }
628                                 }
629                         }
630                 }
631         }
632
633         # handle backlinks; if a page has added/removed links, update the
634         # pages it links to
635         # TODO: inefficient; pages may get rendered above and again here;
636         # problem is the backlinks could be wrong in the first pass render
637         # above
638         if (%rendered) {
639                 my %linkchanged;
640                 foreach my $file (keys %rendered, @del) {
641                         my $page=pagename($file);
642                         if (exists $links{$page}) {
643                                 foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
644                                         if (length $link &&
645                                             ! exists $oldlinks{$page} ||
646                                             ! grep { $_ eq $link } @{$oldlinks{$page}}) {
647                                                 $linkchanged{$link}=1;
648                                         }
649                                 }
650                         }
651                         if (exists $oldlinks{$page}) {
652                                 foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
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(" ", @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 $best_loc;
1026                         my ($from)=$form->param('from')=~/$config{wiki_file_regexp}/;
1027                         if (! defined $from || ! length $from ||
1028                             $from ne $form->param('from') ||
1029                             $from=~/$config{wiki_file_prune_regexp}/ || $from=~/^\//) {
1030                                 @page_locs=$best_loc=$page;
1031                         }
1032                         else {
1033                                 my $dir=$from."/";
1034                                 $dir=~s![^/]+/$!!;
1035                                 push @page_locs, $dir.$page;
1036                                 push @page_locs, "$from/$page";
1037                                 $best_loc="$from/$page";
1038                                 while (length $dir) {
1039                                         $dir=~s![^/]+/$!!;
1040                                         push @page_locs, $dir.$page;
1041                                 }
1042
1043                                 @page_locs = grep { ! exists
1044                                         $pagesources{lc($_)} } @page_locs;
1045                         }
1046
1047                         $form->tmpl_param("page_select", 1);
1048                         $form->field(name => "page", type => 'select',
1049                                 options => \@page_locs, value => $best_loc);
1050                         $form->title("creating $page");
1051                 }
1052                 elsif ($form->field("do") eq "edit") {
1053                         my $content="";
1054                         if (exists $pagesources{lc($page)}) {
1055                                 $content=readfile("$config{srcdir}/$pagesources{lc($page)}");
1056                                 $content=~s/\n/\r\n/g;
1057                         }
1058                         $form->tmpl_param("page_select", 0);
1059                         $form->field(name => "content", value => $content,
1060                                 force => 1);
1061                         $form->field(name => "page", type => 'hidden');
1062                         $form->title("editing $page");
1063                 }
1064                 
1065                 $form->tmpl_param("can_commit", $config{svn});
1066                 $form->tmpl_param("indexlink", indexlink());
1067                 print $form->render(submit => ["Save Page", "Cancel"]);
1068         }
1069         else {
1070                 # save page
1071                 my $file=$page.$config{default_pageext};
1072                 my $newfile=1;
1073                 if (exists $pagesources{lc($page)}) {
1074                         $file=$pagesources{lc($page)};
1075                         $newfile=0;
1076                 }
1077                 
1078                 my $content=$form->field('content');
1079                 $content=~s/\r\n/\n/g;
1080                 $content=~s/\r/\n/g;
1081                 writefile("$config{srcdir}/$file", $content);
1082                 
1083                 my $message="web commit ";
1084                 if ($session->param("name")) {
1085                         $message.="by ".$session->param("name");
1086                 }
1087                 else {
1088                         $message.="from $ENV{REMOTE_ADDR}";
1089                 }
1090                 if (defined $form->field('comments') &&
1091                     length $form->field('comments')) {
1092                         $message.=": ".$form->field('comments');
1093                 }
1094                 
1095                 if ($config{svn}) {
1096                         if ($newfile) {
1097                                 rcs_add($file);
1098                         }
1099                         # presumably the commit will trigger an update
1100                         # of the wiki
1101                         rcs_commit($message);
1102                 }
1103                 else {
1104                         loadindex();
1105                         refresh();
1106                         saveindex();
1107                 }
1108                 
1109                 # The trailing question mark tries to avoid broken
1110                 # caches and get the most recent version of the page.
1111                 print $q->redirect("$config{url}/".htmlpage($page)."?updated");
1112         }
1113 } #}}}
1114
1115 sub cgi () { #{{{
1116         eval q{use CGI};
1117         eval q{use CGI::Session};
1118         
1119         my $q=CGI->new;
1120         
1121         my $do=$q->param('do');
1122         if (! defined $do || ! length $do) {
1123                 error("\"do\" parameter missing");
1124         }
1125         
1126         # This does not need a session.
1127         if ($do eq 'recentchanges') {
1128                 cgi_recentchanges($q);
1129                 return;
1130         }
1131         
1132         CGI::Session->name("ikiwiki_session");
1133
1134         my $oldmask=umask(077);
1135         my $session = CGI::Session->new("driver:db_file", $q,
1136                 { FileName => "$config{srcdir}/.ikiwiki/sessions.db" });
1137         umask($oldmask);
1138         
1139         # Everything below this point needs the user to be signed in.
1140         if ((! $config{anonok} && ! defined $session->param("name") ||
1141                 ! userinfo_get($session->param("name"), "regdate")) || $do eq 'signin') {
1142                 cgi_signin($q, $session);
1143         
1144                 # Force session flush with safe umask.
1145                 my $oldmask=umask(077);
1146                 $session->flush;
1147                 umask($oldmask);
1148                 
1149                 return;
1150         }
1151         
1152         if ($do eq 'create' || $do eq 'edit') {
1153                 cgi_editpage($q, $session);
1154         }
1155         else {
1156                 error("unknown do parameter");
1157         }
1158 } #}}}
1159
1160 sub setup () { # {{{
1161         my $setup=possibly_foolish_untaint($config{setup});
1162         delete $config{setup};
1163         open (IN, $setup) || error("read $setup: $!\n");
1164         local $/=undef;
1165         my $code=<IN>;
1166         ($code)=$code=~/(.*)/s;
1167         close IN;
1168
1169         eval $code;
1170         error($@) if $@;
1171         exit;
1172 } #}}}
1173
1174 # main {{{
1175 setup() if $config{setup};
1176 if ($config{wrapper}) {
1177         gen_wrapper(%config);
1178         exit;
1179 }
1180 memoize('pagename');
1181 memoize('bestlink');
1182 loadindex() unless $config{rebuild};
1183 if ($config{cgi}) {
1184         cgi();
1185 }
1186 else {
1187         rcs_update() if $config{svn};
1188         refresh();
1189         saveindex();
1190 }
1191 #}}}