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