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