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";
31 die "usage: ikiwiki [options] source templates dest\n";
36 print "Content-type: text/html\n\n";
46 print "@_\n" if $verbose;
52 return (stat($page))[9];
55 sub possibly_foolish_untaint ($) { #{{{
57 my ($untainted)=$tainted=~/(.*)/;
61 sub basename ($) { #{{{
68 sub dirname ($) { #{{{
75 sub pagetype ($) { #{{{
78 if ($page =~ /\.mdwn$/) {
86 sub pagename ($) { #{{{
89 my $type=pagetype($file);
91 $page=~s/\Q$type\E*$// unless $type eq 'unknown';
95 sub htmlpage ($) { #{{{
101 sub readfile ($) { #{{{
105 open (IN, "$file") || error("failed to read $file: $!");
111 sub writefile ($$) { #{{{
115 my $dir=dirname($file);
118 foreach my $s (split(m!/+!, $dir)) {
121 mkdir($d) || error("failed to create directory $d: $!");
126 open (OUT, ">$file") || error("failed to write $file: $!");
131 sub findlinks ($) { #{{{
135 while ($content =~ /$wiki_link_regexp/g) {
141 # Given a page and the text of a link on the page, determine which existing
142 # page that link best points to. Prefers pages under a subdirectory with
143 # the same name as the source page, failing that goes down the directory tree
144 # to the base looking for matching pages.
145 sub bestlink ($$) { #{{{
152 $l.="/" if length $l;
155 if (exists $links{$l}) {
156 #debug("for $page, \"$link\", use $l");
159 } while $cwd=~s!/?[^/]+$!!;
161 #print STDERR "warning: page $page, broken link: $link\n";
165 sub isinlinableimage ($) { #{{{
168 $file=~/\.(png|gif|jpg|jpeg)$/;
174 my $noimagelink=shift;
176 my $bestlink=bestlink($page, $link);
178 return $link if $page eq $bestlink;
180 # TODO BUG: %renderedfiles may not have it, if the linked to page
181 # was also added and isn't yet rendered! Note that this bug is
182 # masked by the bug mentioned below that makes all new files
184 if (! grep { $_ eq $bestlink } values %renderedfiles) {
185 $bestlink=htmlpage($bestlink);
187 if (! grep { $_ eq $bestlink } values %renderedfiles) {
188 return "<a href=\"$cgiurl?do=create&page=$link&from=$page\">?</a>$link"
191 $bestlink=File::Spec->abs2rel($bestlink, dirname($page));
193 if (! $noimagelink && isinlinableimage($bestlink)) {
194 return "<img src=\"$bestlink\">";
196 return "<a href=\"$bestlink\">$link</a>";
199 sub linkify ($$) { #{{{
203 $content =~ s/$wiki_link_regexp/htmllink(pagename($file), $1)/eg;
208 sub htmlize ($$) { #{{{
212 if ($type eq '.mdwn') {
213 return Markdown::Markdown($content);
216 error("htmlization of $type not supported");
220 sub backlinks ($) { #{{{
224 foreach my $p (keys %links) {
225 next if bestlink($page, $p) eq $page;
226 if (grep { length $_ && bestlink($p, $_) eq $page } @{$links{$p}}) {
227 my $href=File::Spec->abs2rel(htmlpage($p), dirname($page));
229 # Trim common dir prefixes from both pages.
231 my $page_trimmed=$page;
233 1 while (($dir)=$page_trimmed=~m!^([^/]+/)!) &&
235 $p_trimmed=~s/^\Q$dir\E// &&
236 $page_trimmed=~s/^\Q$dir\E//;
238 push @links, { url => $href, page => $p_trimmed };
245 sub parentlinks ($) { #{{{
252 foreach my $dir (reverse split("/", $page)) {
254 unshift @ret, { url => "$path$dir.html", page => $dir };
264 sub indexlink () { #{{{
265 return "<a href=\"$url\">$wikiname</a>/ ";
268 sub finalize ($$) { #{{{
272 my $title=basename($page);
275 my $template=HTML::Template->new(blind_cache => 1,
276 filename => "$templatedir/page.tmpl");
278 if (length $cgiurl) {
279 $template->param(editurl => "$cgiurl?do=edit&page=$page");
280 $template->param(recentchangesurl => "$cgiurl?do=recentchanges");
283 if (length $historyurl) {
285 $u=~s/\[\[\]\]/$pagesources{$page}/g;
286 $template->param(historyurl => $u);
292 wikiname => $wikiname,
293 parentlinks => [parentlinks($page)],
295 backlinks => [backlinks($page)],
298 return $template->output;
301 sub render ($) { #{{{
304 my $type=pagetype($file);
305 my $content=readfile("$srcdir/$file");
306 if ($type ne 'unknown') {
307 my $page=pagename($file);
309 $links{$page}=[findlinks($content)];
311 $content=linkify($content, $file);
312 $content=htmlize($type, $content);
313 $content=finalize($content, $page);
315 writefile("$destdir/".htmlpage($page), $content);
316 $oldpagemtime{$page}=time;
317 $renderedfiles{$page}=htmlpage($page);
321 writefile("$destdir/$file", $content);
322 $oldpagemtime{$file}=time;
323 $renderedfiles{$file}=$file;
327 sub loadindex () { #{{{
328 open (IN, "$srcdir/.ikiwiki/index") || return;
330 $_=possibly_foolish_untaint($_);
332 my ($mtime, $file, $rendered, @links)=split(' ', $_);
333 my $page=pagename($file);
334 $pagesources{$page}=$file;
335 $oldpagemtime{$page}=$mtime;
336 $oldlinks{$page}=[@links];
337 $links{$page}=[@links];
338 $renderedfiles{$page}=$rendered;
343 sub saveindex () { #{{{
344 if (! -d "$srcdir/.ikiwiki") {
345 mkdir("$srcdir/.ikiwiki");
347 open (OUT, ">$srcdir/.ikiwiki/index") || error("cannot write to index: $!");
348 foreach my $page (keys %oldpagemtime) {
349 print OUT "$oldpagemtime{$page} $pagesources{$page} $renderedfiles{$page} ".
350 join(" ", @{$links{$page}})."\n"
351 if $oldpagemtime{$page};
356 sub rcs_update () { #{{{
357 if (-d "$srcdir/.svn") {
358 if (system("svn", "update", "--quiet", $srcdir) != 0) {
359 warn("svn update failed\n");
364 sub rcs_commit ($) { #{{{
367 if (-d "$srcdir/.svn") {
368 if (system("svn", "commit", "--quiet", "-m",
369 possibly_foolish_untaint($message), $srcdir) != 0) {
370 warn("svn commit failed\n");
375 sub rcs_add ($) { #{{{
378 if (-d "$srcdir/.svn") {
379 my $parent=dirname($file);
380 while (! -d "$srcdir/$parent/.svn") {
382 $parent=dirname($file);
385 if (system("svn", "add", "--quiet", "$srcdir/$file") != 0) {
386 warn("svn add failed\n");
391 sub rcs_recentchanges ($) { #{{{
395 eval q{use Date::Parse};
396 eval q{use Time::Duration};
398 if (-d "$srcdir/.svn") {
399 my $info=`LANG=C svn info $srcdir`;
400 my ($svn_url)=$info=~/^URL: (.*)$/m;
402 # FIXME: currently assumes that the wiki is somewhere
403 # under trunk in svn, doesn't support other layouts.
404 my ($svn_base)=$svn_url=~m!(/trunk(?:/.*)?)$!;
406 my $div=qr/^--------------------+$/;
407 my $infoline=qr/^r(\d+)\s+\|\s+([^\s]+)\s+\|\s+(\d+-\d+-\d+\s+\d+:\d+:\d+\s+[-+]?\d+).*/;
409 my ($rev, $user, $when, @pages, $message);
410 foreach (`LANG=C svn log -v '$svn_url'`) {
412 if ($state eq 'start' && /$div/) {
415 elsif ($state eq 'header' && /$infoline/) {
418 $when=concise(ago(time - str2time($3)));
420 elsif ($state eq 'header' && /^\s+[A-Z]\s+\Q$svn_base\E\/(.+)$/) {
421 push @pages, htmllink("", pagename($1), 1)
424 elsif ($state eq 'header' && /^$/) {
427 elsif ($state eq 'body' && /$div/) {
428 push @ret, { rev => $rev, user => $user,
429 when => $when, message => $message,
430 pages => [@pages] } if @pages;
431 return @ret if @ret >= $num;
434 $message=$rev=$user=$when=undef;
437 elsif ($state eq 'body') {
438 $message.="$_<br>\n";
450 my $dir=dirname($file);
451 while (rmdir($dir)) {
456 sub refresh () { #{{{
457 # Find existing pages.
463 if (/$wiki_file_prune_regexp/) {
464 $File::Find::prune=1;
467 my ($f)=/$wiki_file_regexp/; # untaint
469 warn("skipping bad filename $_\n");
472 $f=~s/^\Q$srcdir\E\/?//;
474 $exists{pagename($f)}=1;
482 # check for added or removed pages
484 foreach my $file (@files) {
485 my $page=pagename($file);
486 if (! $oldpagemtime{$page}) {
487 debug("new page $page");
490 $pagesources{$page}=$file;
494 foreach my $page (keys %oldpagemtime) {
495 if (! $exists{$page}) {
496 debug("removing old page $page");
497 push @del, $renderedfiles{$page};
498 prune($destdir."/".$renderedfiles{$page});
499 delete $renderedfiles{$page};
500 $oldpagemtime{$page}=0;
501 delete $pagesources{$page};
505 # render any updated files
506 foreach my $file (@files) {
507 my $page=pagename($file);
509 if (! exists $oldpagemtime{$page} ||
510 mtime("$srcdir/$file") > $oldpagemtime{$page}) {
511 debug("rendering changed file $file");
517 # if any files were added or removed, check to see if each page
518 # needs an update due to linking to them
519 # TODO: inefficient; pages may get rendered above and again here;
520 # problem is the bestlink may have changed and we won't know until
523 FILE: foreach my $file (@files) {
524 my $page=pagename($file);
525 foreach my $f (@add, @del) {
527 foreach my $link (@{$links{$page}}) {
528 if (bestlink($page, $link) eq $p) {
529 debug("rendering $file, which links to $p");
539 # handle backlinks; if a page has added/removed links, update the
541 # TODO: inefficient; pages may get rendered above and again here;
542 # problem is the backlinks could be wrong in the first pass render
546 foreach my $file (keys %rendered, @del) {
547 my $page=pagename($file);
548 if (exists $links{$page}) {
549 foreach my $link (@{$links{$page}}) {
550 $link=bestlink($page, $link);
552 ! exists $oldlinks{$page} ||
553 ! grep { $_ eq $link } @{$oldlinks{$page}}) {
554 $linkchanged{$link}=1;
558 if (exists $oldlinks{$page}) {
559 foreach my $link (@{$oldlinks{$page}}) {
560 $link=bestlink($page, $link);
562 ! exists $links{$page} ||
563 ! grep { $_ eq $link } @{$links{$page}}) {
564 $linkchanged{$link}=1;
569 foreach my $link (keys %linkchanged) {
570 my $linkfile=$pagesources{$link};
571 if (defined $linkfile) {
572 debug("rendering $linkfile, to update its backlinks");
579 # Generates a C wrapper program for running ikiwiki in a specific way.
580 # The wrapper may be safely made suid.
581 sub gen_wrapper ($$) { #{{{
582 my ($svn, $rebuild)=@_;
584 eval q{use Cwd 'abs_path'};
585 $srcdir=abs_path($srcdir);
586 $destdir=abs_path($destdir);
587 my $this=abs_path($0);
589 error("$this doesn't seem to be executable");
592 my @params=($srcdir, $templatedir, $destdir, "--wikiname=$wikiname");
593 push @params, "--verbose" if $verbose;
594 push @params, "--rebuild" if $rebuild;
595 push @params, "--nosvn" if !$svn;
596 push @params, "--cgi" if $cgi;
597 push @params, "--url=$url" if $url;
598 push @params, "--cgiurl=$cgiurl" if $cgiurl;
599 push @params, "--historyurl=$historyurl" if $historyurl;
600 my $params=join(" ", @params);
602 foreach my $p ($this, $this, @params) {
608 push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
609 CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
610 HTTP_COOKIE} if $cgi;
612 foreach my $var (@envsave) {
614 if ((s=getenv("$var")))
615 asprintf(&newenviron[i++], "%s=%s", "$var", s);
619 open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
621 /* A wrapper for ikiwiki, can be safely made suid. */
628 extern char **environ;
630 int main (int argc, char **argv) {
631 /* Sanitize environment. */
633 char *newenviron[$#envsave+3];
636 newenviron[i++]="HOME=$ENV{HOME}";
640 if (argc == 2 && strcmp(argv[1], "--params") == 0) {
641 printf("$params\\n");
646 perror("failed to run $this");
651 if (system("gcc", "ikiwiki-wrap.c", "-o", "ikiwiki-wrap") != 0) {
652 error("failed to compile ikiwiki-wrap.c");
654 unlink("ikiwiki-wrap.c");
655 print "successfully generated ikiwiki-wrap\n";
659 sub cgi_recentchanges () { #{{{
662 my $template=HTML::Template->new(
663 filename => "$templatedir/recentchanges.tmpl");
665 title => "RecentChanges",
667 wikiname => $wikiname,
668 changelog => [rcs_recentchanges(100)],
670 return $template->output;
673 sub cgi_signin ($$) { #{{{
677 eval q{use CGI::FormBuilder};
678 my $form = CGI::FormBuilder->new(
679 title => "$wikiname signin",
680 fields => [qw(do page name password confirm_password email)],
685 confirm_password => {
686 perl => q{eq $form->field("password")},
693 action => $q->request_uri,
696 $form->sessionid($session->id);
697 $form->field(name => "name", required => 0);
698 $form->field(name => "do", type => "hidden");
699 $form->field(name => "page", type => "hidden");
700 $form->field(name => "password", type => "password", required => 0);
701 $form->field(name => "confirm_password", type => "password", required => 0);
702 $form->field(name => "email", required => 0);
703 if ($session->param("name")) {
704 $form->field(name => "name", value => $session->param("name"));
706 if ($q->param("do") ne "signin") {
707 $form->text("You need to log in before you can edit pages.");
710 if ($form->submitted) {
711 # Set required fields based on how form was submitted.
713 "Login" => [qw(name password)],
714 "Register" => [qw(name password confirm_password email)],
715 "Mail Password" => [qw(name)],
717 foreach my $opt (@{$required{$form->submitted}}) {
718 $form->field(name => $opt, required => 1);
721 # Validate password differently depending on how form was
723 if ($form->submitted eq 'Login') {
727 # TODO get real user password
733 $form->field(name => "password", validate => 'VALUE');
737 # Comments only shown first time.
738 $form->field(name => "name", comment => "use FirstnameLastName");
739 $form->field(name => "confirm_password", comment => "(only needed");
740 $form->field(name => "email", comment => "for registration)");
743 if ($form->submitted && $form->validate) {
744 if ($form->submitted eq 'Login') {
745 $session->param("name", $form->field("name"));
746 if (defined $form->field("do")) {
748 "$cgiurl?do=".$form->field("do").
749 "&page=".$form->field("page"));
755 elsif ($form->submitted eq 'Register') {
756 # TODO: save registration info
757 $form->field(name => "confirm_password", type => "hidden");
758 $form->field(name => "email", type => "hidden");
759 $form->text("Registration successful. Now you can Login.");
760 print $form->render(submit => ["Login"]);;
762 elsif ($form->submitted eq 'Mail Password') {
764 $form->text("Your password has been emailed to you.");
765 print $form->render(submit => ["Login", "Register", "Mail Password"]);;
769 print $form->render(submit => ["Login", "Register", "Mail Password"]);;
775 eval q{use CGI::Session};
778 # session id has to be _sessionid for CGI::FormBuilder to work.
779 # TODO: stop having the formbuilder emit cookies and change session
780 # id to something else.
781 CGI::Session->name("_sessionid");
782 my $session = CGI::Session->new(undef, $q,
783 { Directory=> "$srcdir/.ikiwiki/sessions" });
785 my $do=$q->param('do');
786 if (! defined $do || ! length $do) {
787 error("\"do\" parameter missing");
790 if ($do eq 'recentchanges') {
795 if (! defined $session->param("name") || $do eq 'signin') {
796 cgi_signin($q, $session);
800 my ($page)=$q->param('page')=~/$wiki_file_regexp/;
801 if (! defined $page || ! length $page || $page ne $q->param('page') ||
802 $page=~/$wiki_file_prune_regexp/ || $page=~/^\//) {
803 error("bad page name");
807 my $action=$q->request_uri;
810 if ($do eq 'create') {
811 if (exists $pagesources{lc($page)}) {
812 # hmm, someone else made the page in the meantime?
813 print $q->redirect("$url/".htmlpage($page));
817 my ($from)=$q->param('from')=~/$wiki_file_regexp/;
818 if (! defined $from || ! length $from ||
819 $from ne $q->param('from') ||
820 $from=~/$wiki_file_prune_regexp/ || $from=~/^\//) {
826 push @page_locs, $dir.$page;
827 push @page_locs, "$from/$page";
828 while (length $dir) {
830 push @page_locs, $dir.$page;
834 $q->param("do", "save");
836 $q->start_html("Creating $page"),
837 $q->h1(indexlink()." Creating $page"),
838 $q->start_form(-action => $action),
840 "Select page location:",
841 $q->popup_menu('page', \@page_locs),
842 $q->textarea(-name => 'content',
847 "Optional comment about this change:",
849 $q->textfield(-name => "comments", -size => 80),
851 $q->submit("Save Page"),
855 elsif ($do eq 'edit') {
857 if (exists $pagesources{lc($page)}) {
858 $content=readfile("$srcdir/$pagesources{lc($page)}");
859 $content=~s/\n/\r\n/g;
861 $q->param("do", "save");
863 $q->start_html("Editing $page"),
864 $q->h1(indexlink()." Editing $page"),
865 $q->start_form(-action => $action),
868 $q->textarea(-name => 'content',
869 -default => $content,
873 "Optional comment about this change:",
875 $q->textfield(-name => "comments", -size => 80),
877 $q->submit("Save Page"),
881 elsif ($do eq 'save') {
882 my $file=$page.$default_pagetype;
884 if (exists $pagesources{lc($page)}) {
885 $file=$pagesources{lc($page)};
889 my $content=$q->param('content');
890 $content=~s/\r\n/\n/g;
892 writefile("$srcdir/$file", $content);
894 my $message="web commit from $ENV{REMOTE_ADDR}";
895 if (defined $q->param('comments')) {
896 $message.=": ".$q->param('comments');
903 # presumably the commit will trigger an update
905 rcs_commit($message);
911 print $q->redirect("$url/".htmlpage($page));
914 error("unknown do parameter");
921 if (grep /^-/, @ARGV) {
922 eval {use Getopt::Long};
924 "wikiname=s" => \$wikiname,
925 "verbose|v" => \$verbose,
926 "rebuild" => \$rebuild,
927 "wrapper" => \$wrapper,
931 "cgiurl=s" => \$cgiurl,
932 "historyurl=s" => \$historyurl,
935 usage() unless @ARGV == 3;
936 ($srcdir) = possibly_foolish_untaint(shift);
937 ($templatedir) = possibly_foolish_untaint(shift);
938 ($destdir) = possibly_foolish_untaint(shift);
940 if ($cgi && ! length $url) {
941 error("Must specify url to wiki with --url when using --cgi");
944 gen_wrapper($svn, $rebuild) if $wrapper;
947 loadindex() unless $rebuild;
952 rcs_update() if $svn;