]> sipb.mit.edu Git - ikiwiki.git/blob - ikiwiki
security improvements, switched to single session db file
[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                                 push @ret, { rev => $rev, user => $user,
450                                         when => $when, message => [@message],
451                                         pages => [@pages] } if @pages;
452                                 return @ret if @ret >= $num;
453                                 
454                                 $state='header';
455                                 $rev=$user=$when=undef;
456                                 @pages=@message=();
457                         }
458                         elsif ($state eq 'body') {
459                                 push @message, {line => $_},
460                         }
461                 }
462         }
463
464         return @ret;
465 } #}}}
466
467 sub prune ($) { #{{{
468         my $file=shift;
469
470         unlink($file);
471         my $dir=dirname($file);
472         while (rmdir($dir)) {
473                 $dir=dirname($dir);
474         }
475 } #}}}
476
477 sub refresh () { #{{{
478         # Find existing pages.
479         my %exists;
480         my @files;
481         find({
482                 no_chdir => 1,
483                 wanted => sub {
484                         if (/$wiki_file_prune_regexp/) {
485                                 $File::Find::prune=1;
486                         }
487                         elsif (! -d $_) {
488                                 my ($f)=/$wiki_file_regexp/; # untaint
489                                 if (! defined $f) {
490                                         warn("skipping bad filename $_\n");
491                                 }
492                                 else {
493                                         $f=~s/^\Q$srcdir\E\/?//;
494                                         push @files, $f;
495                                         $exists{pagename($f)}=1;
496                                 }
497                         }
498                 },
499         }, $srcdir);
500
501         my %rendered;
502
503         # check for added or removed pages
504         my @add;
505         foreach my $file (@files) {
506                 my $page=pagename($file);
507                 if (! $oldpagemtime{$page}) {
508                         debug("new page $page");
509                         push @add, $file;
510                         $links{$page}=[];
511                         $pagesources{$page}=$file;
512                 }
513         }
514         my @del;
515         foreach my $page (keys %oldpagemtime) {
516                 if (! $exists{$page}) {
517                         debug("removing old page $page");
518                         push @del, $renderedfiles{$page};
519                         prune($destdir."/".$renderedfiles{$page});
520                         delete $renderedfiles{$page};
521                         $oldpagemtime{$page}=0;
522                         delete $pagesources{$page};
523                 }
524         }
525         
526         # render any updated files
527         foreach my $file (@files) {
528                 my $page=pagename($file);
529                 
530                 if (! exists $oldpagemtime{$page} ||
531                     mtime("$srcdir/$file") > $oldpagemtime{$page}) {
532                         debug("rendering changed file $file");
533                         render($file);
534                         $rendered{$file}=1;
535                 }
536         }
537         
538         # if any files were added or removed, check to see if each page
539         # needs an update due to linking to them
540         # TODO: inefficient; pages may get rendered above and again here;
541         # problem is the bestlink may have changed and we won't know until
542         # now
543         if (@add || @del) {
544 FILE:           foreach my $file (@files) {
545                         my $page=pagename($file);
546                         foreach my $f (@add, @del) {
547                                 my $p=pagename($f);
548                                 foreach my $link (@{$links{$page}}) {
549                                         if (bestlink($page, $link) eq $p) {
550                                                 debug("rendering $file, which links to $p");
551                                                 render($file);
552                                                 $rendered{$file}=1;
553                                                 next FILE;
554                                         }
555                                 }
556                         }
557                 }
558         }
559
560         # handle backlinks; if a page has added/removed links, update the
561         # pages it links to
562         # TODO: inefficient; pages may get rendered above and again here;
563         # problem is the backlinks could be wrong in the first pass render
564         # above
565         if (%rendered) {
566                 my %linkchanged;
567                 foreach my $file (keys %rendered, @del) {
568                         my $page=pagename($file);
569                         if (exists $links{$page}) {
570                                 foreach my $link (@{$links{$page}}) {
571                                         $link=bestlink($page, $link);
572                                         if (length $link &&
573                                             ! exists $oldlinks{$page} ||
574                                             ! grep { $_ eq $link } @{$oldlinks{$page}}) {
575                                                 $linkchanged{$link}=1;
576                                         }
577                                 }
578                         }
579                         if (exists $oldlinks{$page}) {
580                                 foreach my $link (@{$oldlinks{$page}}) {
581                                         $link=bestlink($page, $link);
582                                         if (length $link &&
583                                             ! exists $links{$page} ||
584                                             ! grep { $_ eq $link } @{$links{$page}}) {
585                                                 $linkchanged{$link}=1;
586                                         }
587                                 }
588                         }
589                 }
590                 foreach my $link (keys %linkchanged) {
591                         my $linkfile=$pagesources{$link};
592                         if (defined $linkfile) {
593                                 debug("rendering $linkfile, to update its backlinks");
594                                 render($linkfile);
595                         }
596                 }
597         }
598 } #}}}
599
600 # Generates a C wrapper program for running ikiwiki in a specific way.
601 # The wrapper may be safely made suid.
602 sub gen_wrapper ($$) { #{{{
603         my ($svn, $rebuild)=@_;
604
605         eval q{use Cwd 'abs_path'};
606         $srcdir=abs_path($srcdir);
607         $destdir=abs_path($destdir);
608         my $this=abs_path($0);
609         if (! -x $this) {
610                 error("$this doesn't seem to be executable");
611         }
612
613         my @params=($srcdir, $templatedir, $destdir, "--wikiname=$wikiname");
614         push @params, "--verbose" if $verbose;
615         push @params, "--rebuild" if $rebuild;
616         push @params, "--nosvn" if !$svn;
617         push @params, "--cgi" if $cgi;
618         push @params, "--url=$url" if $url;
619         push @params, "--cgiurl=$cgiurl" if $cgiurl;
620         push @params, "--historyurl=$historyurl" if $historyurl;
621         push @params, "--anonok" if $anonok;
622         my $params=join(" ", @params);
623         my $call='';
624         foreach my $p ($this, $this, @params) {
625                 $call.=qq{"$p", };
626         }
627         $call.="NULL";
628         
629         my @envsave;
630         push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
631                        CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
632                        HTTP_COOKIE} if $cgi;
633         my $envsave="";
634         foreach my $var (@envsave) {
635                 $envsave.=<<"EOF"
636         if ((s=getenv("$var")))
637                 asprintf(&newenviron[i++], "%s=%s", "$var", s);
638 EOF
639         }
640         
641         open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
642         print OUT <<"EOF";
643 /* A wrapper for ikiwiki, can be safely made suid. */
644 #define _GNU_SOURCE
645 #include <stdio.h>
646 #include <unistd.h>
647 #include <stdlib.h>
648 #include <string.h>
649
650 extern char **environ;
651
652 int main (int argc, char **argv) {
653         /* Sanitize environment. */
654         char *s;
655         char *newenviron[$#envsave+3];
656         int i=0;
657 $envsave
658         newenviron[i++]="HOME=$ENV{HOME}";
659         newenviron[i]=NULL;
660         environ=newenviron;
661
662         if (argc == 2 && strcmp(argv[1], "--params") == 0) {
663                 printf("$params\\n");
664                 exit(0);
665         }
666         
667         execl($call);
668         perror("failed to run $this");
669         exit(1);
670 }
671 EOF
672         close OUT;
673         if (system("gcc", "ikiwiki-wrap.c", "-o", "ikiwiki-wrap") != 0) {
674                 error("failed to compile ikiwiki-wrap.c");
675         }
676         unlink("ikiwiki-wrap.c");
677         print "successfully generated ikiwiki-wrap\n";
678         exit 0;
679 } #}}}
680                 
681 sub misctemplate ($$) { #{{{
682         my $title=shift;
683         my $pagebody=shift;
684         
685         my $template=HTML::Template->new(
686                 filename => "$templatedir/misc.tmpl"
687         );
688         $template->param(
689                 title => $title,
690                 indexlink => indexlink(),
691                 wikiname => $wikiname,
692                 pagebody => $pagebody,
693         );
694         return $template->output;
695 }#}}}
696
697 sub cgi_recentchanges ($) { #{{{
698         my $q=shift;
699         
700         my $template=HTML::Template->new(
701                 filename => "$templatedir/recentchanges.tmpl"
702         );
703         $template->param(
704                 title => "RecentChanges",
705                 indexlink => indexlink(),
706                 wikiname => $wikiname,
707                 changelog => [rcs_recentchanges(100)],
708         );
709         print $q->header, $template->output;
710 } #}}}
711
712 sub cgi_signin ($$) { #{{{
713         my $q=shift;
714         my $session=shift;
715
716         eval q{use CGI::FormBuilder};
717         my $form = CGI::FormBuilder->new(
718                 title => "$wikiname signin",
719                 fields => [qw(do page name password confirm_password email)],
720                 header => 1,
721                 method => 'POST',
722                 validate => {
723                         name => '/^\w+$/',
724                         confirm_password => {
725                                 perl => q{eq $form->field("password")},
726                         },
727                         email => 'EMAIL',
728                 },
729                 required => 'NONE',
730                 javascript => 0,
731                 params => $q,
732                 action => $q->request_uri,
733                 header => 0,
734                 template => (-e "$templatedir/signin.tmpl" ? "$templatedir/signin.tmpl" : "")
735         );
736         
737         $form->field(name => "name", required => 0);
738         $form->field(name => "do", type => "hidden");
739         $form->field(name => "page", type => "hidden");
740         $form->field(name => "password", type => "password", required => 0);
741         $form->field(name => "confirm_password", type => "password", required => 0);
742         $form->field(name => "email", required => 0);
743         if ($session->param("name")) {
744                 $form->field(name => "name", value => $session->param("name"));
745         }
746         if ($q->param("do") ne "signin") {
747                 $form->text("You need to log in before you can edit pages.");
748         }
749         
750         if ($form->submitted) {
751                 # Set required fields based on how form was submitted.
752                 my %required=(
753                         "Login" => [qw(name password)],
754                         "Register" => [qw(name password confirm_password email)],
755                         "Mail Password" => [qw(name)],
756                 );
757                 foreach my $opt (@{$required{$form->submitted}}) {
758                         $form->field(name => $opt, required => 1);
759                 }
760         
761                 # Validate password differently depending on how form was
762                 # submitted.
763                 if ($form->submitted eq 'Login') {
764                         $form->field(
765                                 name => "password",
766                                 validate => sub {
767                                         # TODO get real user password
768                                         shift eq "foo";
769                                 },
770                         );
771                 }
772                 else {
773                         $form->field(name => "password", validate => 'VALUE');
774                 }
775         }
776         else {
777                 # Comments only shown first time.
778                 $form->field(name => "name", comment => "use FirstnameLastName");
779                 $form->field(name => "confirm_password", comment => "(only needed");
780                 $form->field(name => "email",            comment => "for registration)");
781         }
782
783         if ($form->submitted && $form->validate) {
784                 if ($form->submitted eq 'Login') {
785                         $session->param("name", $form->field("name"));
786                         if (defined $form->field("do") && 
787                             $form->field("do") ne 'signin') {
788                                 print $q->redirect(
789                                         "$cgiurl?do=".$form->field("do").
790                                         "&page=".$form->field("page"));
791                         }
792                         else {
793                                 print $q->redirect($url);
794                         }
795                 }
796                 elsif ($form->submitted eq 'Register') {
797                         # TODO: save registration info
798                         $form->field(name => "confirm_password", type => "hidden");
799                         $form->field(name => "email", type => "hidden");
800                         $form->text("Registration successful. Now you can Login.");
801                         print $session->header();
802                         print misctemplate($form->title, $form->render(submit => ["Login"]));
803                 }
804                 elsif ($form->submitted eq 'Mail Password') {
805                         # TODO mail password
806                         $form->text("Your password has been emailed to you.");
807                         print $session->header();
808                         print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
809                 }
810         }
811         else {
812                 print $session->header();
813                 print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
814         }
815 } #}}}
816
817 sub cgi_editpage ($$) { #{{{
818         my $q=shift;
819         my $session=shift;
820
821         eval q{use CGI::FormBuilder};
822         my $form = CGI::FormBuilder->new(
823                 fields => [qw(do from page content comments)],
824                 header => 1,
825                 method => 'POST',
826                 validate => {},
827                 required => [qw{}],
828                 javascript => 0,
829                 params => $q,
830                 action => $q->request_uri,
831                 table => 0,
832                 template => "$templatedir/editpage.tmpl"
833         );
834         
835         my ($page)=$form->param('page')=~/$wiki_file_regexp/;
836         if (! defined $page || ! length $page || $page ne $q->param('page') ||
837             $page=~/$wiki_file_prune_regexp/ || $page=~/^\//) {
838                 error("bad page name");
839         }
840         $page=lc($page);
841
842         $form->field(name => "do", type => 'hidden');
843         $form->field(name => "from", type => 'hidden');
844         $form->field(name => "page", value => "$page", force => 1);
845         $form->field(name => "comments", type => "text", size => 80);
846         $form->field(name => "content", type => "textarea", rows => 20,
847                 cols => 80);
848         
849         if (! $form->submitted || ! $form->validate) {
850                 if ($form->field("do") eq "create") {
851                         if (exists $pagesources{lc($page)}) {
852                                 # hmm, someone else made the page in the
853                                 # meantime?
854                                 print $q->redirect("$url/".htmlpage($page));
855                                 return;
856                         }
857                         
858                         my @page_locs;
859                         my ($from)=$form->param('from')=~/$wiki_file_regexp/;
860                         if (! defined $from || ! length $from ||
861                             $from ne $form->param('from') ||
862                             $from=~/$wiki_file_prune_regexp/ || $from=~/^\//) {
863                                 @page_locs=$page;
864                         }
865                         else {
866                                 my $dir=$from."/";
867                                 $dir=~s![^/]+/$!!;
868                                 push @page_locs, $dir.$page;
869                                 push @page_locs, "$from/$page";
870                                 while (length $dir) {
871                                         $dir=~s![^/]+/$!!;
872                                         push @page_locs, $dir.$page;
873                                 }
874                         }
875
876                         $form->tmpl_param("page_select", 1);
877                         $form->field(name => "page", type => 'select',
878                                 options => \@page_locs);
879                         $form->title("creating $page");
880                 }
881                 elsif ($form->field("do") eq "edit") {
882                         my $content="";
883                         if (exists $pagesources{lc($page)}) {
884                                 $content=readfile("$srcdir/$pagesources{lc($page)}");
885                                 $content=~s/\n/\r\n/g;
886                         }
887                         $form->tmpl_param("page_select", 0);
888                         $form->field(name => "content", value => $content,
889                                 force => 1);
890                         $form->field(name => "page", type => 'hidden');
891                         $form->title("editing $page");
892                 }
893                 
894                 $form->tmpl_param("can_commit", $svn);
895                 $form->tmpl_param("indexlink", indexlink());
896                 print $form->render(submit => ["Save Page"]);
897         }
898         else {
899                 # save page
900                 my $file=$page.$default_pagetype;
901                 my $newfile=1;
902                 if (exists $pagesources{lc($page)}) {
903                         $file=$pagesources{lc($page)};
904                         $newfile=0;
905                 }
906                 
907                 my $content=$form->field('content');
908                 $content=~s/\r\n/\n/g;
909                 $content=~s/\r/\n/g;
910                 writefile("$srcdir/$file", $content);
911                 
912                 my $message="web commit ";
913                 if ($session->param("name")) {
914                         $message.="by ".$session->param("name");
915                 }
916                 else {
917                         $message.="from $ENV{REMOTE_ADDR}";
918                 }
919                 if (length $form->field('comments')) {
920                         $message.=": ".$form->field('comments');
921                 }
922                 
923                 if ($svn) {
924                         if ($newfile) {
925                                 rcs_add($file);
926                         }
927                         # presumably the commit will trigger an update
928                         # of the wiki
929                         rcs_commit($message);
930                 }
931                 else {
932                         refresh();
933                 }
934                 
935                 print $q->redirect("$url/".htmlpage($page));
936         }
937 } #}}}
938
939 sub cgi () { #{{{
940         eval q{use CGI};
941         eval q{use CGI::Session};
942         
943         my $q=CGI->new;
944         
945         my $do=$q->param('do');
946         if (! defined $do || ! length $do) {
947                 error("\"do\" parameter missing");
948         }
949         
950         # This does not need a session.
951         if ($do eq 'recentchanges') {
952                 cgi_recentchanges($q);
953                 return;
954         }
955         
956         CGI::Session->name("ikiwiki_session");
957
958         my $oldmask=umask(077);
959         my $session = CGI::Session->new("driver:db_file", $q,
960                 { FileName => "$srcdir/.ikiwiki/sessions.db" });
961         umask($oldmask);
962         
963         # Everything below this point needs the user to be signed in.
964         if ((! $anonok && ! defined $session->param("name")) || $do eq 'signin') {
965                 cgi_signin($q, $session);
966                 return;
967         }
968         
969         if ($do eq 'create' || $do eq 'edit') {
970                 cgi_editpage($q, $session);
971         }
972         else {
973                 error("unknown do parameter");
974         }
975 } #}}}
976
977 # main {{{
978 my $rebuild=0;
979 my $wrapper=0;
980 if (grep /^-/, @ARGV) {
981         eval {use Getopt::Long};
982         GetOptions(
983                 "wikiname=s" => \$wikiname,
984                 "verbose|v" => \$verbose,
985                 "rebuild" => \$rebuild,
986                 "wrapper" => \$wrapper,
987                 "svn!" => \$svn,
988                 "anonok!" => \$anonok,
989                 "cgi" => \$cgi,
990                 "url=s" => \$url,
991                 "cgiurl=s" => \$cgiurl,
992                 "historyurl=s" => \$historyurl,
993         ) || usage();
994 }
995 usage() unless @ARGV == 3;
996 ($srcdir) = possibly_foolish_untaint(shift);
997 ($templatedir) = possibly_foolish_untaint(shift);
998 ($destdir) = possibly_foolish_untaint(shift);
999
1000 if ($cgi && ! length $url) {
1001         error("Must specify url to wiki with --url when using --cgi");
1002 }
1003
1004 gen_wrapper($svn, $rebuild) if $wrapper;
1005 memoize('pagename');
1006 memoize('bestlink');
1007 loadindex() unless $rebuild;
1008 if ($cgi) {
1009         cgi();
1010 }
1011 else {
1012         rcs_update() if $svn;
1013         refresh();
1014         saveindex();
1015 }
1016 #}}}