]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - ikiwiki
foo
[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;
31 sub usage { #{{{
32         die "usage: ikiwiki [options] source templates dest\n";
33 } #}}}
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 } #}}}
46 sub debug ($) { #{{{
47         if (! $cgi) {
48                 print "@_\n" if $verbose;
49         }
50         else {
51                 print STDERR "@_\n" if $verbose;
52         }
53 } #}}}
55 sub mtime ($) { #{{{
56         my $page=shift;
57         
58         return (stat($page))[9];
59 } #}}}
61 sub possibly_foolish_untaint ($) { #{{{
62         my $tainted=shift;
63         my ($untainted)=$tainted=~/(.*)/;
64         return $untainted;
65 } #}}}
67 sub basename ($) { #{{{
68         my $file=shift;
70         $file=~s!.*/!!;
71         return $file;
72 } #}}}
74 sub dirname ($) { #{{{
75         my $file=shift;
77         $file=~s!/?[^/]+$!!;
78         return $file;
79 } #}}}
81 sub pagetype ($) { #{{{
82         my $page=shift;
83         
84         if ($page =~ /\.mdwn$/) {
85                 return ".mdwn";
86         }
87         else {
88                 return "unknown";
89         }
90 } #}}}
92 sub pagename ($) { #{{{
93         my $file=shift;
95         my $type=pagetype($file);
96         my $page=$file;
97         $page=~s/\Q$type\E*$// unless $type eq 'unknown';
98         return $page;
99 } #}}}
101 sub htmlpage ($) { #{{{
102         my $page=shift;
104         return $page.".html";
105 } #}}}
107 sub readfile ($) { #{{{
108         my $file=shift;
110         local $/=undef;
111         open (IN, "$file") || error("failed to read $file: $!");
112         my $ret=<IN>;
113         close IN;
114         return $ret;
115 } #}}}
117 sub writefile ($$) { #{{{
118         my $file=shift;
119         my $content=shift;
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 } #}}}
137 sub findlinks ($) { #{{{
138         my $content=shift;
140         my @links;
141         while ($content =~ /$wiki_link_regexp/g) {
142                 push @links, lc($1);
143         }
144         return @links;
145 } #}}}
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;
161                 if (exists $links{$l}) {
162                         #debug("for $page, \"$link\", use $l");
163                         return $l;
164                 }
165         } while $cwd=~s!/?[^/]+$!!;
167         #print STDERR "warning: page $page, broken link: $link\n";
168         return "";
169 } #}}}
171 sub isinlinableimage ($) { #{{{
172         my $file=shift;
173         
174         $file=~/\.(png|gif|jpg|jpeg)$/;
175 } #}}}
177 sub htmllink { #{{{
178         my $page=shift;
179         my $link=shift;
180         my $noimagelink=shift;
182         my $bestlink=bestlink($page, $link);
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 } #}}}
205 sub linkify ($$) { #{{{
206         my $content=shift;
207         my $file=shift;
209         $content =~ s/$wiki_link_regexp/htmllink(pagename($file), $1)/eg;
210         
211         return $content;
212 } #}}}
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 } #}}}
226 sub backlinks ($) { #{{{
227         my $page=shift;
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         }
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 } #}}}
271 sub indexlink () { #{{{
272         return "<a href=\"$url\">$wikiname</a>";
273 } #}}}
274         
275 sub finalize ($$) { #{{{
276         my $content=shift;
277         my $page=shift;
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         }
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 } #}}}
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 } #}}}
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 } #}}}
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 } #}}}
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 } #}}}
385 sub rcs_commit ($) { #{{{
386         my $message=shift;
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 } #}}}
396 sub rcs_add ($) { #{{{
397         my $file=shift;
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 } #}}}
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;
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                                 print STDERR ">>$message[0]<<\n";
450                                 if (defined $message[0] &&
451                                     $message[0]=~/^web commit by (\w+)(.*)/) {
452                                         $user="$1 (web)";
453                                         $message[0]=$2;
454                                 }
455                                 
456                                 push @ret, { rev => $rev, user => $user,
457                                         when => $when, message => [@message],
458                                         pages => [@pages] } if @pages;
459                                 return @ret if @ret >= $num;
460                                 
461                                 $state='header';
462                                 $rev=$user=$when=undef;
463                                 @pages=@message=();
464                         }
465                         elsif ($state eq 'body') {
466                                 push @message, {line => $_},
467                         }
468                 }
469         }
471         return @ret;
472 } #}}}
474 sub prune ($) { #{{{
475         my $file=shift;
477         unlink($file);
478         my $dir=dirname($file);
479         while (rmdir($dir)) {
480                 $dir=dirname($dir);
481         }
482 } #}}}
484 sub refresh () { #{{{
485         # Find existing pages.
486         my %exists;
487         my @files;
488         find({
489                 no_chdir => 1,
490                 wanted => sub {
491                         if (/$wiki_file_prune_regexp/) {
492                                 $File::Find::prune=1;
493                         }
494                         elsif (! -d $_) {
495                                 my ($f)=/$wiki_file_regexp/; # untaint
496                                 if (! defined $f) {
497                                         warn("skipping bad filename $_\n");
498                                 }
499                                 else {
500                                         $f=~s/^\Q$srcdir\E\/?//;
501                                         push @files, $f;
502                                         $exists{pagename($f)}=1;
503                                 }
504                         }
505                 },
506         }, $srcdir);
508         my %rendered;
510         # check for added or removed pages
511         my @add;
512         foreach my $file (@files) {
513                 my $page=pagename($file);
514                 if (! $oldpagemtime{$page}) {
515                         debug("new page $page");
516                         push @add, $file;
517                         $links{$page}=[];
518                         $pagesources{$page}=$file;
519                 }
520         }
521         my @del;
522         foreach my $page (keys %oldpagemtime) {
523                 if (! $exists{$page}) {
524                         debug("removing old page $page");
525                         push @del, $renderedfiles{$page};
526                         prune($destdir."/".$renderedfiles{$page});
527                         delete $renderedfiles{$page};
528                         $oldpagemtime{$page}=0;
529                         delete $pagesources{$page};
530                 }
531         }
532         
533         # render any updated files
534         foreach my $file (@files) {
535                 my $page=pagename($file);
536                 
537                 if (! exists $oldpagemtime{$page} ||
538                     mtime("$srcdir/$file") > $oldpagemtime{$page}) {
539                         debug("rendering changed file $file");
540                         render($file);
541                         $rendered{$file}=1;
542                 }
543         }
544         
545         # if any files were added or removed, check to see if each page
546         # needs an update due to linking to them
547         # TODO: inefficient; pages may get rendered above and again here;
548         # problem is the bestlink may have changed and we won't know until
549         # now
550         if (@add || @del) {
551 FILE:           foreach my $file (@files) {
552                         my $page=pagename($file);
553                         foreach my $f (@add, @del) {
554                                 my $p=pagename($f);
555                                 foreach my $link (@{$links{$page}}) {
556                                         if (bestlink($page, $link) eq $p) {
557                                                 debug("rendering $file, which links to $p");
558                                                 render($file);
559                                                 $rendered{$file}=1;
560                                                 next FILE;
561                                         }
562                                 }
563                         }
564                 }
565         }
567         # handle backlinks; if a page has added/removed links, update the
568         # pages it links to
569         # TODO: inefficient; pages may get rendered above and again here;
570         # problem is the backlinks could be wrong in the first pass render
571         # above
572         if (%rendered) {
573                 my %linkchanged;
574                 foreach my $file (keys %rendered, @del) {
575                         my $page=pagename($file);
576                         if (exists $links{$page}) {
577                                 foreach my $link (@{$links{$page}}) {
578                                         $link=bestlink($page, $link);
579                                         if (length $link &&
580                                             ! exists $oldlinks{$page} ||
581                                             ! grep { $_ eq $link } @{$oldlinks{$page}}) {
582                                                 $linkchanged{$link}=1;
583                                         }
584                                 }
585                         }
586                         if (exists $oldlinks{$page}) {
587                                 foreach my $link (@{$oldlinks{$page}}) {
588                                         $link=bestlink($page, $link);
589                                         if (length $link &&
590                                             ! exists $links{$page} ||
591                                             ! grep { $_ eq $link } @{$links{$page}}) {
592                                                 $linkchanged{$link}=1;
593                                         }
594                                 }
595                         }
596                 }
597                 foreach my $link (keys %linkchanged) {
598                         my $linkfile=$pagesources{$link};
599                         if (defined $linkfile) {
600                                 debug("rendering $linkfile, to update its backlinks");
601                                 render($linkfile);
602                         }
603                 }
604         }
605 } #}}}
607 # Generates a C wrapper program for running ikiwiki in a specific way.
608 # The wrapper may be safely made suid.
609 sub gen_wrapper ($$) { #{{{
610         my ($svn, $rebuild)=@_;
612         eval q{use Cwd 'abs_path'};
613         $srcdir=abs_path($srcdir);
614         $destdir=abs_path($destdir);
615         my $this=abs_path($0);
616         if (! -x $this) {
617                 error("$this doesn't seem to be executable");
618         }
620         my @params=($srcdir, $templatedir, $destdir, "--wikiname=$wikiname");
621         push @params, "--verbose" if $verbose;
622         push @params, "--rebuild" if $rebuild;
623         push @params, "--nosvn" if !$svn;
624         push @params, "--cgi" if $cgi;
625         push @params, "--url=$url" if $url;
626         push @params, "--cgiurl=$cgiurl" if $cgiurl;
627         push @params, "--historyurl=$historyurl" if $historyurl;
628         push @params, "--anonok" if $anonok;
629         my $params=join(" ", @params);
630         my $call='';
631         foreach my $p ($this, $this, @params) {
632                 $call.=qq{"$p", };
633         }
634         $call.="NULL";
635         
636         my @envsave;
637         push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
638                        CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
639                        HTTP_COOKIE} if $cgi;
640         my $envsave="";
641         foreach my $var (@envsave) {
642                 $envsave.=<<"EOF"
643         if ((s=getenv("$var")))
644                 asprintf(&newenviron[i++], "%s=%s", "$var", s);
645 EOF
646         }
647         
648         open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
649         print OUT <<"EOF";
650 /* A wrapper for ikiwiki, can be safely made suid. */
651 #define _GNU_SOURCE
652 #include <stdio.h>
653 #include <unistd.h>
654 #include <stdlib.h>
655 #include <string.h>
657 extern char **environ;
659 int main (int argc, char **argv) {
660         /* Sanitize environment. */
661         char *s;
662         char *newenviron[$#envsave+3];
663         int i=0;
664 $envsave
665         newenviron[i++]="HOME=$ENV{HOME}";
666         newenviron[i]=NULL;
667         environ=newenviron;
669         if (argc == 2 && strcmp(argv[1], "--params") == 0) {
670                 printf("$params\\n");
671                 exit(0);
672         }
673         
674         execl($call);
675         perror("failed to run $this");
676         exit(1);
678 EOF
679         close OUT;
680         if (system("gcc", "ikiwiki-wrap.c", "-o", "ikiwiki-wrap") != 0) {
681                 error("failed to compile ikiwiki-wrap.c");
682         }
683         unlink("ikiwiki-wrap.c");
684         print "successfully generated ikiwiki-wrap\n";
685         exit 0;
686 } #}}}
687                 
688 sub misctemplate ($$) { #{{{
689         my $title=shift;
690         my $pagebody=shift;
691         
692         my $template=HTML::Template->new(
693                 filename => "$templatedir/misc.tmpl"
694         );
695         $template->param(
696                 title => $title,
697                 indexlink => indexlink(),
698                 wikiname => $wikiname,
699                 pagebody => $pagebody,
700         );
701         return $template->output;
702 }#}}}
704 sub cgi_recentchanges ($) { #{{{
705         my $q=shift;
706         
707         my $template=HTML::Template->new(
708                 filename => "$templatedir/recentchanges.tmpl"
709         );
710         $template->param(
711                 title => "RecentChanges",
712                 indexlink => indexlink(),
713                 wikiname => $wikiname,
714                 changelog => [rcs_recentchanges(100)],
715         );
716         print $q->header, $template->output;
717 } #}}}
719 sub userinfo_get ($$) { #{{
720         my $user=shift;
721         my $field=shift;
723         eval q{use Storable};
724         my $userdata=eval{ Storable::lock_retrieve("$srcdir/.ikiwiki/userdb") };
725         if (! defined $userdata || ! ref $userdata || 
726             ! exists $userdata->{$user} || ! ref $userdata->{$user}) {
727                 return "";
728         }
729         return $userdata->{$user}->{$field};
730 } #}}
732 sub userinfo_set ($$) { #{{
733         my $user=shift;
734         my $info=shift;
735         
736         eval q{use Storable};
737         my $userdata=eval{ Storable::lock_retrieve("$srcdir/.ikiwiki/userdb") };
738         if (! defined $userdata || ! ref $userdata) {
739                 $userdata={};
740         }
741         $userdata->{$user}=$info;
742         my $oldmask=umask(077);
743         my $ret=Storable::lock_store($userdata, "$srcdir/.ikiwiki/userdb");
744         umask($oldmask);
745         return $ret;
746 } #}}
748 sub cgi_signin ($$) { #{{{
749         my $q=shift;
750         my $session=shift;
752         eval q{use CGI::FormBuilder};
753         my $form = CGI::FormBuilder->new(
754                 title => "$wikiname signin",
755                 fields => [qw(do page name password confirm_password email)],
756                 header => 1,
757                 method => 'POST',
758                 validate => {
759                         confirm_password => {
760                                 perl => q{eq $form->field("password")},
761                         },
762                         email => 'EMAIL',
763                 },
764                 required => 'NONE',
765                 javascript => 0,
766                 params => $q,
767                 action => $q->request_uri,
768                 header => 0,
769                 template => (-e "$templatedir/signin.tmpl" ? "$templatedir/signin.tmpl" : "")
770         );
771         
772         $form->field(name => "name", required => 0);
773         $form->field(name => "do", type => "hidden");
774         $form->field(name => "page", type => "hidden");
775         $form->field(name => "password", type => "password", required => 0);
776         $form->field(name => "confirm_password", type => "password", required => 0);
777         $form->field(name => "email", required => 0);
778         if ($q->param("do") ne "signin") {
779                 $form->text("You need to log in before you can edit pages.");
780         }
781         
782         if ($form->submitted) {
783                 # Set required fields based on how form was submitted.
784                 my %required=(
785                         "Login" => [qw(name password)],
786                         "Register" => [qw(name password confirm_password email)],
787                         "Mail Password" => [qw(name)],
788                 );
789                 foreach my $opt (@{$required{$form->submitted}}) {
790                         $form->field(name => $opt, required => 1);
791                 }
792         
793                 # Validate password differently depending on how
794                 # form was submitted.
795                 if ($form->submitted eq 'Login') {
796                         $form->field(
797                                 name => "password",
798                                 validate => sub {
799                                         length $form->field("name") &&
800                                         shift eq userinfo_get($form->field("name"), 'password');
801                                 },
802                         );
803                         $form->field(name => "name", validate => '/^\w+$/');
804                 }
805                 else {
806                         $form->field(name => "password", validate => 'VALUE');
807                 }
808                 # And make sure the entered name exists when logging
809                 # in or sending email, and does not when registering.
810                 if ($form->submitted eq 'Register') {
811                         $form->field(
812                                 name => "name",
813                                 validate => sub {
814                                         my $name=shift;
815                                         length $name &&
816                                         ! userinfo_get($name, "regdate");
817                                 },
818                         );
819                 }
820                 else {
821                         $form->field(
822                                 name => "name",
823                                 validate => sub {
824                                         my $name=shift;
825                                         length $name &&
826                                         userinfo_get($name, "regdate");
827                                 },
828                         );
829                 }
830         }
831         else {
832                 # First time settings.
833                 $form->field(name => "name", comment => "use FirstnameLastName");
834                 $form->field(name => "confirm_password", comment => "(only needed");
835                 $form->field(name => "email",            comment => "for registration)");
836                 if ($session->param("name")) {
837                         $form->field(name => "name", value => $session->param("name"));
838                 }
839         }
841         if ($form->submitted && $form->validate) {
842                 if ($form->submitted eq 'Login') {
843                         $session->param("name", $form->field("name"));
844                         if (defined $form->field("do") && 
845                             $form->field("do") ne 'signin') {
846                                 print $q->redirect(
847                                         "$cgiurl?do=".$form->field("do").
848                                         "&page=".$form->field("page"));
849                         }
850                         else {
851                                 print $q->redirect($url);
852                         }
853                 }
854                 elsif ($form->submitted eq 'Register') {
855                         my $user_name=$form->field('name');
856                         if (userinfo_set($user_name, {
857                                            'email' => $form->field('email'),
858                                            'password' => $form->field('password'),
859                                            'regdate' => time
860                                          })) {
861                                 $form->field(name => "confirm_password", type => "hidden");
862                                 $form->field(name => "email", type => "hidden");
863                                 $form->text("Registration successful. Now you can Login.");
864                                 print $session->header();
865                                 print misctemplate($form->title, $form->render(submit => ["Login"]));
866                         }
867                         else {
868                                 error("Error saving registration.");
869                         }
870                 }
871                 elsif ($form->submitted eq 'Mail Password') {
872                         my $user_name=$form->field("name");
873                         my $template=HTML::Template->new(
874                                 filename => "$templatedir/passwordmail.tmpl"
875                         );
876                         $template->param(
877                                 user_name => $user_name,
878                                 user_password => userinfo_get($user_name, "password"),
879                                 wikiurl => $url,
880                                 wikiname => $wikiname,
881                                 REMOTE_ADDR => $ENV{REMOTE_ADDR},
882                         );
883                         
884                         eval q{use Mail::Sendmail};
885                         my ($fromhost) = $cgiurl =~ m!/([^/]+)!;
886                         print STDERR "$< $> >>> $cgiurl ".(getpwuid($>))[0]."@".$fromhost."\n";
887                         sendmail(
888                                 To => userinfo_get($user_name, "email"),
889                                 From => "$wikiname admin <".(getpwuid($>))[0]."@".$fromhost.">",
890                                 Subject => "$wikiname information",
891                                 Message => $template->output,
892                         ) or error("Failed to send mail");
893                         
894                         $form->text("Your password has been emailed to you.");
895                         $form->field(name => "name", required => 0);
896                         print $session->header();
897                         print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
898                 }
899         }
900         else {
901                 print $session->header();
902                 print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
903         }
904 } #}}}
906 sub cgi_editpage ($$) { #{{{
907         my $q=shift;
908         my $session=shift;
910         eval q{use CGI::FormBuilder};
911         my $form = CGI::FormBuilder->new(
912                 fields => [qw(do from page content comments)],
913                 header => 1,
914                 method => 'POST',
915                 validate => {},
916                 required => [qw{}],
917                 javascript => 0,
918                 params => $q,
919                 action => $q->request_uri,
920                 table => 0,
921                 template => "$templatedir/editpage.tmpl"
922         );
923         
924         my ($page)=$form->param('page')=~/$wiki_file_regexp/;
925         if (! defined $page || ! length $page || $page ne $q->param('page') ||
926             $page=~/$wiki_file_prune_regexp/ || $page=~/^\//) {
927                 error("bad page name");
928         }
929         $page=lc($page);
931         $form->field(name => "do", type => 'hidden');
932         $form->field(name => "from", type => 'hidden');
933         $form->field(name => "page", value => "$page", force => 1);
934         $form->field(name => "comments", type => "text", size => 80);
935         $form->field(name => "content", type => "textarea", rows => 20,
936                 cols => 80);
937         
938         if (! $form->submitted || ! $form->validate) {
939                 if ($form->field("do") eq "create") {
940                         if (exists $pagesources{lc($page)}) {
941                                 # hmm, someone else made the page in the
942                                 # meantime?
943                                 print $q->redirect("$url/".htmlpage($page));
944                                 return;
945                         }
946                         
947                         my @page_locs;
948                         my ($from)=$form->param('from')=~/$wiki_file_regexp/;
949                         if (! defined $from || ! length $from ||
950                             $from ne $form->param('from') ||
951                             $from=~/$wiki_file_prune_regexp/ || $from=~/^\//) {
952                                 @page_locs=$page;
953                         }
954                         else {
955                                 my $dir=$from."/";
956                                 $dir=~s![^/]+/$!!;
957                                 push @page_locs, $dir.$page;
958                                 push @page_locs, "$from/$page";
959                                 while (length $dir) {
960                                         $dir=~s![^/]+/$!!;
961                                         push @page_locs, $dir.$page;
962                                 }
963                         }
965                         $form->tmpl_param("page_select", 1);
966                         $form->field(name => "page", type => 'select',
967                                 options => \@page_locs);
968                         $form->title("creating $page");
969                 }
970                 elsif ($form->field("do") eq "edit") {
971                         my $content="";
972                         if (exists $pagesources{lc($page)}) {
973                                 $content=readfile("$srcdir/$pagesources{lc($page)}");
974                                 $content=~s/\n/\r\n/g;
975                         }
976                         $form->tmpl_param("page_select", 0);
977                         $form->field(name => "content", value => $content,
978                                 force => 1);
979                         $form->field(name => "page", type => 'hidden');
980                         $form->title("editing $page");
981                 }
982                 
983                 $form->tmpl_param("can_commit", $svn);
984                 $form->tmpl_param("indexlink", indexlink());
985                 print $form->render(submit => ["Save Page"]);
986         }
987         else {
988                 # save page
989                 my $file=$page.$default_pagetype;
990                 my $newfile=1;
991                 if (exists $pagesources{lc($page)}) {
992                         $file=$pagesources{lc($page)};
993                         $newfile=0;
994                 }
995                 
996                 my $content=$form->field('content');
997                 $content=~s/\r\n/\n/g;
998                 $content=~s/\r/\n/g;
999                 writefile("$srcdir/$file", $content);
1000                 
1001                 my $message="web commit ";
1002                 if ($session->param("name")) {
1003                         $message.="by ".$session->param("name");
1004                 }
1005                 else {
1006                         $message.="from $ENV{REMOTE_ADDR}";
1007                 }
1008                 if (defined $form->field('comments') &&
1009                     length $form->field('comments')) {
1010                         $message.=": ".$form->field('comments');
1011                 }
1012                 
1013                 if ($svn) {
1014                         if ($newfile) {
1015                                 rcs_add($file);
1016                         }
1017                         # presumably the commit will trigger an update
1018                         # of the wiki
1019                         rcs_commit($message);
1020                 }
1021                 else {
1022                         refresh();
1023                 }
1024                 
1025                 print $q->redirect("$url/".htmlpage($page));
1026         }
1027 } #}}}
1029 sub cgi () { #{{{
1030         eval q{use CGI};
1031         eval q{use CGI::Session};
1032         
1033         my $q=CGI->new;
1034         
1035         my $do=$q->param('do');
1036         if (! defined $do || ! length $do) {
1037                 error("\"do\" parameter missing");
1038         }
1039         
1040         # This does not need a session.
1041         if ($do eq 'recentchanges') {
1042                 cgi_recentchanges($q);
1043                 return;
1044         }
1045         
1046         CGI::Session->name("ikiwiki_session");
1048         my $oldmask=umask(077);
1049         my $session = CGI::Session->new("driver:db_file", $q,
1050                 { FileName => "$srcdir/.ikiwiki/sessions.db" });
1051         umask($oldmask);
1052         
1053         # Everything below this point needs the user to be signed in.
1054         if ((! $anonok && ! defined $session->param("name") ||
1055                 ! userinfo_get($session->param("name"), "regdate")) || $do eq 'signin') {
1056                 cgi_signin($q, $session);
1057         
1058                 # Force session flush with safe umask.
1059                 my $oldmask=umask(077);
1060                 $session->flush;
1061                 umask($oldmask);
1062                 
1063                 return;
1064         }
1065         
1066         if ($do eq 'create' || $do eq 'edit') {
1067                 cgi_editpage($q, $session);
1068         }
1069         else {
1070                 error("unknown do parameter");
1071         }
1072 } #}}}
1074 # main {{{
1075 my $rebuild=0;
1076 my $wrapper=0;
1077 if (grep /^-/, @ARGV) {
1078         eval {use Getopt::Long};
1079         GetOptions(
1080                 "wikiname=s" => \$wikiname,
1081                 "verbose|v" => \$verbose,
1082                 "rebuild" => \$rebuild,
1083                 "wrapper" => \$wrapper,
1084                 "svn!" => \$svn,
1085                 "anonok!" => \$anonok,
1086                 "cgi" => \$cgi,
1087                 "url=s" => \$url,
1088                 "cgiurl=s" => \$cgiurl,
1089                 "historyurl=s" => \$historyurl,
1090         ) || usage();
1092 usage() unless @ARGV == 3;
1093 ($srcdir) = possibly_foolish_untaint(shift);
1094 ($templatedir) = possibly_foolish_untaint(shift);
1095 ($destdir) = possibly_foolish_untaint(shift);
1097 if ($cgi && ! length $url) {
1098         error("Must specify url to wiki with --url when using --cgi");
1101 gen_wrapper($svn, $rebuild) if $wrapper;
1102 memoize('pagename');
1103 memoize('bestlink');
1104 loadindex() unless $rebuild;
1105 if ($cgi) {
1106         cgi();
1108 else {
1109         rcs_update() if $svn;
1110         refresh();
1111         saveindex();
1113 #}}}