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