10 $blosxom::version="is a proper perl module too much to ask?";
11 do "/usr/bin/markdown";
14 $ENV{PATH}="/usr/local/bin:/usr/bin:/bin";
15 my ($srcdir, $destdir, %links, %oldlinks, %oldpagemtime, %renderedfiles,
17 my $wiki_link_regexp=qr/\[\[([^\s]+)\]\]/;
18 my $wiki_file_regexp=qr/(^[-A-Za-z0-9_.:\/+]+$)/;
19 my $wiki_file_prune_regexp=qr!((^|/).svn/|\.\.|^\.|\/\.|\.html?$)!;
22 my $default_pagetype=".mdwn";
30 die "usage: ikiwiki [options] source dest\n";
35 print "Content-type: text/html\n\n";
45 print "@_\n" if $verbose;
51 return (stat($page))[9];
54 sub possibly_foolish_untaint ($) { #{{{
56 my ($untainted)=$tainted=~/(.*)/;
60 sub basename ($) { #{{{
67 sub dirname ($) { #{{{
74 sub pagetype ($) { #{{{
77 if ($page =~ /\.mdwn$/) {
85 sub pagename ($) { #{{{
88 my $type=pagetype($file);
90 $page=~s/\Q$type\E*$// unless $type eq 'unknown';
94 sub htmlpage ($) { #{{{
100 sub readfile ($) { #{{{
104 open (IN, "$file") || error("failed to read $file: $!");
110 sub writefile ($$) { #{{{
114 my $dir=dirname($file);
117 foreach my $s (split(m!/+!, $dir)) {
120 mkdir($d) || error("failed to create directory $d: $!");
125 open (OUT, ">$file") || error("failed to write $file: $!");
134 while ($content =~ /$wiki_link_regexp/g) {
140 # Given a page and the text of a link on the page, determine which existing
141 # page that link best points to. Prefers pages under a subdirectory with
142 # the same name as the source page, failing that goes down the directory tree
143 # to the base looking for matching pages.
144 sub bestlink ($$) { #{{{
151 $l.="/" if length $l;
154 if (exists $links{$l}) {
155 #debug("for $page, \"$link\", use $l");
158 } while $cwd=~s!/?[^/]+$!!;
160 #print STDERR "warning: page $page, broken link: $link\n";
164 sub isinlinableimage ($) { #{{{
167 $file=~/\.(png|gif|jpg|jpeg)$/;
173 my $noimagelink=shift;
175 my $bestlink=bestlink($page, $link);
177 return $link if $page eq $bestlink;
179 # TODO BUG: %renderedfiles may not have it, if the linked to page
180 # was also added and isn't yet rendered! Note that this bug is
181 # masked by the bug mentioned below that makes all new files
183 if (! grep { $_ eq $bestlink } values %renderedfiles) {
184 $bestlink=htmlpage($bestlink);
186 if (! grep { $_ eq $bestlink } values %renderedfiles) {
187 return "<a href=\"$cgiurl?do=create&page=$link&from=$page\">?</a>$link"
190 $bestlink=File::Spec->abs2rel($bestlink, dirname($page));
192 if (! $noimagelink && isinlinableimage($bestlink)) {
193 return "<img src=\"$bestlink\">";
195 return "<a href=\"$bestlink\">$link</a>";
198 sub linkify ($$) { #{{{
202 $content =~ s/$wiki_link_regexp/htmllink(pagename($file), $1)/eg;
207 sub htmlize ($$) { #{{{
211 if ($type eq '.mdwn') {
212 return Markdown::Markdown($content);
215 error("htmlization of $type not supported");
219 sub linkbacks ($$) { #{{{
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, "<a href=\"$href\">$p_trimmed</a>";
242 $content.="<hr><p>Links: ".join(" ", sort @links)."</p>\n" if @links;
246 sub finalize ($$) { #{{{
250 my $title=basename($page);
255 foreach my $dir (reverse split("/", $page)) {
256 if (length($pagelink)) {
257 $pagelink="<a href=\"$path$dir.html\">$dir</a>/ $pagelink";
264 $path=~s/\.\.\/$/index.html/;
265 $pagelink="<a href=\"$path\">$wikiname</a>/ $pagelink";
268 if (length $cgiurl) {
269 push @actions, "<a href=\"$cgiurl?do=edit&page=$page\">Edit</a>";
270 push @actions, "<a href=\"$cgiurl?do=recentchanges\">RecentChanges</a>";
272 if (length $historyurl) {
274 $url=~s/\[\[\]\]/$page/g;
275 push @actions, "<a href=\"$url\">History</a>";
278 $content="<html>\n<head><title>$title</title></head>\n<body>\n".
279 "<h1>$pagelink</h1>\n".
282 "</body>\n</html>\n";
287 sub render ($) { #{{{
290 my $type=pagetype($file);
291 my $content=readfile("$srcdir/$file");
292 if ($type ne 'unknown') {
293 my $page=pagename($file);
295 $links{$page}=[findlinks($content)];
297 $content=linkify($content, $file);
298 $content=htmlize($type, $content);
299 $content=linkbacks($content, $page);
300 $content=finalize($content, $page);
302 writefile("$destdir/".htmlpage($page), $content);
303 $oldpagemtime{$page}=time;
304 $renderedfiles{$page}=htmlpage($page);
308 writefile("$destdir/$file", $content);
309 $oldpagemtime{$file}=time;
310 $renderedfiles{$file}=$file;
314 sub loadindex () { #{{{
315 open (IN, "$srcdir/.index") || return;
317 $_=possibly_foolish_untaint($_);
319 my ($mtime, $file, $rendered, @links)=split(' ', $_);
320 my $page=pagename($file);
321 $pagesources{$page}=$file;
322 $oldpagemtime{$page}=$mtime;
323 $oldlinks{$page}=[@links];
324 $links{$page}=[@links];
325 $renderedfiles{$page}=$rendered;
330 sub saveindex () { #{{{
331 open (OUT, ">$srcdir/.index") || error("cannot write to .index: $!");
332 foreach my $page (keys %oldpagemtime) {
333 print OUT "$oldpagemtime{$page} $pagesources{$page} $renderedfiles{$page} ".
334 join(" ", @{$links{$page}})."\n"
335 if $oldpagemtime{$page};
340 sub rcs_update () { #{{{
341 if (-d "$srcdir/.svn") {
342 if (system("svn", "update", "--quiet", $srcdir) != 0) {
343 warn("svn update failed\n");
348 sub rcs_commit ($) { #{{{
351 if (-d "$srcdir/.svn") {
352 if (system("svn", "commit", "--quiet", "-m",
353 possibly_foolish_untaint($message), $srcdir) != 0) {
354 warn("svn commit failed\n");
359 sub rcs_add ($) { #{{{
362 if (-d "$srcdir/.svn") {
363 my $parent=dirname($file);
364 while (! -d "$srcdir/$parent/.svn") {
366 $parent=dirname($file);
369 if (system("svn", "add", "--quiet", "$srcdir/$file") != 0) {
370 warn("svn add failed\n");
375 sub rcs_recentchanges ($) { #{{{
379 eval q{use Date::Parse};
380 eval q{use Time::Duration};
382 if (-d "$srcdir/.svn") {
383 my $info=`LANG=C svn info $srcdir`;
384 my ($svn_url)=$info=~/^URL: (.*)$/m;
386 # FIXME: currently assumes that the wiki is somewhere
387 # under trunk in svn, doesn't support other layouts.
388 my ($svn_base)=$svn_url=~m!(/trunk(?:/.*)?)$!;
390 my $div=qr/^--------------------+$/;
391 my $infoline=qr/^r(\d+)\s+\|\s+([^\s]+)\s+\|\s+(\d+-\d+-\d+\s+\d+:\d+:\d+\s+[-+]?\d+).*/;
393 my ($rev, $user, $when, @pages, $message);
394 foreach (`LANG=C svn log -v '$svn_url'`) {
396 if ($state eq 'start' && /$div/) {
399 elsif ($state eq 'header' && /$infoline/) {
402 $when=concise(ago(time - str2time($3)));
404 elsif ($state eq 'header' && /^\s+[A-Z]\s+\Q$svn_base\E\/(.+)$/) {
405 push @pages, pagename($1) if length $1;
407 elsif ($state eq 'header' && /^$/) {
410 elsif ($state eq 'body' && /$div/) {
411 push @ret, { rev => $rev, user => $user,
412 when => $when, message => $message,
413 pages => [@pages] } if @pages;
414 return @ret if @ret >= $num;
417 $message=$rev=$user=$when=undef;
420 elsif ($state eq 'body') {
421 $message.="$_<br>\n";
433 my $dir=dirname($file);
434 while (rmdir($dir)) {
439 sub refresh () { #{{{
440 # Find existing pages.
446 if (/$wiki_file_prune_regexp/) {
447 $File::Find::prune=1;
450 my ($f)=/$wiki_file_regexp/; # untaint
452 warn("skipping bad filename $_\n");
455 $f=~s/^\Q$srcdir\E\/?//;
457 $exists{pagename($f)}=1;
465 # check for added or removed pages
467 foreach my $file (@files) {
468 my $page=pagename($file);
469 if (! $oldpagemtime{$page}) {
470 debug("new page $page");
473 $pagesources{$page}=$file;
477 foreach my $page (keys %oldpagemtime) {
478 if (! $exists{$page}) {
479 debug("removing old page $page");
480 push @del, $renderedfiles{$page};
481 prune($destdir."/".$renderedfiles{$page});
482 delete $renderedfiles{$page};
483 $oldpagemtime{$page}=0;
484 delete $pagesources{$page};
488 # render any updated files
489 foreach my $file (@files) {
490 my $page=pagename($file);
492 if (! exists $oldpagemtime{$page} ||
493 mtime("$srcdir/$file") > $oldpagemtime{$page}) {
494 debug("rendering changed file $file");
500 # if any files were added or removed, check to see if each page
501 # needs an update due to linking to them
502 # TODO: inefficient; pages may get rendered above and again here;
503 # problem is the bestlink may have changed and we won't know until
506 FILE: foreach my $file (@files) {
507 my $page=pagename($file);
508 foreach my $f (@add, @del) {
510 foreach my $link (@{$links{$page}}) {
511 if (bestlink($page, $link) eq $p) {
512 debug("rendering $file, which links to $p");
522 # handle linkbacks; if a page has added/removed links, update the
524 # TODO: inefficient; pages may get rendered above and again here;
525 # problem is the linkbacks could be wrong in the first pass render
529 foreach my $file (keys %rendered, @del) {
530 my $page=pagename($file);
531 if (exists $links{$page}) {
532 foreach my $link (@{$links{$page}}) {
533 $link=bestlink($page, $link);
535 ! exists $oldlinks{$page} ||
536 ! grep { $_ eq $link } @{$oldlinks{$page}}) {
537 $linkchanged{$link}=1;
541 if (exists $oldlinks{$page}) {
542 foreach my $link (@{$oldlinks{$page}}) {
543 $link=bestlink($page, $link);
545 ! exists $links{$page} ||
546 ! grep { $_ eq $link } @{$links{$page}}) {
547 $linkchanged{$link}=1;
552 foreach my $link (keys %linkchanged) {
553 my $linkfile=$pagesources{$link};
554 if (defined $linkfile) {
555 debug("rendering $linkfile, to update its linkbacks");
562 # Generates a C wrapper program for running ikiwiki in a specific way.
563 # The wrapper may be safely made suid.
564 sub gen_wrapper ($$) { #{{{
565 my ($svn, $rebuild)=@_;
567 eval q{use Cwd 'abs_path'};
568 $srcdir=abs_path($srcdir);
569 $destdir=abs_path($destdir);
570 my $this=abs_path($0);
572 error("$this doesn't seem to be executable");
575 my @params=($srcdir, $destdir, "--wikiname=$wikiname");
576 push @params, "--verbose" if $verbose;
577 push @params, "--rebuild" if $rebuild;
578 push @params, "--nosvn" if !$svn;
579 push @params, "--cgi" if $cgi;
580 push @params, "--url=$url" if $url;
581 push @params, "--cgiurl=$cgiurl" if $cgiurl;
582 push @params, "--historyurl=$historyurl" if $historyurl;
583 my $params=join(" ", @params);
585 foreach my $p ($this, $this, @params) {
591 push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
592 CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE} if $cgi;
594 foreach my $var (@envsave) {
596 if ((s=getenv("$var")))
597 asprintf(&newenviron[i++], "%s=%s", "$var", s);
601 open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
603 /* A wrapper for ikiwiki, can be safely made suid. */
610 extern char **environ;
612 int main (int argc, char **argv) {
613 /* Sanitize environment. */
615 char *newenviron[$#envsave+3];
618 newenviron[i++]="HOME=$ENV{HOME}";
622 if (argc == 2 && strcmp(argv[1], "--params") == 0) {
623 printf("$params\\n");
628 perror("failed to run $this");
633 if (system("gcc", "ikiwiki-wrap.c", "-o", "ikiwiki-wrap") != 0) {
634 error("failed to compile ikiwiki-wrap.c");
636 unlink("ikiwiki-wrap.c");
637 print "successfully generated ikiwiki-wrap\n";
645 my $do=$q->param('do');
646 if (! defined $do || ! length $do) {
647 error("\"do\" parameter missing");
650 if ($do eq 'recentchanges') {
652 foreach my $change (rcs_recentchanges(100)) {
654 $list.=join(", ", map { htmllink("", $_, 1) } @{$change->{pages}});
656 $list.="changed ".$change->{when}." by ".
657 htmllink("", $change->{user}, 1).
658 ": <i>".$change->{message}."</i>\n";
664 $q->start_html("RecentChanges"),
665 $q->h1("<a href=\"$url\">$wikiname</a>/ RecentChanges"),
672 my ($page)=$q->param('page')=~/$wiki_file_regexp/;
673 if (! defined $page || ! length $page || $page ne $q->param('page') ||
674 $page=~/$wiki_file_prune_regexp/ || $page=~/^\//) {
675 error("bad page name");
679 my $action=$q->request_uri;
682 if ($do eq 'create') {
683 if (exists $pagesources{lc($page)}) {
684 # hmm, someone else made the page in the meantime?
685 print $q->redirect("$url/".htmlpage($page));
689 my ($from)=$q->param('from')=~/$wiki_file_regexp/;
690 if (! defined $from || ! length $from ||
691 $from ne $q->param('from') ||
692 $from=~/$wiki_file_prune_regexp/ || $from=~/^\//) {
698 push @page_locs, $dir.$page;
699 push @page_locs, "$from/$page";
700 while (length $dir) {
702 push @page_locs, $dir.$page;
706 $q->param("do", "save");
708 $q->start_html("Creating $page"),
709 $q->h1("<a href=\"$url\">$wikiname</a>/ Creating $page"),
710 $q->start_form(-action => $action),
712 "Select page location:",
713 $q->popup_menu('page', \@page_locs),
714 $q->textarea(-name => 'content',
719 "Optional comment about this change:",
721 $q->textfield(-name => "comments", -size => 80),
723 $q->submit("Save Page"),
727 elsif ($do eq 'edit') {
729 if (exists $pagesources{lc($page)}) {
730 $content=readfile("$srcdir/$pagesources{lc($page)}");
731 $content=~s/\n/\r\n/g;
733 $q->param("do", "save");
735 $q->start_html("Editing $page"),
736 $q->h1("<a href=\"$url\">$wikiname</a>/ Editing $page"),
737 $q->start_form(-action => $action),
740 $q->textarea(-name => 'content',
741 -default => $content,
745 "Optional comment about this change:",
747 $q->textfield(-name => "comments", -size => 80),
749 $q->submit("Save Page"),
753 elsif ($do eq 'save') {
754 my $file=$page.$default_pagetype;
756 if (exists $pagesources{lc($page)}) {
757 $file=$pagesources{lc($page)};
761 my $content=$q->param('content');
762 $content=~s/\r\n/\n/g;
764 writefile("$srcdir/$file", $content);
766 my $message="web commit from $ENV{REMOTE_ADDR}";
767 if (defined $q->param('comments')) {
768 $message.=": ".$q->param('comments');
775 # presumably the commit will trigger an update
777 rcs_commit($message);
783 print $q->redirect("$url/".htmlpage($page));
786 error("unknown do parameter");
793 if (grep /^-/, @ARGV) {
794 eval {use Getopt::Long};
796 "wikiname=s" => \$wikiname,
797 "verbose|v" => \$verbose,
798 "rebuild" => \$rebuild,
799 "wrapper" => \$wrapper,
803 "cgiurl=s" => \$cgiurl,
804 "historyurl=s" => \$historyurl,
807 usage() unless @ARGV == 2;
808 ($srcdir) = possibly_foolish_untaint(shift);
809 ($destdir) = possibly_foolish_untaint(shift);
811 if ($cgi && ! length $url) {
812 error("Must specify url to wiki with --url when using --cgi");
815 gen_wrapper($svn, $rebuild) if $wrapper;
818 loadindex() unless $rebuild;
823 rcs_update() if $svn;