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