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