]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - ikiwiki
fix
[git.ikiwiki.info.git] / ikiwiki
1 #!/usr/bin/perl -T
3 use warnings;
4 use strict;
5 use File::Find;
6 use Memoize;
7 use File::Spec;
8 use HTML::Template;
10 BEGIN {
11         $blosxom::version="is a proper perl module too much to ask?";
12         do "/usr/bin/markdown";
13 }
15 $ENV{PATH}="/usr/local/bin:/usr/bin:/bin";
16 my ($srcdir, $templatedir, $destdir, %links, %oldlinks, %oldpagemtime,
17     %renderedfiles, %pagesources);
18 my $wiki_link_regexp=qr/\[\[([^\s]+)\]\]/;
19 my $wiki_file_regexp=qr/(^[-A-Za-z0-9_.:\/+]+$)/;
20 my $wiki_file_prune_regexp=qr!((^|/).svn/|\.\.|^\.|\/\.|\.html?$)!;
21 my $verbose=0;
22 my $wikiname="wiki";
23 my $default_pagetype=".mdwn";
24 my $cgi=0;
25 my $url="";
26 my $cgiurl="";
27 my $historyurl="";
28 my $svn=1;
29 my $anonok=0;
31 sub usage { #{{{
32         die "usage: ikiwiki [options] source templates dest\n";
33 } #}}}
35 sub error ($) { #{{{
36         if ($cgi) {
37                 print "Content-type: text/html\n\n";
38                 print misctemplate("Error", "<p>Error: @_</p>");
39                 exit 1;
40         }
41         else {
42                 die @_;
43         }
44 } #}}}
46 sub debug ($) { #{{{
47         if (! $cgi) {
48                 print "@_\n" if $verbose;
49         }
50         else {
51                 print STDERR "@_\n" if $verbose;
52         }
53 } #}}}
55 sub mtime ($) { #{{{
56         my $page=shift;
57         
58         return (stat($page))[9];
59 } #}}}
61 sub possibly_foolish_untaint ($) { #{{{
62         my $tainted=shift;
63         my ($untainted)=$tainted=~/(.*)/;
64         return $untainted;
65 } #}}}
67 sub basename ($) { #{{{
68         my $file=shift;
70         $file=~s!.*/!!;
71         return $file;
72 } #}}}
74 sub dirname ($) { #{{{
75         my $file=shift;
77         $file=~s!/?[^/]+$!!;
78         return $file;
79 } #}}}
81 sub pagetype ($) { #{{{
82         my $page=shift;
83         
84         if ($page =~ /\.mdwn$/) {
85                 return ".mdwn";
86         }
87         else {
88                 return "unknown";
89         }
90 } #}}}
92 sub pagename ($) { #{{{
93         my $file=shift;
95         my $type=pagetype($file);
96         my $page=$file;
97         $page=~s/\Q$type\E*$// unless $type eq 'unknown';
98         return $page;
99 } #}}}
101 sub htmlpage ($) { #{{{
102         my $page=shift;
104         return $page.".html";
105 } #}}}
107 sub readfile ($) { #{{{
108         my $file=shift;
110         local $/=undef;
111         open (IN, "$file") || error("failed to read $file: $!");
112         my $ret=<IN>;
113         close IN;
114         return $ret;
115 } #}}}
117 sub writefile ($$) { #{{{
118         my $file=shift;
119         my $content=shift;
121         my $dir=dirname($file);
122         if (! -d $dir) {
123                 print STDERR ">>$dir<<\n";
124                 my $d="";
125                 foreach my $s (split(m!/+!, $dir)) {
126                         $d.="$s/";
127                         if (! -d $d) {
128                                 mkdir($d) || error("failed to create directory $d: $!");
129                         }
130                 }
131         }
132         
133         open (OUT, ">$file") || error("failed to write $file: $!");
134         print OUT $content;
135         close OUT;
136 } #}}}
138 sub findlinks ($) { #{{{
139         my $content=shift;
141         my @links;
142         while ($content =~ /$wiki_link_regexp/g) {
143                 push @links, lc($1);
144         }
145         return @links;
146 } #}}}
148 # Given a page and the text of a link on the page, determine which existing
149 # page that link best points to. Prefers pages under a subdirectory with
150 # the same name as the source page, failing that goes down the directory tree
151 # to the base looking for matching pages.
152 sub bestlink ($$) { #{{{
153         my $page=shift;
154         my $link=lc(shift);
155         
156         my $cwd=$page;
157         do {
158                 my $l=$cwd;
159                 $l.="/" if length $l;
160                 $l.=$link;
162                 if (exists $links{$l}) {
163                         #debug("for $page, \"$link\", use $l");
164                         return $l;
165                 }
166         } while $cwd=~s!/?[^/]+$!!;
168         #print STDERR "warning: page $page, broken link: $link\n";
169         return "";
170 } #}}}
172 sub isinlinableimage ($) { #{{{
173         my $file=shift;
174         
175         $file=~/\.(png|gif|jpg|jpeg)$/;
176 } #}}}
178 sub htmllink { #{{{
179         my $page=shift;
180         my $link=shift;
181         my $noimagelink=shift;
183         my $bestlink=bestlink($page, $link);
185         return $link if $page eq $bestlink;
186         
187         # TODO BUG: %renderedfiles may not have it, if the linked to page
188         # was also added and isn't yet rendered! Note that this bug is
189         # masked by the bug mentioned below that makes all new files
190         # be rendered twice.
191         if (! grep { $_ eq $bestlink } values %renderedfiles) {
192                 $bestlink=htmlpage($bestlink);
193         }
194         if (! grep { $_ eq $bestlink } values %renderedfiles) {
195                 return "<a href=\"$cgiurl?do=create&page=$link&from=$page\">?</a>$link"
196         }
197         
198         $bestlink=File::Spec->abs2rel($bestlink, dirname($page));
199         
200         if (! $noimagelink && isinlinableimage($bestlink)) {
201                 return "<img src=\"$bestlink\">";
202         }
203         return "<a href=\"$bestlink\">$link</a>";
204 } #}}}
206 sub linkify ($$) { #{{{
207         my $content=shift;
208         my $file=shift;
210         $content =~ s/$wiki_link_regexp/htmllink(pagename($file), $1)/eg;
211         
212         return $content;
213 } #}}}
215 sub htmlize ($$) { #{{{
216         my $type=shift;
217         my $content=shift;
218         
219         if ($type eq '.mdwn') {
220                 return Markdown::Markdown($content);
221         }
222         else {
223                 error("htmlization of $type not supported");
224         }
225 } #}}}
227 sub backlinks ($) { #{{{
228         my $page=shift;
230         my @links;
231         foreach my $p (keys %links) {
232                 next if bestlink($page, $p) eq $page;
233                 if (grep { length $_ && bestlink($p, $_) eq $page } @{$links{$p}}) {
234                         my $href=File::Spec->abs2rel(htmlpage($p), dirname($page));
235                         
236                         # Trim common dir prefixes from both pages.
237                         my $p_trimmed=$p;
238                         my $page_trimmed=$page;
239                         my $dir;
240                         1 while (($dir)=$page_trimmed=~m!^([^/]+/)!) &&
241                                 defined $dir &&
242                                 $p_trimmed=~s/^\Q$dir\E// &&
243                                 $page_trimmed=~s/^\Q$dir\E//;
244                                        
245                         push @links, { url => $href, page => $p_trimmed };
246                 }
247         }
249         # TODO sort by page name
250         return @links;
251 } #}}}
252         
253 sub parentlinks ($) { #{{{
254         my $page=shift;
255         
256         my @ret;
257         my $pagelink="";
258         my $path="";
259         my $skip=1;
260         foreach my $dir (reverse split("/", $page)) {
261                 if (! $skip) {
262                         unshift @ret, { url => "$path$dir.html", page => $dir };
263                 }
264                 else {
265                         $skip=0;
266                 }
267                 $path.="../";
268         }
269         unshift @ret, { url => $path , page => $wikiname };
270         return @ret;
271 } #}}}
273 sub indexlink () { #{{{
274         return "<a href=\"$url\">$wikiname</a>";
275 } #}}}
276         
277 sub finalize ($$) { #{{{
278         my $content=shift;
279         my $page=shift;
281         my $title=basename($page);
282         $title=~s/_/ /g;
283         
284         my $template=HTML::Template->new(blind_cache => 1,
285                 filename => "$templatedir/page.tmpl");
286         
287         if (length $cgiurl) {
288                 $template->param(editurl => "$cgiurl?do=edit&page=$page");
289                 if ($svn) {
290                         $template->param(recentchangesurl => "$cgiurl?do=recentchanges");
291                 }
292         }
294         if (length $historyurl) {
295                 my $u=$historyurl;
296                 $u=~s/\[\[\]\]/$pagesources{$page}/g;
297                 $template->param(historyurl => $u);
298         }
299         
300         $template->param(
301                 title => $title,
302                 wikiname => $wikiname,
303                 parentlinks => [parentlinks($page)],
304                 content => $content,
305                 backlinks => [backlinks($page)],
306         );
307         
308         return $template->output;
309 } #}}}
311 sub render ($) { #{{{
312         my $file=shift;
313         
314         my $type=pagetype($file);
315         my $content=readfile("$srcdir/$file");
316         if ($type ne 'unknown') {
317                 my $page=pagename($file);
318                 
319                 $links{$page}=[findlinks($content)];
320                 
321                 $content=linkify($content, $file);
322                 $content=htmlize($type, $content);
323                 $content=finalize($content, $page);
324                 
325                 writefile("$destdir/".htmlpage($page), $content);
326                 $oldpagemtime{$page}=time;
327                 $renderedfiles{$page}=htmlpage($page);
328         }
329         else {
330                 $links{$file}=[];
331                 writefile("$destdir/$file", $content);
332                 $oldpagemtime{$file}=time;
333                 $renderedfiles{$file}=$file;
334         }
335 } #}}}
337 sub loadindex () { #{{{
338         open (IN, "$srcdir/.ikiwiki/index") || return;
339         while (<IN>) {
340                 $_=possibly_foolish_untaint($_);
341                 chomp;
342                 my ($mtime, $file, $rendered, @links)=split(' ', $_);
343                 my $page=pagename($file);
344                 $pagesources{$page}=$file;
345                 $oldpagemtime{$page}=$mtime;
346                 $oldlinks{$page}=[@links];
347                 $links{$page}=[@links];
348                 $renderedfiles{$page}=$rendered;
349         }
350         close IN;
351 } #}}}
353 sub saveindex () { #{{{
354         if (! -d "$srcdir/.ikiwiki") {
355                 mkdir("$srcdir/.ikiwiki");
356         }
357         open (OUT, ">$srcdir/.ikiwiki/index") || error("cannot write to index: $!");
358         foreach my $page (keys %oldpagemtime) {
359                 print OUT "$oldpagemtime{$page} $pagesources{$page} $renderedfiles{$page} ".
360                         join(" ", @{$links{$page}})."\n"
361                                 if $oldpagemtime{$page};
362         }
363         close OUT;
364 } #}}}
366 sub rcs_update () { #{{{
367         if (-d "$srcdir/.svn") {
368                 if (system("svn", "update", "--quiet", $srcdir) != 0) {
369                         warn("svn update failed\n");
370                 }
371         }
372 } #}}}
374 sub rcs_commit ($) { #{{{
375         my $message=shift;
377         if (-d "$srcdir/.svn") {
378                 if (system("svn", "commit", "--quiet", "-m",
379                            possibly_foolish_untaint($message), $srcdir) != 0) {
380                         warn("svn commit failed\n");
381                 }
382         }
383 } #}}}
385 sub rcs_add ($) { #{{{
386         my $file=shift;
388         if (-d "$srcdir/.svn") {
389                 my $parent=dirname($file);
390                 while (! -d "$srcdir/$parent/.svn") {
391                         $file=$parent;
392                         $parent=dirname($file);
393                 }
394                 
395                 if (system("svn", "add", "--quiet", "$srcdir/$file") != 0) {
396                         warn("svn add failed\n");
397                 }
398         }
399 } #}}}
401 sub rcs_recentchanges ($) { #{{{
402         my $num=shift;
403         my @ret;
404         
405         eval q{use Date::Parse};
406         eval q{use Time::Duration};
407         
408         if (-d "$srcdir/.svn") {
409                 my $info=`LANG=C svn info $srcdir`;
410                 my ($svn_url)=$info=~/^URL: (.*)$/m;
412                 # FIXME: currently assumes that the wiki is somewhere
413                 # under trunk in svn, doesn't support other layouts.
414                 my ($svn_base)=$svn_url=~m!(/trunk(?:/.*)?)$!;
415                 
416                 my $div=qr/^--------------------+$/;
417                 my $infoline=qr/^r(\d+)\s+\|\s+([^\s]+)\s+\|\s+(\d+-\d+-\d+\s+\d+:\d+:\d+\s+[-+]?\d+).*/;
418                 my $state='start';
419                 my ($rev, $user, $when, @pages, @message);
420                 foreach (`LANG=C svn log -v '$svn_url'`) {
421                         chomp;
422                         if ($state eq 'start' && /$div/) {
423                                 $state='header';
424                         }
425                         elsif ($state eq 'header' && /$infoline/) {
426                                 $rev=$1;
427                                 $user=$2;
428                                 $when=concise(ago(time - str2time($3)));
429                         }
430                         elsif ($state eq 'header' && /^\s+[A-Z]\s+\Q$svn_base\E\/(.+)$/) {
431                                 push @pages, { link => htmllink("", pagename($1), 1) }
432                                         if length $1;
433                         }
434                         elsif ($state eq 'header' && /^$/) {
435                                 $state='body';
436                         }
437                         elsif ($state eq 'body' && /$div/) {
438                                 push @ret, { rev => $rev, user => $user,
439                                         when => $when, message => [@message],
440                                         pages => [@pages] } if @pages;
441                                 return @ret if @ret >= $num;
442                                 
443                                 $state='header';
444                                 $rev=$user=$when=undef;
445                                 @pages=@message=();
446                         }
447                         elsif ($state eq 'body') {
448                                 push @message, {line => $_},
449                         }
450                 }
451         }
453         return @ret;
454 } #}}}
456 sub prune ($) { #{{{
457         my $file=shift;
459         unlink($file);
460         my $dir=dirname($file);
461         while (rmdir($dir)) {
462                 $dir=dirname($dir);
463         }
464 } #}}}
466 sub refresh () { #{{{
467         # Find existing pages.
468         my %exists;
469         my @files;
470         find({
471                 no_chdir => 1,
472                 wanted => sub {
473                         if (/$wiki_file_prune_regexp/) {
474                                 $File::Find::prune=1;
475                         }
476                         elsif (! -d $_) {
477                                 my ($f)=/$wiki_file_regexp/; # untaint
478                                 if (! defined $f) {
479                                         warn("skipping bad filename $_\n");
480                                 }
481                                 else {
482                                         $f=~s/^\Q$srcdir\E\/?//;
483                                         push @files, $f;
484                                         $exists{pagename($f)}=1;
485                                 }
486                         }
487                 },
488         }, $srcdir);
490         my %rendered;
492         # check for added or removed pages
493         my @add;
494         foreach my $file (@files) {
495                 my $page=pagename($file);
496                 if (! $oldpagemtime{$page}) {
497                         debug("new page $page");
498                         push @add, $file;
499                         $links{$page}=[];
500                         $pagesources{$page}=$file;
501                 }
502         }
503         my @del;
504         foreach my $page (keys %oldpagemtime) {
505                 if (! $exists{$page}) {
506                         debug("removing old page $page");
507                         push @del, $renderedfiles{$page};
508                         prune($destdir."/".$renderedfiles{$page});
509                         delete $renderedfiles{$page};
510                         $oldpagemtime{$page}=0;
511                         delete $pagesources{$page};
512                 }
513         }
514         
515         # render any updated files
516         foreach my $file (@files) {
517                 my $page=pagename($file);
518                 
519                 if (! exists $oldpagemtime{$page} ||
520                     mtime("$srcdir/$file") > $oldpagemtime{$page}) {
521                         debug("rendering changed file $file");
522                         render($file);
523                         $rendered{$file}=1;
524                 }
525         }
526         
527         # if any files were added or removed, check to see if each page
528         # needs an update due to linking to them
529         # TODO: inefficient; pages may get rendered above and again here;
530         # problem is the bestlink may have changed and we won't know until
531         # now
532         if (@add || @del) {
533 FILE:           foreach my $file (@files) {
534                         my $page=pagename($file);
535                         foreach my $f (@add, @del) {
536                                 my $p=pagename($f);
537                                 foreach my $link (@{$links{$page}}) {
538                                         if (bestlink($page, $link) eq $p) {
539                                                 debug("rendering $file, which links to $p");
540                                                 render($file);
541                                                 $rendered{$file}=1;
542                                                 next FILE;
543                                         }
544                                 }
545                         }
546                 }
547         }
549         # handle backlinks; if a page has added/removed links, update the
550         # pages it links to
551         # TODO: inefficient; pages may get rendered above and again here;
552         # problem is the backlinks could be wrong in the first pass render
553         # above
554         if (%rendered) {
555                 my %linkchanged;
556                 foreach my $file (keys %rendered, @del) {
557                         my $page=pagename($file);
558                         if (exists $links{$page}) {
559                                 foreach my $link (@{$links{$page}}) {
560                                         $link=bestlink($page, $link);
561                                         if (length $link &&
562                                             ! exists $oldlinks{$page} ||
563                                             ! grep { $_ eq $link } @{$oldlinks{$page}}) {
564                                                 $linkchanged{$link}=1;
565                                         }
566                                 }
567                         }
568                         if (exists $oldlinks{$page}) {
569                                 foreach my $link (@{$oldlinks{$page}}) {
570                                         $link=bestlink($page, $link);
571                                         if (length $link &&
572                                             ! exists $links{$page} ||
573                                             ! grep { $_ eq $link } @{$links{$page}}) {
574                                                 $linkchanged{$link}=1;
575                                         }
576                                 }
577                         }
578                 }
579                 foreach my $link (keys %linkchanged) {
580                         my $linkfile=$pagesources{$link};
581                         if (defined $linkfile) {
582                                 debug("rendering $linkfile, to update its backlinks");
583                                 render($linkfile);
584                         }
585                 }
586         }
587 } #}}}
589 # Generates a C wrapper program for running ikiwiki in a specific way.
590 # The wrapper may be safely made suid.
591 sub gen_wrapper ($$) { #{{{
592         my ($svn, $rebuild)=@_;
594         eval q{use Cwd 'abs_path'};
595         $srcdir=abs_path($srcdir);
596         $destdir=abs_path($destdir);
597         my $this=abs_path($0);
598         if (! -x $this) {
599                 error("$this doesn't seem to be executable");
600         }
602         my @params=($srcdir, $templatedir, $destdir, "--wikiname=$wikiname");
603         push @params, "--verbose" if $verbose;
604         push @params, "--rebuild" if $rebuild;
605         push @params, "--nosvn" if !$svn;
606         push @params, "--cgi" if $cgi;
607         push @params, "--url=$url" if $url;
608         push @params, "--cgiurl=$cgiurl" if $cgiurl;
609         push @params, "--historyurl=$historyurl" if $historyurl;
610         push @params, "--anonok" if $anonok;
611         my $params=join(" ", @params);
612         my $call='';
613         foreach my $p ($this, $this, @params) {
614                 $call.=qq{"$p", };
615         }
616         $call.="NULL";
617         
618         my @envsave;
619         push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
620                        CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
621                        HTTP_COOKIE} if $cgi;
622         my $envsave="";
623         foreach my $var (@envsave) {
624                 $envsave.=<<"EOF"
625         if ((s=getenv("$var")))
626                 asprintf(&newenviron[i++], "%s=%s", "$var", s);
627 EOF
628         }
629         
630         open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
631         print OUT <<"EOF";
632 /* A wrapper for ikiwiki, can be safely made suid. */
633 #define _GNU_SOURCE
634 #include <stdio.h>
635 #include <unistd.h>
636 #include <stdlib.h>
637 #include <string.h>
639 extern char **environ;
641 int main (int argc, char **argv) {
642         /* Sanitize environment. */
643         char *s;
644         char *newenviron[$#envsave+3];
645         int i=0;
646 $envsave
647         newenviron[i++]="HOME=$ENV{HOME}";
648         newenviron[i]=NULL;
649         environ=newenviron;
651         if (argc == 2 && strcmp(argv[1], "--params") == 0) {
652                 printf("$params\\n");
653                 exit(0);
654         }
655         
656         execl($call);
657         perror("failed to run $this");
658         exit(1);
660 EOF
661         close OUT;
662         if (system("gcc", "ikiwiki-wrap.c", "-o", "ikiwiki-wrap") != 0) {
663                 error("failed to compile ikiwiki-wrap.c");
664         }
665         unlink("ikiwiki-wrap.c");
666         print "successfully generated ikiwiki-wrap\n";
667         exit 0;
668 } #}}}
669                 
670 sub misctemplate ($$) { #{{{
671         my $title=shift;
672         my $pagebody=shift;
673         
674         my $template=HTML::Template->new(
675                 filename => "$templatedir/misc.tmpl");
676         $template->param(
677                 title => $title,
678                 indexlink => indexlink(),
679                 wikiname => $wikiname,
680                 pagebody => $pagebody,
681         );
682         return $template->output;
683 }#}}}
685 sub cgi_recentchanges ($) { #{{{
686         my $q=shift;
687         
688         my $template=HTML::Template->new(
689                 filename => "$templatedir/recentchanges.tmpl");
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 } #}}}
699 sub cgi_signin ($$) { #{{{
700         my $q=shift;
701         my $session=shift;
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         }
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 } #}}}
804 sub cgi_editpage ($$) { #{{{
805         my $q=shift;
806         my $session=shift;
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);
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                         }
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 } #}}}
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 } #}}}
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();
979 usage() unless @ARGV == 3;
980 ($srcdir) = possibly_foolish_untaint(shift);
981 ($templatedir) = possibly_foolish_untaint(shift);
982 ($destdir) = possibly_foolish_untaint(shift);
984 if ($cgi && ! length $url) {
985         error("Must specify url to wiki with --url when using --cgi");
988 gen_wrapper($svn, $rebuild) if $wrapper;
989 memoize('pagename');
990 memoize('bestlink');
991 loadindex() unless $rebuild;
992 if ($cgi) {
993         cgi();
995 else {
996         rcs_update() if $svn;
997         refresh();
998         saveindex();
1000 #}}}