stupid mistakes
[ikiwiki.git] / 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 $page=shift;
251
252         $content =~ s{(\\?)$config{wiki_link_regexp}}{
253                 $1 ? "[[$2]]" : htmllink($page, $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, $page);
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 lockwiki () { #{{{
405         # Take an exclusive lock on the wiki to prevent multiple concurrent
406         # run issues. The lock will be dropped on program exit.
407         if (! -d "$config{srcdir}/.ikiwiki") {
408                 mkdir("$config{srcdir}/.ikiwiki");
409         }
410         open(WIKILOCK, ">$config{srcdir}/.ikiwiki/lockfile") || error ("cannot write to lockfile: $!");
411         if (! flock(WIKILOCK, 2 | 4)) {
412                 debug("wiki seems to be locked, waiting for lock");
413                 my $wait=600; # arbitrary, but don't hang forever to 
414                               # prevent process pileup
415                 for (1..600) {
416                         return if flock(WIKILOCK, 2 | 4);
417                         sleep 1;
418                 }
419                 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
420         }
421 } #}}}
422
423 sub unlockwiki () { #{{{
424         close WIKILOCK;
425 } #}}}
426
427 sub loadindex () { #{{{
428         open (IN, "$config{srcdir}/.ikiwiki/index") || return;
429         while (<IN>) {
430                 $_=possibly_foolish_untaint($_);
431                 chomp;
432                 my ($mtime, $file, $rendered, @links)=split(' ', $_);
433                 my $page=pagename($file);
434                 $pagesources{$page}=$file;
435                 $oldpagemtime{$page}=$mtime;
436                 $oldlinks{$page}=[@links];
437                 $links{$page}=[@links];
438                 $renderedfiles{$page}=$rendered;
439         }
440         close IN;
441 } #}}}
442
443 sub saveindex () { #{{{
444         if (! -d "$config{srcdir}/.ikiwiki") {
445                 mkdir("$config{srcdir}/.ikiwiki");
446         }
447         open (OUT, ">$config{srcdir}/.ikiwiki/index") || error("cannot write to index: $!");
448         foreach my $page (keys %oldpagemtime) {
449                 print OUT "$oldpagemtime{$page} $pagesources{$page} $renderedfiles{$page} ".
450                         join(" ", @{$links{$page}})."\n"
451                                 if $oldpagemtime{$page};
452         }
453         close OUT;
454 } #}}}
455
456 sub rcs_update () { #{{{
457         if (-d "$config{srcdir}/.svn") {
458                 if (system("svn", "update", "--quiet", $config{srcdir}) != 0) {
459                         warn("svn update failed\n");
460                 }
461         }
462 } #}}}
463
464 sub rcs_commit ($$) { #{{{
465         # Tries to commit the page; returns undef on _success_ and
466         # a version of the page with the rcs's conflict markers on failure.
467         # The file is relative to the srcdir.
468         my $file=shift;
469         my $message=shift;
470
471         if (-d "$config{srcdir}/.svn") {
472                 # svn up to let svn merge in other changes
473                 if (system("svn", "update", "-quiet", "$config{srcdir}/$file") != 0) {
474                         warn("svn update failed\n");
475                 }
476                 if (system("svn", "commit", "--quiet", "-m",
477                            possibly_foolish_untaint($message),
478                            "$config{srcdir}/$file") != 0) {
479                         warn("svn commit failed\n");
480                         my $conflict=readfile("$config{srcdir}/$file");
481                         if (system("svn", "revert", "--quiet", "$config{srcdir}/$file") != 0) {
482                                 warn("svn revert failed\n");
483                         }
484                         return $conflict;
485                 }
486         }
487         return undef # success
488 } #}}}
489
490 sub rcs_add ($) { #{{{
491         # filename is relative to the root of the srcdir
492         my $file=shift;
493
494         if (-d "$config{srcdir}/.svn") {
495                 my $parent=dirname($file);
496                 while (! -d "$config{srcdir}/$parent/.svn") {
497                         $file=$parent;
498                         $parent=dirname($file);
499                 }
500                 
501                 if (system("svn", "add", "--quiet", "$config{srcdir}/$file") != 0) {
502                         warn("svn add failed\n");
503                 }
504         }
505 } #}}}
506
507 sub rcs_recentchanges ($) { #{{{
508         my $num=shift;
509         my @ret;
510         
511         eval q{use CGI 'escapeHTML'};
512         eval q{use Date::Parse};
513         eval q{use Time::Duration};
514         
515         if (-d "$config{srcdir}/.svn") {
516                 my $info=`LANG=C svn info $config{srcdir}`;
517                 my ($svn_url)=$info=~/^URL: (.*)$/m;
518
519                 # FIXME: currently assumes that the wiki is somewhere
520                 # under trunk in svn, doesn't support other layouts.
521                 my ($svn_base)=$svn_url=~m!(/trunk(?:/.*)?)$!;
522                 
523                 my $div=qr/^--------------------+$/;
524                 my $infoline=qr/^r(\d+)\s+\|\s+([^\s]+)\s+\|\s+(\d+-\d+-\d+\s+\d+:\d+:\d+\s+[-+]?\d+).*/;
525                 my $state='start';
526                 my ($rev, $user, $when, @pages, @message);
527                 foreach (`LANG=C svn log --limit $num -v '$svn_url'`) {
528                         chomp;
529                         if ($state eq 'start' && /$div/) {
530                                 $state='header';
531                         }
532                         elsif ($state eq 'header' && /$infoline/) {
533                                 $rev=$1;
534                                 $user=$2;
535                                 $when=concise(ago(time - str2time($3)));
536                         }
537                         elsif ($state eq 'header' && /^\s+[A-Z]\s+\Q$svn_base\E\/(.+)$/) {
538                                 push @pages, { link => htmllink("", pagename($1), 1) }
539                                         if length $1;
540                         }
541                         elsif ($state eq 'header' && /^$/) {
542                                 $state='body';
543                         }
544                         elsif ($state eq 'body' && /$div/) {
545                                 my $committype="web";
546                                 if (defined $message[0] &&
547                                     $message[0]->{line}=~/^web commit by (\w+):?(.*)/) {
548                                         $user="$1";
549                                         $message[0]->{line}=$2;
550                                 }
551                                 else {
552                                         $committype="svn";
553                                 }
554                                 
555                                 push @ret, { rev => $rev,
556                                         user => htmllink("", $user, 1),
557                                         committype => $committype,
558                                         when => $when, message => [@message],
559                                         pages => [@pages] } if @pages;
560                                 return @ret if @ret >= $num;
561                                 
562                                 $state='header';
563                                 $rev=$user=$when=undef;
564                                 @pages=@message=();
565                         }
566                         elsif ($state eq 'body') {
567                                 push @message, {line => escapeHTML($_)},
568                         }
569                 }
570         }
571
572         return @ret;
573 } #}}}
574
575 sub prune ($) { #{{{
576         my $file=shift;
577
578         unlink($file);
579         my $dir=dirname($file);
580         while (rmdir($dir)) {
581                 $dir=dirname($dir);
582         }
583 } #}}}
584
585 sub refresh () { #{{{
586         # find existing pages
587         my %exists;
588         my @files;
589         eval q{use File::Find};
590         find({
591                 no_chdir => 1,
592                 wanted => sub {
593                         if (/$config{wiki_file_prune_regexp}/) {
594                                 no warnings 'once';
595                                 $File::Find::prune=1;
596                                 use warnings "all";
597                         }
598                         elsif (! -d $_ && ! -l $_) {
599                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
600                                 if (! defined $f) {
601                                         warn("skipping bad filename $_\n");
602                                 }
603                                 else {
604                                         $f=~s/^\Q$config{srcdir}\E\/?//;
605                                         push @files, $f;
606                                         $exists{pagename($f)}=1;
607                                 }
608                         }
609                 },
610         }, $config{srcdir});
611
612         my %rendered;
613
614         # check for added or removed pages
615         my @add;
616         foreach my $file (@files) {
617                 my $page=pagename($file);
618                 if (! $oldpagemtime{$page}) {
619                         debug("new page $page");
620                         push @add, $file;
621                         $links{$page}=[];
622                         $pagesources{$page}=$file;
623                 }
624         }
625         my @del;
626         foreach my $page (keys %oldpagemtime) {
627                 if (! $exists{$page}) {
628                         debug("removing old page $page");
629                         push @del, $pagesources{$page};
630                         prune($config{destdir}."/".$renderedfiles{$page});
631                         delete $renderedfiles{$page};
632                         $oldpagemtime{$page}=0;
633                         delete $pagesources{$page};
634                 }
635         }
636         
637         # render any updated files
638         foreach my $file (@files) {
639                 my $page=pagename($file);
640                 
641                 if (! exists $oldpagemtime{$page} ||
642                     mtime("$config{srcdir}/$file") > $oldpagemtime{$page}) {
643                         debug("rendering changed file $file");
644                         render($file);
645                         $rendered{$file}=1;
646                 }
647         }
648         
649         # if any files were added or removed, check to see if each page
650         # needs an update due to linking to them
651         # TODO: inefficient; pages may get rendered above and again here;
652         # problem is the bestlink may have changed and we won't know until
653         # now
654         if (@add || @del) {
655 FILE:           foreach my $file (@files) {
656                         my $page=pagename($file);
657                         foreach my $f (@add, @del) {
658                                 my $p=pagename($f);
659                                 foreach my $link (@{$links{$page}}) {
660                                         if (bestlink($page, $link) eq $p) {
661                                                 debug("rendering $file, which links to $p");
662                                                 render($file);
663                                                 $rendered{$file}=1;
664                                                 next FILE;
665                                         }
666                                 }
667                         }
668                 }
669         }
670
671         # handle backlinks; if a page has added/removed links, update the
672         # pages it links to
673         # TODO: inefficient; pages may get rendered above and again here;
674         # problem is the backlinks could be wrong in the first pass render
675         # above
676         if (%rendered) {
677                 my %linkchanged;
678                 foreach my $file (keys %rendered, @del) {
679                         my $page=pagename($file);
680                         if (exists $links{$page}) {
681                                 foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
682                                         if (length $link &&
683                                             ! exists $oldlinks{$page} ||
684                                             ! grep { $_ eq $link } @{$oldlinks{$page}}) {
685                                                 $linkchanged{$link}=1;
686                                         }
687                                 }
688                         }
689                         if (exists $oldlinks{$page}) {
690                                 foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
691                                         if (length $link &&
692                                             ! exists $links{$page} ||
693                                             ! grep { $_ eq $link } @{$links{$page}}) {
694                                                 $linkchanged{$link}=1;
695                                         }
696                                 }
697                         }
698                 }
699                 foreach my $link (keys %linkchanged) {
700                         my $linkfile=$pagesources{$link};
701                         if (defined $linkfile) {
702                                 debug("rendering $linkfile, to update its backlinks");
703                                 render($linkfile);
704                         }
705                 }
706         }
707 } #}}}
708
709 sub gen_wrapper (@) { #{{{
710         my %config=(@_);
711         eval q{use Cwd 'abs_path'};
712         $config{srcdir}=abs_path($config{srcdir});
713         $config{destdir}=abs_path($config{destdir});
714         my $this=abs_path($0);
715         if (! -x $this) {
716                 error("$this doesn't seem to be executable");
717         }
718
719         if ($config{setup}) {
720                 error("cannot create a wrapper that uses a setup file");
721         }
722         
723         my @params=($config{srcdir}, $config{templatedir}, $config{destdir},
724                 "--wikiname=$config{wikiname}");
725         push @params, "--verbose" if $config{verbose};
726         push @params, "--rebuild" if $config{rebuild};
727         push @params, "--nosvn" if !$config{svn};
728         push @params, "--cgi" if $config{cgi};
729         push @params, "--url=$config{url}" if length $config{url};
730         push @params, "--cgiurl=$config{cgiurl}" if length $config{cgiurl};
731         push @params, "--historyurl=$config{historyurl}" if length $config{historyurl};
732         push @params, "--anonok" if $config{anonok};
733         my $params=join(" ", @params);
734         my $call='';
735         foreach my $p ($this, $this, @params) {
736                 $call.=qq{"$p", };
737         }
738         $call.="NULL";
739         
740         my @envsave;
741         push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
742                        CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
743                        HTTP_COOKIE} if $config{cgi};
744         my $envsave="";
745         foreach my $var (@envsave) {
746                 $envsave.=<<"EOF"
747         if ((s=getenv("$var")))
748                 asprintf(&newenviron[i++], "%s=%s", "$var", s);
749 EOF
750         }
751         
752         open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
753         print OUT <<"EOF";
754 /* A wrapper for ikiwiki, can be safely made suid. */
755 #define _GNU_SOURCE
756 #include <stdio.h>
757 #include <unistd.h>
758 #include <stdlib.h>
759 #include <string.h>
760
761 extern char **environ;
762
763 int main (int argc, char **argv) {
764         /* Sanitize environment. */
765         char *s;
766         char *newenviron[$#envsave+3];
767         int i=0;
768 $envsave
769         newenviron[i++]="HOME=$ENV{HOME}";
770         newenviron[i]=NULL;
771         environ=newenviron;
772
773         if (argc == 2 && strcmp(argv[1], "--params") == 0) {
774                 printf("$params\\n");
775                 exit(0);
776         }
777         
778         execl($call);
779         perror("failed to run $this");
780         exit(1);
781 }
782 EOF
783         close OUT;
784         if (system("gcc", "ikiwiki-wrap.c", "-o", possibly_foolish_untaint($config{wrapper})) != 0) {
785                 error("failed to compile ikiwiki-wrap.c");
786         }
787         unlink("ikiwiki-wrap.c");
788         if (defined $config{wrappermode} &&
789             ! chmod(oct($config{wrappermode}), possibly_foolish_untaint($config{wrapper}))) {
790                 error("chmod $config{wrapper}: $!");
791         }
792         print "successfully generated $config{wrapper}\n";
793 } #}}}
794                 
795 sub misctemplate ($$) { #{{{
796         my $title=shift;
797         my $pagebody=shift;
798         
799         my $template=HTML::Template->new(
800                 filename => "$config{templatedir}/misc.tmpl"
801         );
802         $template->param(
803                 title => $title,
804                 indexlink => indexlink(),
805                 wikiname => $config{wikiname},
806                 pagebody => $pagebody,
807         );
808         return $template->output;
809 }#}}}
810
811 sub cgi_recentchanges ($) { #{{{
812         my $q=shift;
813         
814         my $template=HTML::Template->new(
815                 filename => "$config{templatedir}/recentchanges.tmpl"
816         );
817         $template->param(
818                 title => "RecentChanges",
819                 indexlink => indexlink(),
820                 wikiname => $config{wikiname},
821                 changelog => [rcs_recentchanges(100)],
822         );
823         print $q->header, $template->output;
824 } #}}}
825
826 sub userinfo_get ($$) { #{{{
827         my $user=shift;
828         my $field=shift;
829
830         eval q{use Storable};
831         my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
832         if (! defined $userdata || ! ref $userdata || 
833             ! exists $userdata->{$user} || ! ref $userdata->{$user}) {
834                 return "";
835         }
836         return $userdata->{$user}->{$field};
837 } #}}}
838
839 sub userinfo_set ($$) { #{{{
840         my $user=shift;
841         my $info=shift;
842         
843         eval q{use Storable};
844         my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
845         if (! defined $userdata || ! ref $userdata) {
846                 $userdata={};
847         }
848         $userdata->{$user}=$info;
849         my $oldmask=umask(077);
850         my $ret=Storable::lock_store($userdata, "$config{srcdir}/.ikiwiki/userdb");
851         umask($oldmask);
852         return $ret;
853 } #}}}
854
855 sub cgi_signin ($$) { #{{{
856         my $q=shift;
857         my $session=shift;
858
859         eval q{use CGI::FormBuilder};
860         my $form = CGI::FormBuilder->new(
861                 title => "$config{wikiname} signin",
862                 fields => [qw(do page from name password confirm_password email)],
863                 header => 1,
864                 method => 'POST',
865                 validate => {
866                         confirm_password => {
867                                 perl => q{eq $form->field("password")},
868                         },
869                         email => 'EMAIL',
870                 },
871                 required => 'NONE',
872                 javascript => 0,
873                 params => $q,
874                 action => $q->request_uri,
875                 header => 0,
876                 template => (-e "$config{templatedir}/signin.tmpl" ?
877                               "$config{templatedir}/signin.tmpl" : "")
878         );
879         
880         $form->field(name => "name", required => 0);
881         $form->field(name => "do", type => "hidden");
882         $form->field(name => "page", type => "hidden");
883         $form->field(name => "from", type => "hidden");
884         $form->field(name => "password", type => "password", required => 0);
885         $form->field(name => "confirm_password", type => "password", required => 0);
886         $form->field(name => "email", required => 0);
887         if ($q->param("do") ne "signin") {
888                 $form->text("You need to log in before you can edit pages.");
889         }
890         
891         if ($form->submitted) {
892                 # Set required fields based on how form was submitted.
893                 my %required=(
894                         "Login" => [qw(name password)],
895                         "Register" => [qw(name password confirm_password email)],
896                         "Mail Password" => [qw(name)],
897                 );
898                 foreach my $opt (@{$required{$form->submitted}}) {
899                         $form->field(name => $opt, required => 1);
900                 }
901         
902                 # Validate password differently depending on how
903                 # form was submitted.
904                 if ($form->submitted eq 'Login') {
905                         $form->field(
906                                 name => "password",
907                                 validate => sub {
908                                         length $form->field("name") &&
909                                         shift eq userinfo_get($form->field("name"), 'password');
910                                 },
911                         );
912                         $form->field(name => "name", validate => '/^\w+$/');
913                 }
914                 else {
915                         $form->field(name => "password", validate => 'VALUE');
916                 }
917                 # And make sure the entered name exists when logging
918                 # in or sending email, and does not when registering.
919                 if ($form->submitted eq 'Register') {
920                         $form->field(
921                                 name => "name",
922                                 validate => sub {
923                                         my $name=shift;
924                                         length $name &&
925                                         ! userinfo_get($name, "regdate");
926                                 },
927                         );
928                 }
929                 else {
930                         $form->field(
931                                 name => "name",
932                                 validate => sub {
933                                         my $name=shift;
934                                         length $name &&
935                                         userinfo_get($name, "regdate");
936                                 },
937                         );
938                 }
939         }
940         else {
941                 # First time settings.
942                 $form->field(name => "name", comment => "use FirstnameLastName");
943                 $form->field(name => "confirm_password", comment => "(only needed");
944                 $form->field(name => "email",            comment => "for registration)");
945                 if ($session->param("name")) {
946                         $form->field(name => "name", value => $session->param("name"));
947                 }
948         }
949
950         if ($form->submitted && $form->validate) {
951                 if ($form->submitted eq 'Login') {
952                         $session->param("name", $form->field("name"));
953                         if (defined $form->field("do") && 
954                             $form->field("do") ne 'signin') {
955                                 print $q->redirect(
956                                         "$config{cgiurl}?do=".$form->field("do").
957                                         "&page=".$form->field("page").
958                                         "&from=".$form->field("from"));;
959                         }
960                         else {
961                                 print $q->redirect($config{url});
962                         }
963                 }
964                 elsif ($form->submitted eq 'Register') {
965                         my $user_name=$form->field('name');
966                         if (userinfo_set($user_name, {
967                                            'email' => $form->field('email'),
968                                            'password' => $form->field('password'),
969                                            'regdate' => time
970                                          })) {
971                                 $form->field(name => "confirm_password", type => "hidden");
972                                 $form->field(name => "email", type => "hidden");
973                                 $form->text("Registration successful. Now you can Login.");
974                                 print $session->header();
975                                 print misctemplate($form->title, $form->render(submit => ["Login"]));
976                         }
977                         else {
978                                 error("Error saving registration.");
979                         }
980                 }
981                 elsif ($form->submitted eq 'Mail Password') {
982                         my $user_name=$form->field("name");
983                         my $template=HTML::Template->new(
984                                 filename => "$config{templatedir}/passwordmail.tmpl"
985                         );
986                         $template->param(
987                                 user_name => $user_name,
988                                 user_password => userinfo_get($user_name, "password"),
989                                 wikiurl => $config{url},
990                                 wikiname => $config{wikiname},
991                                 REMOTE_ADDR => $ENV{REMOTE_ADDR},
992                         );
993                         
994                         eval q{use Mail::Sendmail};
995                         my ($fromhost) = $config{cgiurl} =~ m!/([^/]+)!;
996                         sendmail(
997                                 To => userinfo_get($user_name, "email"),
998                                 From => "$config{wikiname} admin <".(getpwuid($>))[0]."@".$fromhost.">",
999                                 Subject => "$config{wikiname} information",
1000                                 Message => $template->output,
1001                         ) or error("Failed to send mail");
1002                         
1003                         $form->text("Your password has been emailed to you.");
1004                         $form->field(name => "name", required => 0);
1005                         print $session->header();
1006                         print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
1007                 }
1008         }
1009         else {
1010                 print $session->header();
1011                 print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
1012         }
1013 } #}}}
1014
1015 sub cgi_editpage ($$) { #{{{
1016         my $q=shift;
1017         my $session=shift;
1018
1019         eval q{use CGI::FormBuilder};
1020         my $form = CGI::FormBuilder->new(
1021                 fields => [qw(do from page content comments)],
1022                 header => 1,
1023                 method => 'POST',
1024                 validate => {
1025                         content => '/.+/',
1026                 },
1027                 required => [qw{content}],
1028                 javascript => 0,
1029                 params => $q,
1030                 action => $q->request_uri,
1031                 table => 0,
1032                 template => "$config{templatedir}/editpage.tmpl"
1033         );
1034         my @buttons=("Save Page", "Preview", "Cancel");
1035         
1036         my ($page)=$form->param('page')=~/$config{wiki_file_regexp}/;
1037         if (! defined $page || ! length $page || $page ne $q->param('page') ||
1038             $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
1039                 error("bad page name");
1040         }
1041         $page=lc($page);
1042
1043         $form->field(name => "do", type => 'hidden');
1044         $form->field(name => "from", type => 'hidden');
1045         $form->field(name => "page", value => "$page", force => 1);
1046         $form->field(name => "comments", type => "text", size => 80);
1047         $form->field(name => "content", type => "textarea", rows => 20,
1048                 cols => 80);
1049         
1050         if ($form->submitted eq "Cancel") {
1051                 print $q->redirect("$config{url}/".htmlpage($page));
1052                 return;
1053         }
1054         elsif ($form->submitted eq "Preview") {
1055                 $form->tmpl_param("page_preview",
1056                         htmlize($config{default_pageext},
1057                                 linkify($form->field('content'), $page)));
1058         }
1059         else {
1060                 $form->tmpl_param("page_preview", "");
1061         }
1062         $form->tmpl_param("page_conflict", "");
1063         
1064         if (! $form->submitted || $form->submitted eq "Preview" || 
1065             ! $form->validate) {
1066                 if ($form->field("do") eq "create") {
1067                         if (exists $pagesources{lc($page)}) {
1068                                 # hmm, someone else made the page in the
1069                                 # meantime?
1070                                 print $q->redirect("$config{url}/".htmlpage($page));
1071                                 return;
1072                         }
1073                         
1074                         my @page_locs;
1075                         my $best_loc;
1076                         my ($from)=$form->param('from')=~/$config{wiki_file_regexp}/;
1077                         if (! defined $from || ! length $from ||
1078                             $from ne $form->param('from') ||
1079                             $from=~/$config{wiki_file_prune_regexp}/ || $from=~/^\//) {
1080                                 @page_locs=$best_loc=$page;
1081                         }
1082                         else {
1083                                 my $dir=$from."/";
1084                                 $dir=~s![^/]+/$!!;
1085                                 push @page_locs, $dir.$page;
1086                                 push @page_locs, "$from/$page";
1087                                 $best_loc="$from/$page";
1088                                 while (length $dir) {
1089                                         $dir=~s![^/]+/$!!;
1090                                         push @page_locs, $dir.$page;
1091                                 }
1092
1093                                 @page_locs = grep { ! exists
1094                                         $pagesources{lc($_)} } @page_locs;
1095                         }
1096
1097                         $form->tmpl_param("page_select", 1);
1098                         $form->field(name => "page", type => 'select',
1099                                 options => \@page_locs, value => $best_loc);
1100                         $form->title("creating $page");
1101                 }
1102                 elsif ($form->field("do") eq "edit") {
1103                         if (! length $form->field('content')) {
1104                                 my $content="";
1105                                 if (exists $pagesources{lc($page)}) {
1106                                                 $content=readfile("$config{srcdir}/$pagesources{lc($page)}");
1107                                         $content=~s/\n/\r\n/g;
1108                                 }
1109                                 $form->field(name => "content", value => $content,
1110                                         force => 1);
1111                         }
1112                         $form->tmpl_param("page_select", 0);
1113                         $form->field(name => "page", type => 'hidden');
1114                         $form->title("editing $page");
1115                 }
1116                 
1117                 $form->tmpl_param("can_commit", $config{svn});
1118                 $form->tmpl_param("indexlink", indexlink());
1119                 print $form->render(submit => \@buttons);
1120         }
1121         else {
1122                 # save page
1123                 my $file=$page.$config{default_pageext};
1124                 my $newfile=1;
1125                 if (exists $pagesources{lc($page)}) {
1126                         $file=$pagesources{lc($page)};
1127                         $newfile=0;
1128                 }
1129                 
1130                 my $content=$form->field('content');
1131                 $content=~s/\r\n/\n/g;
1132                 $content=~s/\r/\n/g;
1133                 writefile("$config{srcdir}/$file", $content);
1134                 
1135                 my $message="web commit ";
1136                 if ($session->param("name")) {
1137                         $message.="by ".$session->param("name");
1138                 }
1139                 else {
1140                         $message.="from $ENV{REMOTE_ADDR}";
1141                 }
1142                 if (defined $form->field('comments') &&
1143                     length $form->field('comments')) {
1144                         $message.=": ".$form->field('comments');
1145                 }
1146                 
1147                 if ($config{svn}) {
1148                         if ($newfile) {
1149                                 rcs_add($file);
1150                         }
1151                         # prevent deadlock with post-commit hook
1152                         unlockwiki();
1153                         # presumably the commit will trigger an update
1154                         # of the wiki
1155                         my $conflict=rcs_commit($file, $message);
1156                 
1157                         if (defined $conflict) {
1158                                 $form->tmpl_param("page_conflict", 1);
1159                                 $form->field("content", $conflict);
1160                                 $form->field("do", "edit)");
1161                                 print $form->render(submit => \@buttons);
1162                                 return;
1163                         }
1164                 }
1165                 else {
1166                         loadindex();
1167                         refresh();
1168                         saveindex();
1169                 }
1170                 
1171                 # The trailing question mark tries to avoid broken
1172                 # caches and get the most recent version of the page.
1173                 print $q->redirect("$config{url}/".htmlpage($page)."?updated");
1174         }
1175 } #}}}
1176
1177 sub cgi () { #{{{
1178         eval q{use CGI};
1179         eval q{use CGI::Session};
1180         
1181         my $q=CGI->new;
1182         
1183         my $do=$q->param('do');
1184         if (! defined $do || ! length $do) {
1185                 error("\"do\" parameter missing");
1186         }
1187         
1188         # This does not need a session.
1189         if ($do eq 'recentchanges') {
1190                 cgi_recentchanges($q);
1191                 return;
1192         }
1193         
1194         CGI::Session->name("ikiwiki_session");
1195
1196         my $oldmask=umask(077);
1197         my $session = CGI::Session->new("driver:db_file", $q,
1198                 { FileName => "$config{srcdir}/.ikiwiki/sessions.db" });
1199         umask($oldmask);
1200         
1201         # Everything below this point needs the user to be signed in.
1202         if ((! $config{anonok} && ! defined $session->param("name") ||
1203                 ! userinfo_get($session->param("name"), "regdate")) || $do eq 'signin') {
1204                 cgi_signin($q, $session);
1205         
1206                 # Force session flush with safe umask.
1207                 my $oldmask=umask(077);
1208                 $session->flush;
1209                 umask($oldmask);
1210                 
1211                 return;
1212         }
1213         
1214         if ($do eq 'create' || $do eq 'edit') {
1215                 cgi_editpage($q, $session);
1216         }
1217         else {
1218                 error("unknown do parameter");
1219         }
1220 } #}}}
1221
1222 sub setup () { # {{{
1223         my $setup=possibly_foolish_untaint($config{setup});
1224         delete $config{setup};
1225         open (IN, $setup) || error("read $setup: $!\n");
1226         local $/=undef;
1227         my $code=<IN>;
1228         ($code)=$code=~/(.*)/s;
1229         close IN;
1230
1231         eval $code;
1232         error($@) if $@;
1233         exit;
1234 } #}}}
1235
1236 # main {{{
1237 lockwiki();
1238 setup() if $config{setup};
1239 if ($config{wrapper}) {
1240         gen_wrapper(%config);
1241         exit;
1242 }
1243 memoize('pagename');
1244 memoize('bestlink');
1245 loadindex() unless $config{rebuild};
1246 if ($config{cgi}) {
1247         cgi();
1248 }
1249 else {
1250         rcs_update() if $config{svn};
1251         refresh();
1252         saveindex();
1253 }
1254 #}}}