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