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