]> sipb.mit.edu Git - ikiwiki.git/blob - ikiwiki
prefs page implemented
[ikiwiki.git] / ikiwiki
1 #!/usr/bin/perl -T
2 $ENV{PATH}="/usr/local/bin:/usr/bin:/bin";
3
4 use warnings;
5 use strict;
6 use Memoize;
7 use File::Spec;
8 use HTML::Template;
9 use Getopt::Long;
10
11 my (%links, %oldlinks, %oldpagemtime, %renderedfiles, %pagesources);
12
13 # Holds global config settings, also used by some modules.
14 our %config=( #{{{
15         wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.html?$)},
16         wiki_link_regexp => qr/\[\[([^\s\]]+)\]\]/,
17         wiki_file_regexp => qr/(^[-A-Za-z0-9_.:\/+]+$)/,
18         verbose => 0,
19         wikiname => "wiki",
20         default_pageext => ".mdwn",
21         cgi => 0,
22         svn => 1,
23         url => '',
24         cgiurl => '',
25         historyurl => '',
26         diffurl => '',
27         anonok => 0,
28         rebuild => 0,
29         wrapper => undef,
30         wrappermode => undef,
31         srcdir => undef,
32         destdir => undef,
33         templatedir => undef,
34         setup => undef,
35 ); #}}}
36
37 GetOptions( #{{{
38         "setup=s" => \$config{setup},
39         "wikiname=s" => \$config{wikiname},
40         "verbose|v!" => \$config{verbose},
41         "rebuild!" => \$config{rebuild},
42         "wrapper=s" => sub { $config{wrapper}=$_[1] ? $_[1] : "ikiwiki-wrap" },
43         "wrappermode=i" => \$config{wrappermode},
44         "svn!" => \$config{svn},
45         "anonok!" => \$config{anonok},
46         "cgi!" => \$config{cgi},
47         "url=s" => \$config{url},
48         "cgiurl=s" => \$config{cgiurl},
49         "historyurl=s" => \$config{historyurl},
50         "diffurl=s" => \$config{diffurl},
51         "exclude=s@" => sub {
52                 $config{wiki_file_prune_regexp}=qr/$config{wiki_file_prune_regexp}|$_[1]/;
53         },
54 ) || usage();
55
56 if (! $config{setup}) {
57         usage() unless @ARGV == 3;
58         $config{srcdir} = possibly_foolish_untaint(shift);
59         $config{templatedir} = possibly_foolish_untaint(shift);
60         $config{destdir} = possibly_foolish_untaint(shift);
61         if ($config{cgi} && ! length $config{url}) {
62                 error("Must specify url to wiki with --url when using --cgi");
63         }
64 }
65 #}}}
66
67 sub usage { #{{{
68         die "usage: ikiwiki [options] source templates dest\n";
69 } #}}}
70
71 sub error { #{{{
72         if ($config{cgi}) {
73                 print "Content-type: text/html\n\n";
74                 print misctemplate("Error", "<p>Error: @_</p>");
75         }
76         die @_;
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         my $page=shift;
174
175         my @links;
176         while ($content =~ /(?<!\\)$config{wiki_link_regexp}/g) {
177                 push @links, lc($1);
178         }
179         # Discussion links are a special case since they're not in the text
180         # of the page, but on its template.
181         return @links, "$page/discussion";
182 } #}}}
183
184 sub bestlink ($$) { #{{{
185         # Given a page and the text of a link on the page, determine which
186         # existing page that link best points to. Prefers pages under a
187         # subdirectory with the same name as the source page, failing that
188         # goes down the directory tree to the base looking for matching
189         # pages.
190         my $page=shift;
191         my $link=lc(shift);
192         
193         my $cwd=$page;
194         do {
195                 my $l=$cwd;
196                 $l.="/" if length $l;
197                 $l.=$link;
198
199                 if (exists $links{$l}) {
200                         #debug("for $page, \"$link\", use $l");
201                         return $l;
202                 }
203         } while $cwd=~s!/?[^/]+$!!;
204
205         #print STDERR "warning: page $page, broken link: $link\n";
206         return "";
207 } #}}}
208
209 sub isinlinableimage ($) { #{{{
210         my $file=shift;
211         
212         $file=~/\.(png|gif|jpg|jpeg)$/;
213 } #}}}
214
215 sub htmllink { #{{{
216         my $page=shift;
217         my $link=shift;
218         my $noimageinline=shift; # don't turn links into inline html images
219         my $forcesubpage=shift; # force a link to a subpage
220
221         my $bestlink;
222         if (! $forcesubpage) {
223                 $bestlink=bestlink($page, $link);
224         }
225         else {
226                 $bestlink="$page/".lc($link);
227         }
228
229         return $link if length $bestlink && $page eq $bestlink;
230         
231         # TODO BUG: %renderedfiles may not have it, if the linked to page
232         # was also added and isn't yet rendered! Note that this bug is
233         # masked by the bug mentioned below that makes all new files
234         # be rendered twice.
235         if (! grep { $_ eq $bestlink } values %renderedfiles) {
236                 $bestlink=htmlpage($bestlink);
237         }
238         if (! grep { $_ eq $bestlink } values %renderedfiles) {
239                 return "<a href=\"$config{cgiurl}?do=create&page=$link&from=$page\">?</a>$link"
240         }
241         
242         $bestlink=File::Spec->abs2rel($bestlink, dirname($page));
243         
244         if (! $noimageinline && isinlinableimage($bestlink)) {
245                 return "<img src=\"$bestlink\">";
246         }
247         return "<a href=\"$bestlink\">$link</a>";
248 } #}}}
249
250 sub linkify ($$) { #{{{
251         my $content=shift;
252         my $page=shift;
253
254         $content =~ s{(\\?)$config{wiki_link_regexp}}{
255                 $1 ? "[[$2]]" : htmllink($page, $2)
256         }eg;
257         
258         return $content;
259 } #}}}
260
261 sub htmlize ($$) { #{{{
262         my $type=shift;
263         my $content=shift;
264         
265         if (! $INC{"/usr/bin/markdown"}) {
266                 no warnings 'once';
267                 $blosxom::version="is a proper perl module too much to ask?";
268                 use warnings 'all';
269                 do "/usr/bin/markdown";
270         }
271         
272         if ($type eq '.mdwn') {
273                 return Markdown::Markdown($content);
274         }
275         else {
276                 error("htmlization of $type not supported");
277         }
278 } #}}}
279
280 sub backlinks ($) { #{{{
281         my $page=shift;
282
283         my @links;
284         foreach my $p (keys %links) {
285                 next if bestlink($page, $p) eq $page;
286                 if (grep { length $_ && bestlink($p, $_) eq $page } @{$links{$p}}) {
287                         my $href=File::Spec->abs2rel(htmlpage($p), dirname($page));
288                         
289                         # Trim common dir prefixes from both pages.
290                         my $p_trimmed=$p;
291                         my $page_trimmed=$page;
292                         my $dir;
293                         1 while (($dir)=$page_trimmed=~m!^([^/]+/)!) &&
294                                 defined $dir &&
295                                 $p_trimmed=~s/^\Q$dir\E// &&
296                                 $page_trimmed=~s/^\Q$dir\E//;
297                                        
298                         push @links, { url => $href, page => $p_trimmed };
299                 }
300         }
301
302         return sort { $a->{page} cmp $b->{page} } @links;
303 } #}}}
304         
305 sub parentlinks ($) { #{{{
306         my $page=shift;
307         
308         my @ret;
309         my $pagelink="";
310         my $path="";
311         my $skip=1;
312         foreach my $dir (reverse split("/", $page)) {
313                 if (! $skip) {
314                         $path.="../";
315                         unshift @ret, { url => "$path$dir.html", page => $dir };
316                 }
317                 else {
318                         $skip=0;
319                 }
320         }
321         unshift @ret, { url => length $path ? $path : ".", page => $config{wikiname} };
322         return @ret;
323 } #}}}
324
325 sub indexlink () { #{{{
326         return "<a href=\"$config{url}\">$config{wikiname}</a>";
327 } #}}}
328
329 sub finalize ($$$) { #{{{
330         my $content=shift;
331         my $page=shift;
332         my $mtime=shift;
333
334         my $title=basename($page);
335         $title=~s/_/ /g;
336         
337         my $template=HTML::Template->new(blind_cache => 1,
338                 filename => "$config{templatedir}/page.tmpl");
339         
340         if (length $config{cgiurl}) {
341                 $template->param(editurl => "$config{cgiurl}?do=edit&page=$page");
342                 $template->param(prefsurl => "$config{cgiurl}?do=prefs");
343                 if ($config{svn}) {
344                         $template->param(recentchangesurl => "$config{cgiurl}?do=recentchanges");
345                 }
346         }
347
348         if (length $config{historyurl}) {
349                 my $u=$config{historyurl};
350                 $u=~s/\[\[file\]\]/$pagesources{$page}/g;
351                 $template->param(historyurl => $u);
352         }
353         
354         $template->param(
355                 title => $title,
356                 wikiname => $config{wikiname},
357                 parentlinks => [parentlinks($page)],
358                 content => $content,
359                 backlinks => [backlinks($page)],
360                 discussionlink => htmllink($page, "Discussion", 1, 1),
361                 mtime => scalar(gmtime($mtime)),
362         );
363         
364         return $template->output;
365 } #}}}
366
367 sub check_overwrite ($$) { #{{{
368         # Important security check. Make sure to call this before saving
369         # any files to the source directory.
370         my $dest=shift;
371         my $src=shift;
372         
373         if (! exists $renderedfiles{$src} && -e $dest && ! $config{rebuild}) {
374                 error("$dest already exists and was rendered from ".
375                         join(" ",(grep { $renderedfiles{$_} eq $dest } keys
376                                 %renderedfiles)).
377                         ", before, so not rendering from $src");
378         }
379 } #}}}
380
381 sub render ($) { #{{{
382         my $file=shift;
383         
384         my $type=pagetype($file);
385         my $content=readfile("$config{srcdir}/$file");
386         if ($type ne 'unknown') {
387                 my $page=pagename($file);
388                 
389                 $links{$page}=[findlinks($content, $page)];
390                 
391                 $content=linkify($content, $page);
392                 $content=htmlize($type, $content);
393                 $content=finalize($content, $page,
394                         mtime("$config{srcdir}/$file"));
395                 
396                 check_overwrite("$config{destdir}/".htmlpage($page), $page);
397                 writefile("$config{destdir}/".htmlpage($page), $content);
398                 $oldpagemtime{$page}=time;
399                 $renderedfiles{$page}=htmlpage($page);
400         }
401         else {
402                 $links{$file}=[];
403                 check_overwrite("$config{destdir}/$file", $file);
404                 writefile("$config{destdir}/$file", $content);
405                 $oldpagemtime{$file}=time;
406                 $renderedfiles{$file}=$file;
407         }
408 } #}}}
409
410 sub lockwiki () { #{{{
411         # Take an exclusive lock on the wiki to prevent multiple concurrent
412         # run issues. The lock will be dropped on program exit.
413         if (! -d "$config{srcdir}/.ikiwiki") {
414                 mkdir("$config{srcdir}/.ikiwiki");
415         }
416         open(WIKILOCK, ">$config{srcdir}/.ikiwiki/lockfile") || error ("cannot write to lockfile: $!");
417         if (! flock(WIKILOCK, 2 | 4)) {
418                 debug("wiki seems to be locked, waiting for lock");
419                 my $wait=600; # arbitrary, but don't hang forever to 
420                               # prevent process pileup
421                 for (1..600) {
422                         return if flock(WIKILOCK, 2 | 4);
423                         sleep 1;
424                 }
425                 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
426         }
427 } #}}}
428
429 sub unlockwiki () { #{{{
430         close WIKILOCK;
431 } #}}}
432
433 sub loadindex () { #{{{
434         open (IN, "$config{srcdir}/.ikiwiki/index") || return;
435         while (<IN>) {
436                 $_=possibly_foolish_untaint($_);
437                 chomp;
438                 my ($mtime, $file, $rendered, @links)=split(' ', $_);
439                 my $page=pagename($file);
440                 $pagesources{$page}=$file;
441                 $oldpagemtime{$page}=$mtime;
442                 $oldlinks{$page}=[@links];
443                 $links{$page}=[@links];
444                 $renderedfiles{$page}=$rendered;
445         }
446         close IN;
447 } #}}}
448
449 sub saveindex () { #{{{
450         if (! -d "$config{srcdir}/.ikiwiki") {
451                 mkdir("$config{srcdir}/.ikiwiki");
452         }
453         open (OUT, ">$config{srcdir}/.ikiwiki/index") || error("cannot write to index: $!");
454         foreach my $page (keys %oldpagemtime) {
455                 print OUT "$oldpagemtime{$page} $pagesources{$page} $renderedfiles{$page} ".
456                         join(" ", @{$links{$page}})."\n"
457                                 if $oldpagemtime{$page};
458         }
459         close OUT;
460 } #}}}
461
462 sub rcs_update () { #{{{
463         if (-d "$config{srcdir}/.svn") {
464                 if (system("svn", "update", "--quiet", $config{srcdir}) != 0) {
465                         warn("svn update failed\n");
466                 }
467         }
468 } #}}}
469
470 sub rcs_prepedit ($) { #{{{
471         # Prepares to edit a file under revision control. Returns a token
472         # that must be passed into rcs_commit when the file is ready
473         # for committing.
474         # The file is relative to the srcdir.
475         my $file=shift;
476         
477         if (-d "$config{srcdir}/.svn") {
478                 # For subversion, return the revision of the file when
479                 # editing begins.
480                 my $rev=svn_info("Revision", "$config{srcdir}/$file");
481                 return defined $rev ? $rev : "";
482         }
483 } #}}}
484
485 sub rcs_commit ($$$) { #{{{
486         # Tries to commit the page; returns undef on _success_ and
487         # a version of the page with the rcs's conflict markers on failure.
488         # The file is relative to the srcdir.
489         my $file=shift;
490         my $message=shift;
491         my $rcstoken=shift;
492
493         if (-d "$config{srcdir}/.svn") {
494                 # Check to see if the page has been changed by someone
495                 # else since rcs_prepedit was called.
496                 my ($oldrev)=$rcstoken=~/^([0-9]+)$/; # untaint
497                 my $rev=svn_info("Revision", "$config{srcdir}/$file");
498                 if (defined $rev && defined $oldrev && $rev != $oldrev) {
499                         # Merge their changes into the file that we've
500                         # changed.
501                         chdir($config{srcdir}); # svn merge wants to be here
502                         if (system("svn", "merge", "--quiet", "-r$oldrev:$rev",
503                                    "$config{srcdir}/$file") != 0) {
504                                 warn("svn merge -r$oldrev:$rev failed\n");
505                         }
506                 }
507
508                 if (system("svn", "commit", "--quiet", "-m",
509                            possibly_foolish_untaint($message),
510                            "$config{srcdir}") != 0) {
511                         my $conflict=readfile("$config{srcdir}/$file");
512                         if (system("svn", "revert", "--quiet", "$config{srcdir}/$file") != 0) {
513                                 warn("svn revert failed\n");
514                         }
515                         return $conflict;
516                 }
517         }
518         return undef # success
519 } #}}}
520
521 sub rcs_add ($) { #{{{
522         # filename is relative to the root of the srcdir
523         my $file=shift;
524
525         if (-d "$config{srcdir}/.svn") {
526                 my $parent=dirname($file);
527                 while (! -d "$config{srcdir}/$parent/.svn") {
528                         $file=$parent;
529                         $parent=dirname($file);
530                 }
531                 
532                 if (system("svn", "add", "--quiet", "$config{srcdir}/$file") != 0) {
533                         warn("svn add failed\n");
534                 }
535         }
536 } #}}}
537
538 sub svn_info ($$) { #{{{
539         my $field=shift;
540         my $file=shift;
541
542         my $info=`LANG=C svn info $file`;
543         my ($ret)=$info=~/^$field: (.*)$/m;
544         return $ret;
545 } #}}}
546
547 sub rcs_recentchanges ($) { #{{{
548         my $num=shift;
549         my @ret;
550         
551         eval q{use CGI 'escapeHTML'};
552         eval q{use Date::Parse};
553         eval q{use Time::Duration};
554         
555         if (-d "$config{srcdir}/.svn") {
556                 my $svn_url=svn_info("URL", $config{srcdir});
557
558                 # FIXME: currently assumes that the wiki is somewhere
559                 # under trunk in svn, doesn't support other layouts.
560                 my ($svn_base)=$svn_url=~m!(/trunk(?:/.*)?)$!;
561                 
562                 my $div=qr/^--------------------+$/;
563                 my $infoline=qr/^r(\d+)\s+\|\s+([^\s]+)\s+\|\s+(\d+-\d+-\d+\s+\d+:\d+:\d+\s+[-+]?\d+).*/;
564                 my $state='start';
565                 my ($rev, $user, $when, @pages, @message);
566                 foreach (`LANG=C svn log --limit $num -v '$svn_url'`) {
567                         chomp;
568                         if ($state eq 'start' && /$div/) {
569                                 $state='header';
570                         }
571                         elsif ($state eq 'header' && /$infoline/) {
572                                 $rev=$1;
573                                 $user=$2;
574                                 $when=concise(ago(time - str2time($3)));
575                         }
576                         elsif ($state eq 'header' && /^\s+[A-Z]\s+\Q$svn_base\E\/([^ ]+)(?:$|\s)/) {
577                                 my $file=$1;
578                                 my $diffurl=$config{diffurl};
579                                 $diffurl=~s/\[\[file\]\]/$file/g;
580                                 $diffurl=~s/\[\[r1\]\]/$rev - 1/eg;
581                                 $diffurl=~s/\[\[r2\]\]/$rev/g;
582                                 push @pages, {
583                                         link => htmllink("", pagename($file), 1),
584                                         diffurl => $diffurl,
585                                 } if length $file;
586                         }
587                         elsif ($state eq 'header' && /^$/) {
588                                 $state='body';
589                         }
590                         elsif ($state eq 'body' && /$div/) {
591                                 my $committype="web";
592                                 if (defined $message[0] &&
593                                     $message[0]->{line}=~/^web commit by (\w+):?(.*)/) {
594                                         $user="$1";
595                                         $message[0]->{line}=$2;
596                                 }
597                                 else {
598                                         $committype="svn";
599                                 }
600                                 
601                                 push @ret, { rev => $rev,
602                                         user => htmllink("", $user, 1),
603                                         committype => $committype,
604                                         when => $when, message => [@message],
605                                         pages => [@pages],
606                                 } if @pages;
607                                 return @ret if @ret >= $num;
608                                 
609                                 $state='header';
610                                 $rev=$user=$when=undef;
611                                 @pages=@message=();
612                         }
613                         elsif ($state eq 'body') {
614                                 push @message, {line => escapeHTML($_)},
615                         }
616                 }
617         }
618
619         return @ret;
620 } #}}}
621
622 sub prune ($) { #{{{
623         my $file=shift;
624
625         unlink($file);
626         my $dir=dirname($file);
627         while (rmdir($dir)) {
628                 $dir=dirname($dir);
629         }
630 } #}}}
631
632 sub refresh () { #{{{
633         # find existing pages
634         my %exists;
635         my @files;
636         eval q{use File::Find};
637         find({
638                 no_chdir => 1,
639                 wanted => sub {
640                         if (/$config{wiki_file_prune_regexp}/) {
641                                 no warnings 'once';
642                                 $File::Find::prune=1;
643                                 use warnings "all";
644                         }
645                         elsif (! -d $_ && ! -l $_) {
646                                 my ($f)=/$config{wiki_file_regexp}/; # untaint
647                                 if (! defined $f) {
648                                         warn("skipping bad filename $_\n");
649                                 }
650                                 else {
651                                         $f=~s/^\Q$config{srcdir}\E\/?//;
652                                         push @files, $f;
653                                         $exists{pagename($f)}=1;
654                                 }
655                         }
656                 },
657         }, $config{srcdir});
658
659         my %rendered;
660
661         # check for added or removed pages
662         my @add;
663         foreach my $file (@files) {
664                 my $page=pagename($file);
665                 if (! $oldpagemtime{$page}) {
666                         debug("new page $page");
667                         push @add, $file;
668                         $links{$page}=[];
669                         $pagesources{$page}=$file;
670                 }
671         }
672         my @del;
673         foreach my $page (keys %oldpagemtime) {
674                 if (! $exists{$page}) {
675                         debug("removing old page $page");
676                         push @del, $pagesources{$page};
677                         prune($config{destdir}."/".$renderedfiles{$page});
678                         delete $renderedfiles{$page};
679                         $oldpagemtime{$page}=0;
680                         delete $pagesources{$page};
681                 }
682         }
683         
684         # render any updated files
685         foreach my $file (@files) {
686                 my $page=pagename($file);
687                 
688                 if (! exists $oldpagemtime{$page} ||
689                     mtime("$config{srcdir}/$file") > $oldpagemtime{$page}) {
690                         debug("rendering changed file $file");
691                         render($file);
692                         $rendered{$file}=1;
693                 }
694         }
695         
696         # if any files were added or removed, check to see if each page
697         # needs an update due to linking to them
698         # TODO: inefficient; pages may get rendered above and again here;
699         # problem is the bestlink may have changed and we won't know until
700         # now
701         if (@add || @del) {
702 FILE:           foreach my $file (@files) {
703                         my $page=pagename($file);
704                         foreach my $f (@add, @del) {
705                                 my $p=pagename($f);
706                                 foreach my $link (@{$links{$page}}) {
707                                         if (bestlink($page, $link) eq $p) {
708                                                 debug("rendering $file, which links to $p");
709                                                 render($file);
710                                                 $rendered{$file}=1;
711                                                 next FILE;
712                                         }
713                                 }
714                         }
715                 }
716         }
717
718         # handle backlinks; if a page has added/removed links, update the
719         # pages it links to
720         # TODO: inefficient; pages may get rendered above and again here;
721         # problem is the backlinks could be wrong in the first pass render
722         # above
723         if (%rendered) {
724                 my %linkchanged;
725                 foreach my $file (keys %rendered, @del) {
726                         my $page=pagename($file);
727                         if (exists $links{$page}) {
728                                 foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
729                                         if (length $link &&
730                                             ! exists $oldlinks{$page} ||
731                                             ! grep { $_ eq $link } @{$oldlinks{$page}}) {
732                                                 $linkchanged{$link}=1;
733                                         }
734                                 }
735                         }
736                         if (exists $oldlinks{$page}) {
737                                 foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
738                                         if (length $link &&
739                                             ! exists $links{$page} ||
740                                             ! grep { $_ eq $link } @{$links{$page}}) {
741                                                 $linkchanged{$link}=1;
742                                         }
743                                 }
744                         }
745                 }
746                 foreach my $link (keys %linkchanged) {
747                         my $linkfile=$pagesources{$link};
748                         if (defined $linkfile) {
749                                 debug("rendering $linkfile, to update its backlinks");
750                                 render($linkfile);
751                         }
752                 }
753         }
754 } #}}}
755
756 sub gen_wrapper (@) { #{{{
757         my %config=(@_);
758         eval q{use Cwd 'abs_path'};
759         $config{srcdir}=abs_path($config{srcdir});
760         $config{destdir}=abs_path($config{destdir});
761         my $this=abs_path($0);
762         if (! -x $this) {
763                 error("$this doesn't seem to be executable");
764         }
765
766         if ($config{setup}) {
767                 error("cannot create a wrapper that uses a setup file");
768         }
769         
770         my @params=($config{srcdir}, $config{templatedir}, $config{destdir},
771                 "--wikiname=$config{wikiname}");
772         push @params, "--verbose" if $config{verbose};
773         push @params, "--rebuild" if $config{rebuild};
774         push @params, "--nosvn" if !$config{svn};
775         push @params, "--cgi" if $config{cgi};
776         push @params, "--url=$config{url}" if length $config{url};
777         push @params, "--cgiurl=$config{cgiurl}" if length $config{cgiurl};
778         push @params, "--historyurl=$config{historyurl}" if length $config{historyurl};
779         push @params, "--diffurl=$config{diffurl}" if length $config{diffurl};
780         push @params, "--anonok" if $config{anonok};
781         my $params=join(" ", @params);
782         my $call='';
783         foreach my $p ($this, $this, @params) {
784                 $call.=qq{"$p", };
785         }
786         $call.="NULL";
787         
788         my @envsave;
789         push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
790                        CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
791                        HTTP_COOKIE} if $config{cgi};
792         my $envsave="";
793         foreach my $var (@envsave) {
794                 $envsave.=<<"EOF"
795         if ((s=getenv("$var")))
796                 asprintf(&newenviron[i++], "%s=%s", "$var", s);
797 EOF
798         }
799         
800         open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
801         print OUT <<"EOF";
802 /* A wrapper for ikiwiki, can be safely made suid. */
803 #define _GNU_SOURCE
804 #include <stdio.h>
805 #include <unistd.h>
806 #include <stdlib.h>
807 #include <string.h>
808
809 extern char **environ;
810
811 int main (int argc, char **argv) {
812         /* Sanitize environment. */
813         char *s;
814         char *newenviron[$#envsave+3];
815         int i=0;
816 $envsave
817         newenviron[i++]="HOME=$ENV{HOME}";
818         newenviron[i]=NULL;
819         environ=newenviron;
820
821         if (argc == 2 && strcmp(argv[1], "--params") == 0) {
822                 printf("$params\\n");
823                 exit(0);
824         }
825         
826         execl($call);
827         perror("failed to run $this");
828         exit(1);
829 }
830 EOF
831         close OUT;
832         if (system("gcc", "ikiwiki-wrap.c", "-o", possibly_foolish_untaint($config{wrapper})) != 0) {
833                 error("failed to compile ikiwiki-wrap.c");
834         }
835         unlink("ikiwiki-wrap.c");
836         if (defined $config{wrappermode} &&
837             ! chmod(oct($config{wrappermode}), possibly_foolish_untaint($config{wrapper}))) {
838                 error("chmod $config{wrapper}: $!");
839         }
840         print "successfully generated $config{wrapper}\n";
841 } #}}}
842                 
843 sub misctemplate ($$) { #{{{
844         my $title=shift;
845         my $pagebody=shift;
846         
847         my $template=HTML::Template->new(
848                 filename => "$config{templatedir}/misc.tmpl"
849         );
850         $template->param(
851                 title => $title,
852                 indexlink => indexlink(),
853                 wikiname => $config{wikiname},
854                 pagebody => $pagebody,
855         );
856         return $template->output;
857 }#}}}
858
859 sub cgi_recentchanges ($) { #{{{
860         my $q=shift;
861         
862         my $template=HTML::Template->new(
863                 filename => "$config{templatedir}/recentchanges.tmpl"
864         );
865         $template->param(
866                 title => "RecentChanges",
867                 indexlink => indexlink(),
868                 wikiname => $config{wikiname},
869                 changelog => [rcs_recentchanges(100)],
870         );
871         print $q->header, $template->output;
872 } #}}}
873
874 sub userinfo_get ($$) { #{{{
875         my $user=shift;
876         my $field=shift;
877
878         eval q{use Storable};
879         my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
880         if (! defined $userdata || ! ref $userdata || 
881             ! exists $userdata->{$user} || ! ref $userdata->{$user}) {
882                 return "";
883         }
884         return $userdata->{$user}->{$field};
885 } #}}}
886
887 sub userinfo_set ($$$) { #{{{
888         my $user=shift;
889         my $field=shift;
890         my $value=shift;
891         
892         eval q{use Storable};
893         my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
894         if (! defined $userdata || ! ref $userdata || 
895             ! exists $userdata->{$user} || ! ref $userdata->{$user}) {
896                 return "";
897         }
898         
899         $userdata->{$user}->{$field}=$value;
900         my $oldmask=umask(077);
901         my $ret=Storable::lock_store($userdata, "$config{srcdir}/.ikiwiki/userdb");
902         umask($oldmask);
903         return $ret;
904 } #}}}
905
906 sub userinfo_setall ($$) { #{{{
907         my $user=shift;
908         my $info=shift;
909         
910         eval q{use Storable};
911         my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
912         if (! defined $userdata || ! ref $userdata) {
913                 $userdata={};
914         }
915         $userdata->{$user}=$info;
916         my $oldmask=umask(077);
917         my $ret=Storable::lock_store($userdata, "$config{srcdir}/.ikiwiki/userdb");
918         umask($oldmask);
919         return $ret;
920 } #}}}
921
922 sub cgi_signin ($$) { #{{{
923         my $q=shift;
924         my $session=shift;
925
926         eval q{use CGI::FormBuilder};
927         my $form = CGI::FormBuilder->new(
928                 title => "signin",
929                 fields => [qw(do page from name password confirm_password email)],
930                 header => 1,
931                 method => 'POST',
932                 validate => {
933                         confirm_password => {
934                                 perl => q{eq $form->field("password")},
935                         },
936                         email => 'EMAIL',
937                 },
938                 required => 'NONE',
939                 javascript => 0,
940                 params => $q,
941                 action => $q->request_uri,
942                 header => 0,
943                 template => (-e "$config{templatedir}/signin.tmpl" ?
944                               "$config{templatedir}/signin.tmpl" : "")
945         );
946         
947         $form->field(name => "name", required => 0);
948         $form->field(name => "do", type => "hidden");
949         $form->field(name => "page", type => "hidden");
950         $form->field(name => "from", type => "hidden");
951         $form->field(name => "password", type => "password", required => 0);
952         $form->field(name => "confirm_password", type => "password", required => 0);
953         $form->field(name => "email", required => 0);
954         if ($q->param("do") ne "signin") {
955                 $form->text("You need to log in first.");
956         }
957         
958         if ($form->submitted) {
959                 # Set required fields based on how form was submitted.
960                 my %required=(
961                         "Login" => [qw(name password)],
962                         "Register" => [qw(name password confirm_password email)],
963                         "Mail Password" => [qw(name)],
964                 );
965                 foreach my $opt (@{$required{$form->submitted}}) {
966                         $form->field(name => $opt, required => 1);
967                 }
968         
969                 # Validate password differently depending on how
970                 # form was submitted.
971                 if ($form->submitted eq 'Login') {
972                         $form->field(
973                                 name => "password",
974                                 validate => sub {
975                                         length $form->field("name") &&
976                                         shift eq userinfo_get($form->field("name"), 'password');
977                                 },
978                         );
979                         $form->field(name => "name", validate => '/^\w+$/');
980                 }
981                 else {
982                         $form->field(name => "password", validate => 'VALUE');
983                 }
984                 # And make sure the entered name exists when logging
985                 # in or sending email, and does not when registering.
986                 if ($form->submitted eq 'Register') {
987                         $form->field(
988                                 name => "name",
989                                 validate => sub {
990                                         my $name=shift;
991                                         length $name &&
992                                         ! userinfo_get($name, "regdate");
993                                 },
994                         );
995                 }
996                 else {
997                         $form->field(
998                                 name => "name",
999                                 validate => sub {
1000                                         my $name=shift;
1001                                         length $name &&
1002                                         userinfo_get($name, "regdate");
1003                                 },
1004                         );
1005                 }
1006         }
1007         else {
1008                 # First time settings.
1009                 $form->field(name => "name", comment => "use FirstnameLastName");
1010                 $form->field(name => "confirm_password", comment => "(only needed");
1011                 $form->field(name => "email",            comment => "for registration)");
1012                 if ($session->param("name")) {
1013                         $form->field(name => "name", value => $session->param("name"));
1014                 }
1015         }
1016
1017         if ($form->submitted && $form->validate) {
1018                 if ($form->submitted eq 'Login') {
1019                         $session->param("name", $form->field("name"));
1020                         if (defined $form->field("do") && 
1021                             $form->field("do") ne 'signin') {
1022                                 print $q->redirect(
1023                                         "$config{cgiurl}?do=".$form->field("do").
1024                                         "&page=".$form->field("page").
1025                                         "&from=".$form->field("from"));;
1026                         }
1027                         else {
1028                                 print $q->redirect($config{url});
1029                         }
1030                 }
1031                 elsif ($form->submitted eq 'Register') {
1032                         my $user_name=$form->field('name');
1033                         if (userinfo_setall($user_name, {
1034                                            'email' => $form->field('email'),
1035                                            'password' => $form->field('password'),
1036                                            'regdate' => time
1037                                          })) {
1038                                 $form->field(name => "confirm_password", type => "hidden");
1039                                 $form->field(name => "email", type => "hidden");
1040                                 $form->text("Registration successful. Now you can Login.");
1041                                 print $session->header();
1042                                 print misctemplate($form->title, $form->render(submit => ["Login"]));
1043                         }
1044                         else {
1045                                 error("Error saving registration.");
1046                         }
1047                 }
1048                 elsif ($form->submitted eq 'Mail Password') {
1049                         my $user_name=$form->field("name");
1050                         my $template=HTML::Template->new(
1051                                 filename => "$config{templatedir}/passwordmail.tmpl"
1052                         );
1053                         $template->param(
1054                                 user_name => $user_name,
1055                                 user_password => userinfo_get($user_name, "password"),
1056                                 wikiurl => $config{url},
1057                                 wikiname => $config{wikiname},
1058                                 REMOTE_ADDR => $ENV{REMOTE_ADDR},
1059                         );
1060                         
1061                         eval q{use Mail::Sendmail};
1062                         my ($fromhost) = $config{cgiurl} =~ m!/([^/]+)!;
1063                         sendmail(
1064                                 To => userinfo_get($user_name, "email"),
1065                                 From => "$config{wikiname} admin <".(getpwuid($>))[0]."@".$fromhost.">",
1066                                 Subject => "$config{wikiname} information",
1067                                 Message => $template->output,
1068                         ) or error("Failed to send mail");
1069                         
1070                         $form->text("Your password has been emailed to you.");
1071                         $form->field(name => "name", required => 0);
1072                         print $session->header();
1073                         print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
1074                 }
1075         }
1076         else {
1077                 print $session->header();
1078                 print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
1079         }
1080 } #}}}
1081
1082 sub cgi_prefs ($$) { #{{{
1083         my $q=shift;
1084         my $session=shift;
1085
1086         eval q{use CGI::FormBuilder};
1087         my $form = CGI::FormBuilder->new(
1088                 title => "preferences",
1089                 fields => [qw(do name password confirm_password email)],
1090                 header => 0,
1091                 method => 'POST',
1092                 validate => {
1093                         confirm_password => {
1094                                 perl => q{eq $form->field("password")},
1095                         },
1096                         email => 'EMAIL',
1097                 },
1098                 required => 'NONE',
1099                 javascript => 0,
1100                 params => $q,
1101                 action => $q->request_uri,
1102                 template => (-e "$config{templatedir}/prefs.tmpl" ?
1103                               "$config{templatedir}/prefs.tmpl" : "")
1104         );
1105         my @buttons=("Save Preferences", "Logout", "Cancel");
1106         
1107         my $user_name=$session->param("name");
1108         $form->field(name => "do", type => "hidden");
1109         $form->field(name => "name", disabled => 1,
1110                 value => $user_name, force => 1);
1111         $form->field(name => "password", type => "password");
1112         $form->field(name => "confirm_password", type => "password");
1113         
1114         if (! $form->submitted) {
1115                 $form->field(name => "email", value => userinfo_get($user_name, "email"));
1116         }
1117         
1118         if ($form->submitted eq 'Logout') {
1119                 $session->delete();
1120                 print $q->redirect($config{url});
1121                 return;
1122         }
1123         elsif ($form->submitted eq 'Cancel') {
1124                 print $q->redirect($config{url});
1125                 return;
1126         }
1127         elsif ($form->submitted eq "Save Preferences" && $form->validate) {
1128                 foreach my $field (qw(password email)) {
1129                         if (length $form->field($field)) {
1130                                 userinfo_set($user_name, $field, $form->field($field)) || error("failed to set $field");
1131                         }
1132                 }
1133                 $form->text("Preferences saved.");
1134         }
1135         
1136         print $session->header();
1137         print misctemplate($form->title, $form->render(submit => \@buttons));
1138 } #}}}
1139
1140 sub cgi_editpage ($$) { #{{{
1141         my $q=shift;
1142         my $session=shift;
1143
1144         eval q{use CGI::FormBuilder};
1145         my $form = CGI::FormBuilder->new(
1146                 fields => [qw(do rcsinfo from page content comments)],
1147                 header => 1,
1148                 method => 'POST',
1149                 validate => {
1150                         content => '/.+/',
1151                 },
1152                 required => [qw{content}],
1153                 javascript => 0,
1154                 params => $q,
1155                 action => $q->request_uri,
1156                 table => 0,
1157                 template => "$config{templatedir}/editpage.tmpl"
1158         );
1159         my @buttons=("Save Page", "Preview", "Cancel");
1160         
1161         my ($page)=$form->param('page')=~/$config{wiki_file_regexp}/;
1162         if (! defined $page || ! length $page || $page ne $q->param('page') ||
1163             $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
1164                 error("bad page name");
1165         }
1166         $page=lc($page);
1167         
1168         my $file=$page.$config{default_pageext};
1169         my $newfile=1;
1170         if (exists $pagesources{lc($page)}) {
1171                 $file=$pagesources{lc($page)};
1172                 $newfile=0;
1173         }
1174
1175         $form->field(name => "do", type => 'hidden');
1176         $form->field(name => "from", type => 'hidden');
1177         $form->field(name => "rcsinfo", type => 'hidden');
1178         $form->field(name => "page", value => "$page", force => 1);
1179         $form->field(name => "comments", type => "text", size => 80);
1180         $form->field(name => "content", type => "textarea", rows => 20,
1181                 cols => 80);
1182         $form->tmpl_param("can_commit", $config{svn});
1183         $form->tmpl_param("indexlink", indexlink());
1184         $form->tmpl_param("helponformattinglink",
1185                 htmllink("", "HelpOnFormatting", 1));
1186         if (! $form->submitted) {
1187                 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
1188                         force => 1);
1189         }
1190         
1191         if ($form->submitted eq "Cancel") {
1192                 print $q->redirect("$config{url}/".htmlpage($page));
1193                 return;
1194         }
1195         elsif ($form->submitted eq "Preview") {
1196                 $form->tmpl_param("page_preview",
1197                         htmlize($config{default_pageext},
1198                                 linkify($form->field('content'), $page)));
1199         }
1200         else {
1201                 $form->tmpl_param("page_preview", "");
1202         }
1203         $form->tmpl_param("page_conflict", "");
1204         
1205         if (! $form->submitted || $form->submitted eq "Preview" || 
1206             ! $form->validate) {
1207                 if ($form->field("do") eq "create") {
1208                         if (exists $pagesources{lc($page)}) {
1209                                 # hmm, someone else made the page in the
1210                                 # meantime?
1211                                 print $q->redirect("$config{url}/".htmlpage($page));
1212                                 return;
1213                         }
1214                         
1215                         my @page_locs;
1216                         my $best_loc;
1217                         my ($from)=$form->param('from')=~/$config{wiki_file_regexp}/;
1218                         if (! defined $from || ! length $from ||
1219                             $from ne $form->param('from') ||
1220                             $from=~/$config{wiki_file_prune_regexp}/ || $from=~/^\//) {
1221                                 @page_locs=$best_loc=$page;
1222                         }
1223                         else {
1224                                 my $dir=$from."/";
1225                                 $dir=~s![^/]+/$!!;
1226                                 
1227                                 if ($page eq 'discussion') {
1228                                         $best_loc="$from/$page";
1229                                 }
1230                                 else {
1231                                         $best_loc=$dir.$page;
1232                                 }
1233                                 
1234                                 push @page_locs, $dir.$page;
1235                                 push @page_locs, "$from/$page";
1236                                 while (length $dir) {
1237                                         $dir=~s![^/]+/$!!;
1238                                         push @page_locs, $dir.$page;
1239                                 }
1240
1241                                 @page_locs = grep { ! exists
1242                                         $pagesources{lc($_)} } @page_locs;
1243                         }
1244
1245                         $form->tmpl_param("page_select", 1);
1246                         $form->field(name => "page", type => 'select',
1247                                 options => \@page_locs, value => $best_loc);
1248                         $form->title("creating $page");
1249                 }
1250                 elsif ($form->field("do") eq "edit") {
1251                         if (! defined $form->field('content') || 
1252                             ! length $form->field('content')) {
1253                                 my $content="";
1254                                 if (exists $pagesources{lc($page)}) {
1255                                                 $content=readfile("$config{srcdir}/$pagesources{lc($page)}");
1256                                         $content=~s/\n/\r\n/g;
1257                                 }
1258                                 $form->field(name => "content", value => $content,
1259                                         force => 1);
1260                         }
1261                         $form->tmpl_param("page_select", 0);
1262                         $form->field(name => "page", type => 'hidden');
1263                         $form->title("editing $page");
1264                 }
1265                 
1266                 print $form->render(submit => \@buttons);
1267         }
1268         else {
1269                 # save page
1270                 my $content=$form->field('content');
1271                 $content=~s/\r\n/\n/g;
1272                 $content=~s/\r/\n/g;
1273                 writefile("$config{srcdir}/$file", $content);
1274                 
1275                 my $message="web commit ";
1276                 if ($session->param("name")) {
1277                         $message.="by ".$session->param("name");
1278                 }
1279                 else {
1280                         $message.="from $ENV{REMOTE_ADDR}";
1281                 }
1282                 if (defined $form->field('comments') &&
1283                     length $form->field('comments')) {
1284                         $message.=": ".$form->field('comments');
1285                 }
1286                 
1287                 if ($config{svn}) {
1288                         if ($newfile) {
1289                                 rcs_add($file);
1290                         }
1291                         # prevent deadlock with post-commit hook
1292                         unlockwiki();
1293                         # presumably the commit will trigger an update
1294                         # of the wiki
1295                         my $conflict=rcs_commit($file, $message,
1296                                 $form->field("rcsinfo"));
1297                 
1298                         if (defined $conflict) {
1299                                 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
1300                                         force => 1);
1301                                 $form->tmpl_param("page_conflict", 1);
1302                                 $form->field("content", value => $conflict, force => 1);
1303                                 $form->field("do", "edit)");
1304                                 $form->tmpl_param("page_select", 0);
1305                                 $form->field(name => "page", type => 'hidden');
1306                                 $form->title("editing $page");
1307                                 print $form->render(submit => \@buttons);
1308                                 return;
1309                         }
1310                 }
1311                 else {
1312                         loadindex();
1313                         refresh();
1314                         saveindex();
1315                 }
1316                 
1317                 # The trailing question mark tries to avoid broken
1318                 # caches and get the most recent version of the page.
1319                 print $q->redirect("$config{url}/".htmlpage($page)."?updated");
1320         }
1321 } #}}}
1322
1323 sub cgi () { #{{{
1324         eval q{use CGI};
1325         eval q{use CGI::Session};
1326         
1327         my $q=CGI->new;
1328         
1329         my $do=$q->param('do');
1330         if (! defined $do || ! length $do) {
1331                 error("\"do\" parameter missing");
1332         }
1333         
1334         # This does not need a session.
1335         if ($do eq 'recentchanges') {
1336                 cgi_recentchanges($q);
1337                 return;
1338         }
1339         
1340         CGI::Session->name("ikiwiki_session");
1341
1342         my $oldmask=umask(077);
1343         my $session = CGI::Session->new("driver:db_file", $q,
1344                 { FileName => "$config{srcdir}/.ikiwiki/sessions.db" });
1345         umask($oldmask);
1346         
1347         # Everything below this point needs the user to be signed in.
1348         if ((! $config{anonok} && ! defined $session->param("name") ||
1349              ! defined $session->param("name") ||
1350              ! userinfo_get($session->param("name"), "regdate")) || $do eq 'signin') {
1351                 cgi_signin($q, $session);
1352         
1353                 # Force session flush with safe umask.
1354                 my $oldmask=umask(077);
1355                 $session->flush;
1356                 umask($oldmask);
1357                 
1358                 return;
1359         }
1360         
1361         if ($do eq 'create' || $do eq 'edit') {
1362                 cgi_editpage($q, $session);
1363         }
1364         elsif ($do eq 'prefs') {
1365                 cgi_prefs($q, $session);
1366         }
1367         else {
1368                 error("unknown do parameter");
1369         }
1370 } #}}}
1371
1372 sub setup () { # {{{
1373         my $setup=possibly_foolish_untaint($config{setup});
1374         delete $config{setup};
1375         open (IN, $setup) || error("read $setup: $!\n");
1376         local $/=undef;
1377         my $code=<IN>;
1378         ($code)=$code=~/(.*)/s;
1379         close IN;
1380
1381         eval $code;
1382         error($@) if $@;
1383         exit;
1384 } #}}}
1385
1386 # main {{{
1387 setup() if $config{setup};
1388 lockwiki();
1389 if ($config{wrapper}) {
1390         gen_wrapper(%config);
1391         exit;
1392 }
1393 memoize('pagename');
1394 memoize('bestlink');
1395 loadindex() unless $config{rebuild};
1396 if ($config{cgi}) {
1397         cgi();
1398 }
1399 else {
1400         rcs_update() if $config{svn};
1401         refresh();
1402         saveindex();
1403 }
1404 #}}}