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: $!");
130 sub findlinks ($) { #{{{
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 indexlink () { #{{{
247 return "<a href=\"$url\">$wikiname</a>/ ";
250 sub finalize ($$) { #{{{
254 my $title=basename($page);
259 foreach my $dir (reverse split("/", $page)) {
260 if (length($pagelink)) {
261 $pagelink="<a href=\"$path$dir.html\">$dir</a>/ $pagelink";
268 $path=~s/\.\.\/$/index.html/;
269 $pagelink=indexlink()." $pagelink";
272 if (length $cgiurl) {
273 push @actions, "<a href=\"$cgiurl?do=edit&page=$page\">Edit</a>";
274 push @actions, "<a href=\"$cgiurl?do=recentchanges\">RecentChanges</a>";
276 if (length $historyurl) {
278 $url=~s/\[\[\]\]/$pagesources{$page}/g;
279 push @actions, "<a href=\"$url\">History</a>";
282 $content="<html>\n<head><title>$title</title></head>\n<body>\n".
283 "<h1>$pagelink</h1>\n".
286 "</body>\n</html>\n";
291 sub render ($) { #{{{
294 my $type=pagetype($file);
295 my $content=readfile("$srcdir/$file");
296 if ($type ne 'unknown') {
297 my $page=pagename($file);
299 $links{$page}=[findlinks($content)];
301 $content=linkify($content, $file);
302 $content=htmlize($type, $content);
303 $content=linkbacks($content, $page);
304 $content=finalize($content, $page);
306 writefile("$destdir/".htmlpage($page), $content);
307 $oldpagemtime{$page}=time;
308 $renderedfiles{$page}=htmlpage($page);
312 writefile("$destdir/$file", $content);
313 $oldpagemtime{$file}=time;
314 $renderedfiles{$file}=$file;
318 sub loadindex () { #{{{
319 open (IN, "$srcdir/.ikiwiki/index") || return;
321 $_=possibly_foolish_untaint($_);
323 my ($mtime, $file, $rendered, @links)=split(' ', $_);
324 my $page=pagename($file);
325 $pagesources{$page}=$file;
326 $oldpagemtime{$page}=$mtime;
327 $oldlinks{$page}=[@links];
328 $links{$page}=[@links];
329 $renderedfiles{$page}=$rendered;
334 sub saveindex () { #{{{
335 if (! -d "$srcdir/.ikiwiki") {
336 mkdir("$srcdir/.ikiwiki");
338 open (OUT, ">$srcdir/.ikiwiki/index") || error("cannot write to index: $!");
339 foreach my $page (keys %oldpagemtime) {
340 print OUT "$oldpagemtime{$page} $pagesources{$page} $renderedfiles{$page} ".
341 join(" ", @{$links{$page}})."\n"
342 if $oldpagemtime{$page};
347 sub rcs_update () { #{{{
348 if (-d "$srcdir/.svn") {
349 if (system("svn", "update", "--quiet", $srcdir) != 0) {
350 warn("svn update failed\n");
355 sub rcs_commit ($) { #{{{
358 if (-d "$srcdir/.svn") {
359 if (system("svn", "commit", "--quiet", "-m",
360 possibly_foolish_untaint($message), $srcdir) != 0) {
361 warn("svn commit failed\n");
366 sub rcs_add ($) { #{{{
369 if (-d "$srcdir/.svn") {
370 my $parent=dirname($file);
371 while (! -d "$srcdir/$parent/.svn") {
373 $parent=dirname($file);
376 if (system("svn", "add", "--quiet", "$srcdir/$file") != 0) {
377 warn("svn add failed\n");
382 sub rcs_recentchanges ($) { #{{{
386 eval q{use Date::Parse};
387 eval q{use Time::Duration};
389 if (-d "$srcdir/.svn") {
390 my $info=`LANG=C svn info $srcdir`;
391 my ($svn_url)=$info=~/^URL: (.*)$/m;
393 # FIXME: currently assumes that the wiki is somewhere
394 # under trunk in svn, doesn't support other layouts.
395 my ($svn_base)=$svn_url=~m!(/trunk(?:/.*)?)$!;
397 my $div=qr/^--------------------+$/;
398 my $infoline=qr/^r(\d+)\s+\|\s+([^\s]+)\s+\|\s+(\d+-\d+-\d+\s+\d+:\d+:\d+\s+[-+]?\d+).*/;
400 my ($rev, $user, $when, @pages, $message);
401 foreach (`LANG=C svn log -v '$svn_url'`) {
403 if ($state eq 'start' && /$div/) {
406 elsif ($state eq 'header' && /$infoline/) {
409 $when=concise(ago(time - str2time($3)));
411 elsif ($state eq 'header' && /^\s+[A-Z]\s+\Q$svn_base\E\/(.+)$/) {
412 push @pages, pagename($1) if length $1;
414 elsif ($state eq 'header' && /^$/) {
417 elsif ($state eq 'body' && /$div/) {
418 push @ret, { rev => $rev, user => $user,
419 when => $when, message => $message,
420 pages => [@pages] } if @pages;
421 return @ret if @ret >= $num;
424 $message=$rev=$user=$when=undef;
427 elsif ($state eq 'body') {
428 $message.="$_<br>\n";
440 my $dir=dirname($file);
441 while (rmdir($dir)) {
446 sub refresh () { #{{{
447 # Find existing pages.
453 if (/$wiki_file_prune_regexp/) {
454 $File::Find::prune=1;
457 my ($f)=/$wiki_file_regexp/; # untaint
459 warn("skipping bad filename $_\n");
462 $f=~s/^\Q$srcdir\E\/?//;
464 $exists{pagename($f)}=1;
472 # check for added or removed pages
474 foreach my $file (@files) {
475 my $page=pagename($file);
476 if (! $oldpagemtime{$page}) {
477 debug("new page $page");
480 $pagesources{$page}=$file;
484 foreach my $page (keys %oldpagemtime) {
485 if (! $exists{$page}) {
486 debug("removing old page $page");
487 push @del, $renderedfiles{$page};
488 prune($destdir."/".$renderedfiles{$page});
489 delete $renderedfiles{$page};
490 $oldpagemtime{$page}=0;
491 delete $pagesources{$page};
495 # render any updated files
496 foreach my $file (@files) {
497 my $page=pagename($file);
499 if (! exists $oldpagemtime{$page} ||
500 mtime("$srcdir/$file") > $oldpagemtime{$page}) {
501 debug("rendering changed file $file");
507 # if any files were added or removed, check to see if each page
508 # needs an update due to linking to them
509 # TODO: inefficient; pages may get rendered above and again here;
510 # problem is the bestlink may have changed and we won't know until
513 FILE: foreach my $file (@files) {
514 my $page=pagename($file);
515 foreach my $f (@add, @del) {
517 foreach my $link (@{$links{$page}}) {
518 if (bestlink($page, $link) eq $p) {
519 debug("rendering $file, which links to $p");
529 # handle linkbacks; if a page has added/removed links, update the
531 # TODO: inefficient; pages may get rendered above and again here;
532 # problem is the linkbacks could be wrong in the first pass render
536 foreach my $file (keys %rendered, @del) {
537 my $page=pagename($file);
538 if (exists $links{$page}) {
539 foreach my $link (@{$links{$page}}) {
540 $link=bestlink($page, $link);
542 ! exists $oldlinks{$page} ||
543 ! grep { $_ eq $link } @{$oldlinks{$page}}) {
544 $linkchanged{$link}=1;
548 if (exists $oldlinks{$page}) {
549 foreach my $link (@{$oldlinks{$page}}) {
550 $link=bestlink($page, $link);
552 ! exists $links{$page} ||
553 ! grep { $_ eq $link } @{$links{$page}}) {
554 $linkchanged{$link}=1;
559 foreach my $link (keys %linkchanged) {
560 my $linkfile=$pagesources{$link};
561 if (defined $linkfile) {
562 debug("rendering $linkfile, to update its linkbacks");
569 # Generates a C wrapper program for running ikiwiki in a specific way.
570 # The wrapper may be safely made suid.
571 sub gen_wrapper ($$) { #{{{
572 my ($svn, $rebuild)=@_;
574 eval q{use Cwd 'abs_path'};
575 $srcdir=abs_path($srcdir);
576 $destdir=abs_path($destdir);
577 my $this=abs_path($0);
579 error("$this doesn't seem to be executable");
582 my @params=($srcdir, $destdir, "--wikiname=$wikiname");
583 push @params, "--verbose" if $verbose;
584 push @params, "--rebuild" if $rebuild;
585 push @params, "--nosvn" if !$svn;
586 push @params, "--cgi" if $cgi;
587 push @params, "--url=$url" if $url;
588 push @params, "--cgiurl=$cgiurl" if $cgiurl;
589 push @params, "--historyurl=$historyurl" if $historyurl;
590 my $params=join(" ", @params);
592 foreach my $p ($this, $this, @params) {
598 push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
599 CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
600 HTTP_COOKIE} if $cgi;
602 foreach my $var (@envsave) {
604 if ((s=getenv("$var")))
605 asprintf(&newenviron[i++], "%s=%s", "$var", s);
609 open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
611 /* A wrapper for ikiwiki, can be safely made suid. */
618 extern char **environ;
620 int main (int argc, char **argv) {
621 /* Sanitize environment. */
623 char *newenviron[$#envsave+3];
626 newenviron[i++]="HOME=$ENV{HOME}";
630 if (argc == 2 && strcmp(argv[1], "--params") == 0) {
631 printf("$params\\n");
636 perror("failed to run $this");
641 if (system("gcc", "ikiwiki-wrap.c", "-o", "ikiwiki-wrap") != 0) {
642 error("failed to compile ikiwiki-wrap.c");
644 unlink("ikiwiki-wrap.c");
645 print "successfully generated ikiwiki-wrap\n";
649 sub cgi_recentchanges ($) { #{{{
653 foreach my $change (rcs_recentchanges(100)) {
655 $list.=join(", ", map { htmllink("", $_, 1) } @{$change->{pages}});
657 $list.="changed ".$change->{when}." by ".
658 htmllink("", $change->{user}, 1).
659 ": <i>".$change->{message}."</i>\n";
665 $q->start_html("RecentChanges"),
666 $q->h1(indexlink()." RecentChanges"),
672 sub cgi_signin ($$) { #{{{
676 eval q{use CGI::FormBuilder};
677 my $form = CGI::FormBuilder->new(
678 title => "$wikiname signin",
679 fields => [qw(do page name password confirm_password email)],
684 confirm_password => {
685 perl => q{eq $form->field("password")},
692 action => $q->request_uri,
695 $form->sessionid($session->id);
696 $form->field(name => "name", required => 0);
697 $form->field(name => "do", type => "hidden");
698 $form->field(name => "page", type => "hidden");
699 $form->field(name => "password", type => "password", required => 0);
700 $form->field(name => "confirm_password", type => "password", required => 0);
701 $form->field(name => "email", required => 0);
702 if ($session->param("name")) {
703 $form->field(name => "name", value => $session->param("name"));
705 if ($q->param("do") ne "signin") {
706 $form->text("You need to log in before you can edit pages.");
709 if ($form->submitted) {
710 # Set required fields based on how form was submitted.
712 "Login" => [qw(name password)],
713 "Register" => [qw(name password confirm_password email)],
714 "Mail Password" => [qw(name)],
716 foreach my $opt (@{$required{$form->submitted}}) {
717 $form->field(name => $opt, required => 1);
720 # Validate password differently depending on how form was
722 if ($form->submitted eq 'Login') {
726 # TODO get real user password
732 $form->field(name => "password", validate => 'VALUE');
736 # Comments only shown first time.
737 $form->field(name => "name", comment => "use FirstnameLastName");
738 $form->field(name => "confirm_password", comment => "(only needed");
739 $form->field(name => "email", comment => "for registration)");
742 if ($form->submitted && $form->validate) {
743 if ($form->submitted eq 'Login') {
744 $session->param("name", $form->field("name"));
745 if (defined $form->field("do")) {
747 "$cgiurl?do=".$form->field("do").
748 "&page=".$form->field("page"));
754 elsif ($form->submitted eq 'Register') {
755 # TODO: save registration info
756 $form->field(name => "confirm_password", type => "hidden");
757 $form->field(name => "email", type => "hidden");
758 $form->text("Registration successful. Now you can Login.");
759 print $form->render(submit => ["Login"]);;
761 elsif ($form->submitted eq 'Mail Password') {
763 $form->text("Your password has been emailed to you.");
764 print $form->render(submit => ["Login", "Register", "Mail Password"]);;
768 print $form->render(submit => ["Login", "Register", "Mail Password"]);;
774 eval q{use CGI::Session};
777 # session id has to be _sessionid for CGI::FormBuilder to work.
778 # TODO: stop having the formbuilder emit cookies and change session
779 # id to something else.
780 CGI::Session->name("_sessionid");
781 my $session = CGI::Session->new(undef, $q,
782 { Directory=> "$srcdir/.ikiwiki/sessions" });
784 my $do=$q->param('do');
785 if (! defined $do || ! length $do) {
786 error("\"do\" parameter missing");
789 if ($do eq 'recentchanges') {
790 cgi_recentchanges($q);
794 if (! defined $session->param("name") || $do eq 'signin') {
795 cgi_signin($q, $session);
799 my ($page)=$q->param('page')=~/$wiki_file_regexp/;
800 if (! defined $page || ! length $page || $page ne $q->param('page') ||
801 $page=~/$wiki_file_prune_regexp/ || $page=~/^\//) {
802 error("bad page name");
806 my $action=$q->request_uri;
809 if ($do eq 'create') {
810 if (exists $pagesources{lc($page)}) {
811 # hmm, someone else made the page in the meantime?
812 print $q->redirect("$url/".htmlpage($page));
816 my ($from)=$q->param('from')=~/$wiki_file_regexp/;
817 if (! defined $from || ! length $from ||
818 $from ne $q->param('from') ||
819 $from=~/$wiki_file_prune_regexp/ || $from=~/^\//) {
825 push @page_locs, $dir.$page;
826 push @page_locs, "$from/$page";
827 while (length $dir) {
829 push @page_locs, $dir.$page;
833 $q->param("do", "save");
835 $q->start_html("Creating $page"),
836 $q->h1(indexlink()." Creating $page"),
837 $q->start_form(-action => $action),
839 "Select page location:",
840 $q->popup_menu('page', \@page_locs),
841 $q->textarea(-name => 'content',
846 "Optional comment about this change:",
848 $q->textfield(-name => "comments", -size => 80),
850 $q->submit("Save Page"),
854 elsif ($do eq 'edit') {
856 if (exists $pagesources{lc($page)}) {
857 $content=readfile("$srcdir/$pagesources{lc($page)}");
858 $content=~s/\n/\r\n/g;
860 $q->param("do", "save");
862 $q->start_html("Editing $page"),
863 $q->h1(indexlink()." Editing $page"),
864 $q->start_form(-action => $action),
867 $q->textarea(-name => 'content',
868 -default => $content,
872 "Optional comment about this change:",
874 $q->textfield(-name => "comments", -size => 80),
876 $q->submit("Save Page"),
880 elsif ($do eq 'save') {
881 my $file=$page.$default_pagetype;
883 if (exists $pagesources{lc($page)}) {
884 $file=$pagesources{lc($page)};
888 my $content=$q->param('content');
889 $content=~s/\r\n/\n/g;
891 writefile("$srcdir/$file", $content);
893 my $message="web commit from $ENV{REMOTE_ADDR}";
894 if (defined $q->param('comments')) {
895 $message.=": ".$q->param('comments');
902 # presumably the commit will trigger an update
904 rcs_commit($message);
910 print $q->redirect("$url/".htmlpage($page));
913 error("unknown do parameter");
920 if (grep /^-/, @ARGV) {
921 eval {use Getopt::Long};
923 "wikiname=s" => \$wikiname,
924 "verbose|v" => \$verbose,
925 "rebuild" => \$rebuild,
926 "wrapper" => \$wrapper,
930 "cgiurl=s" => \$cgiurl,
931 "historyurl=s" => \$historyurl,
934 usage() unless @ARGV == 2;
935 ($srcdir) = possibly_foolish_untaint(shift);
936 ($destdir) = possibly_foolish_untaint(shift);
938 if ($cgi && ! length $url) {
939 error("Must specify url to wiki with --url when using --cgi");
942 gen_wrapper($svn, $rebuild) if $wrapper;
945 loadindex() unless $rebuild;
950 rcs_update() if $svn;