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