11 $blosxom::version="is a proper perl module too much to ask?";
12 do "/usr/bin/markdown";
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?$)!;
23 my $default_pagetype=".mdwn";
32 die "usage: ikiwiki [options] source templates dest\n";
37 print "Content-type: text/html\n\n";
38 print misctemplate("Error", "<p>Error: @_</p>");
48 print "@_\n" if $verbose;
51 print STDERR "@_\n" if $verbose;
58 return (stat($page))[9];
61 sub possibly_foolish_untaint ($) { #{{{
63 my ($untainted)=$tainted=~/(.*)/;
67 sub basename ($) { #{{{
74 sub dirname ($) { #{{{
81 sub pagetype ($) { #{{{
84 if ($page =~ /\.mdwn$/) {
92 sub pagename ($) { #{{{
95 my $type=pagetype($file);
97 $page=~s/\Q$type\E*$// unless $type eq 'unknown';
101 sub htmlpage ($) { #{{{
104 return $page.".html";
107 sub readfile ($) { #{{{
111 open (IN, "$file") || error("failed to read $file: $!");
117 sub writefile ($$) { #{{{
121 my $dir=dirname($file);
123 print STDERR ">>$dir<<\n";
125 foreach my $s (split(m!/+!, $dir)) {
128 mkdir($d) || error("failed to create directory $d: $!");
133 open (OUT, ">$file") || error("failed to write $file: $!");
138 sub findlinks ($) { #{{{
142 while ($content =~ /$wiki_link_regexp/g) {
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 ($$) { #{{{
159 $l.="/" if length $l;
162 if (exists $links{$l}) {
163 #debug("for $page, \"$link\", use $l");
166 } while $cwd=~s!/?[^/]+$!!;
168 #print STDERR "warning: page $page, broken link: $link\n";
172 sub isinlinableimage ($) { #{{{
175 $file=~/\.(png|gif|jpg|jpeg)$/;
181 my $noimagelink=shift;
183 my $bestlink=bestlink($page, $link);
185 return $link if $page eq $bestlink;
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
191 if (! grep { $_ eq $bestlink } values %renderedfiles) {
192 $bestlink=htmlpage($bestlink);
194 if (! grep { $_ eq $bestlink } values %renderedfiles) {
195 return "<a href=\"$cgiurl?do=create&page=$link&from=$page\">?</a>$link"
198 $bestlink=File::Spec->abs2rel($bestlink, dirname($page));
200 if (! $noimagelink && isinlinableimage($bestlink)) {
201 return "<img src=\"$bestlink\">";
203 return "<a href=\"$bestlink\">$link</a>";
206 sub linkify ($$) { #{{{
210 $content =~ s/$wiki_link_regexp/htmllink(pagename($file), $1)/eg;
215 sub htmlize ($$) { #{{{
219 if ($type eq '.mdwn') {
220 return Markdown::Markdown($content);
223 error("htmlization of $type not supported");
227 sub backlinks ($) { #{{{
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));
236 # Trim common dir prefixes from both pages.
238 my $page_trimmed=$page;
240 1 while (($dir)=$page_trimmed=~m!^([^/]+/)!) &&
242 $p_trimmed=~s/^\Q$dir\E// &&
243 $page_trimmed=~s/^\Q$dir\E//;
245 push @links, { url => $href, page => $p_trimmed };
249 # TODO sort by page name
253 sub parentlinks ($) { #{{{
260 foreach my $dir (reverse split("/", $page)) {
262 unshift @ret, { url => "$path$dir.html", page => $dir };
269 unshift @ret, { url => $path , page => $wikiname };
273 sub indexlink () { #{{{
274 return "<a href=\"$url\">$wikiname</a>";
277 sub finalize ($$) { #{{{
281 my $title=basename($page);
284 my $template=HTML::Template->new(blind_cache => 1,
285 filename => "$templatedir/page.tmpl");
287 if (length $cgiurl) {
288 $template->param(editurl => "$cgiurl?do=edit&page=$page");
290 $template->param(recentchangesurl => "$cgiurl?do=recentchanges");
294 if (length $historyurl) {
296 $u=~s/\[\[\]\]/$pagesources{$page}/g;
297 $template->param(historyurl => $u);
302 wikiname => $wikiname,
303 parentlinks => [parentlinks($page)],
305 backlinks => [backlinks($page)],
308 return $template->output;
311 sub render ($) { #{{{
314 my $type=pagetype($file);
315 my $content=readfile("$srcdir/$file");
316 if ($type ne 'unknown') {
317 my $page=pagename($file);
319 $links{$page}=[findlinks($content)];
321 $content=linkify($content, $file);
322 $content=htmlize($type, $content);
323 $content=finalize($content, $page);
325 writefile("$destdir/".htmlpage($page), $content);
326 $oldpagemtime{$page}=time;
327 $renderedfiles{$page}=htmlpage($page);
331 writefile("$destdir/$file", $content);
332 $oldpagemtime{$file}=time;
333 $renderedfiles{$file}=$file;
337 sub loadindex () { #{{{
338 open (IN, "$srcdir/.ikiwiki/index") || return;
340 $_=possibly_foolish_untaint($_);
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;
353 sub saveindex () { #{{{
354 if (! -d "$srcdir/.ikiwiki") {
355 mkdir("$srcdir/.ikiwiki");
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};
366 sub rcs_update () { #{{{
367 if (-d "$srcdir/.svn") {
368 if (system("svn", "update", "--quiet", $srcdir) != 0) {
369 warn("svn update failed\n");
374 sub rcs_commit ($) { #{{{
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");
385 sub rcs_add ($) { #{{{
388 if (-d "$srcdir/.svn") {
389 my $parent=dirname($file);
390 while (! -d "$srcdir/$parent/.svn") {
392 $parent=dirname($file);
395 if (system("svn", "add", "--quiet", "$srcdir/$file") != 0) {
396 warn("svn add failed\n");
401 sub rcs_recentchanges ($) { #{{{
405 eval q{use Date::Parse};
406 eval q{use Time::Duration};
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(?:/.*)?)$!;
416 my $div=qr/^--------------------+$/;
417 my $infoline=qr/^r(\d+)\s+\|\s+([^\s]+)\s+\|\s+(\d+-\d+-\d+\s+\d+:\d+:\d+\s+[-+]?\d+).*/;
419 my ($rev, $user, $when, @pages, @message);
420 foreach (`LANG=C svn log -v '$svn_url'`) {
422 if ($state eq 'start' && /$div/) {
425 elsif ($state eq 'header' && /$infoline/) {
428 $when=concise(ago(time - str2time($3)));
430 elsif ($state eq 'header' && /^\s+[A-Z]\s+\Q$svn_base\E\/(.+)$/) {
431 push @pages, { link => htmllink("", pagename($1), 1) }
434 elsif ($state eq 'header' && /^$/) {
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;
444 $rev=$user=$when=undef;
447 elsif ($state eq 'body') {
448 push @message, {line => $_},
460 my $dir=dirname($file);
461 while (rmdir($dir)) {
466 sub refresh () { #{{{
467 # Find existing pages.
473 if (/$wiki_file_prune_regexp/) {
474 $File::Find::prune=1;
477 my ($f)=/$wiki_file_regexp/; # untaint
479 warn("skipping bad filename $_\n");
482 $f=~s/^\Q$srcdir\E\/?//;
484 $exists{pagename($f)}=1;
492 # check for added or removed pages
494 foreach my $file (@files) {
495 my $page=pagename($file);
496 if (! $oldpagemtime{$page}) {
497 debug("new page $page");
500 $pagesources{$page}=$file;
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};
515 # render any updated files
516 foreach my $file (@files) {
517 my $page=pagename($file);
519 if (! exists $oldpagemtime{$page} ||
520 mtime("$srcdir/$file") > $oldpagemtime{$page}) {
521 debug("rendering changed file $file");
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
533 FILE: foreach my $file (@files) {
534 my $page=pagename($file);
535 foreach my $f (@add, @del) {
537 foreach my $link (@{$links{$page}}) {
538 if (bestlink($page, $link) eq $p) {
539 debug("rendering $file, which links to $p");
549 # handle backlinks; if a page has added/removed links, update the
551 # TODO: inefficient; pages may get rendered above and again here;
552 # problem is the backlinks could be wrong in the first pass render
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);
562 ! exists $oldlinks{$page} ||
563 ! grep { $_ eq $link } @{$oldlinks{$page}}) {
564 $linkchanged{$link}=1;
568 if (exists $oldlinks{$page}) {
569 foreach my $link (@{$oldlinks{$page}}) {
570 $link=bestlink($page, $link);
572 ! exists $links{$page} ||
573 ! grep { $_ eq $link } @{$links{$page}}) {
574 $linkchanged{$link}=1;
579 foreach my $link (keys %linkchanged) {
580 my $linkfile=$pagesources{$link};
581 if (defined $linkfile) {
582 debug("rendering $linkfile, to update its backlinks");
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);
599 error("$this doesn't seem to be executable");
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);
613 foreach my $p ($this, $this, @params) {
619 push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
620 CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
621 HTTP_COOKIE} if $cgi;
623 foreach my $var (@envsave) {
625 if ((s=getenv("$var")))
626 asprintf(&newenviron[i++], "%s=%s", "$var", s);
630 open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
632 /* A wrapper for ikiwiki, can be safely made suid. */
639 extern char **environ;
641 int main (int argc, char **argv) {
642 /* Sanitize environment. */
644 char *newenviron[$#envsave+3];
647 newenviron[i++]="HOME=$ENV{HOME}";
651 if (argc == 2 && strcmp(argv[1], "--params") == 0) {
652 printf("$params\\n");
657 perror("failed to run $this");
662 if (system("gcc", "ikiwiki-wrap.c", "-o", "ikiwiki-wrap") != 0) {
663 error("failed to compile ikiwiki-wrap.c");
665 unlink("ikiwiki-wrap.c");
666 print "successfully generated ikiwiki-wrap\n";
670 sub misctemplate ($$) { #{{{
674 my $template=HTML::Template->new(
675 filename => "$templatedir/misc.tmpl");
678 indexlink => indexlink(),
679 wikiname => $wikiname,
680 pagebody => $pagebody,
682 return $template->output;
685 sub cgi_recentchanges ($) { #{{{
688 my $template=HTML::Template->new(
689 filename => "$templatedir/recentchanges.tmpl");
691 title => "RecentChanges",
692 indexlink => indexlink(),
693 wikiname => $wikiname,
694 changelog => [rcs_recentchanges(100)],
696 print $q->header, $template->output;
699 sub cgi_signin ($$) { #{{{
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)],
711 confirm_password => {
712 perl => q{eq $form->field("password")},
719 action => $q->request_uri,
721 template => (-e "$templatedir/signin.tmpl" ? "$templatedir/signin.tmpl" : "")
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"));
733 if ($q->param("do") ne "signin") {
734 $form->text("You need to log in before you can edit pages.");
737 if ($form->submitted) {
738 # Set required fields based on how form was submitted.
740 "Login" => [qw(name password)],
741 "Register" => [qw(name password confirm_password email)],
742 "Mail Password" => [qw(name)],
744 foreach my $opt (@{$required{$form->submitted}}) {
745 $form->field(name => $opt, required => 1);
748 # Validate password differently depending on how form was
750 if ($form->submitted eq 'Login') {
754 # TODO get real user password
760 $form->field(name => "password", validate => 'VALUE');
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)");
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') {
776 "$cgiurl?do=".$form->field("do").
777 "&page=".$form->field("page"));
780 print $q->redirect($url);
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"]));
791 elsif ($form->submitted eq '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"]));
799 print $session->header();
800 print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
804 sub cgi_editpage ($$) { #{{{
808 eval q{use CGI::FormBuilder};
809 my $form = CGI::FormBuilder->new(
810 fields => [qw(do from page content comments)],
817 action => $q->request_uri,
819 template => "$templatedir/editpage.tmpl"
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");
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,
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
841 print $q->redirect("$url/".htmlpage($page));
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=~/^\//) {
855 push @page_locs, $dir.$page;
856 push @page_locs, "$from/$page";
857 while (length $dir) {
859 push @page_locs, $dir.$page;
863 $form->tmpl_param("page_select", 1);
864 $form->field(name => "page", type => 'select',
865 options => \@page_locs);
866 $form->title("creating $page");
868 elsif ($form->field("do") eq "edit") {
870 if (exists $pagesources{lc($page)}) {
871 $content=readfile("$srcdir/$pagesources{lc($page)}");
872 $content=~s/\n/\r\n/g;
874 $form->tmpl_param("page_select", 0);
875 $form->field(name => "content", value => $content,
877 $form->field(name => "page", type => 'hidden');
878 $form->title("editing $page");
881 $form->tmpl_param("can_commit", $svn);
882 $form->tmpl_param("indexlink", indexlink());
883 print $form->render(submit => ["Save Page"]);
887 my $file=$page.$default_pagetype;
889 if (exists $pagesources{lc($page)}) {
890 $file=$pagesources{lc($page)};
894 my $content=$form->field('content');
895 $content=~s/\r\n/\n/g;
897 writefile("$srcdir/$file", $content);
899 my $message="web commit ";
900 if ($session->param("name")) {
901 $message.="by ".$session->param("name");
904 $message.="from $ENV{REMOTE_ADDR}";
906 if (length $form->field('comments')) {
907 $message.=": ".$form->field('comments');
914 # presumably the commit will trigger an update
916 rcs_commit($message);
922 print $q->redirect("$url/".htmlpage($page));
928 eval q{use CGI::Session};
932 my $do=$q->param('do');
933 if (! defined $do || ! length $do) {
934 error("\"do\" parameter missing");
937 # This does not need a session.
938 if ($do eq 'recentchanges') {
939 cgi_recentchanges($q);
943 CGI::Session->name("ikiwiki_session");
944 my $session = CGI::Session->new(undef, $q,
945 { Directory=> "$srcdir/.ikiwiki/sessions" });
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);
953 if ($do eq 'create' || $do eq 'edit') {
954 cgi_editpage($q, $session);
957 error("unknown do parameter");
964 if (grep /^-/, @ARGV) {
965 eval {use Getopt::Long};
967 "wikiname=s" => \$wikiname,
968 "verbose|v" => \$verbose,
969 "rebuild" => \$rebuild,
970 "wrapper" => \$wrapper,
972 "anonok!" => \$anonok,
975 "cgiurl=s" => \$cgiurl,
976 "historyurl=s" => \$historyurl,
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;
991 loadindex() unless $rebuild;
996 rcs_update() if $svn;