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, pagename($1) if length $1;
423 elsif ($state eq 'header' && /^$/) {
426 elsif ($state eq 'body' && /$div/) {
427 push @ret, { rev => $rev, user => $user,
428 when => $when, message => $message,
429 pages => [@pages] } if @pages;
430 return @ret if @ret >= $num;
433 $message=$rev=$user=$when=undef;
436 elsif ($state eq 'body') {
437 $message.="$_<br>\n";
449 my $dir=dirname($file);
450 while (rmdir($dir)) {
455 sub refresh () { #{{{
456 # Find existing pages.
462 if (/$wiki_file_prune_regexp/) {
463 $File::Find::prune=1;
466 my ($f)=/$wiki_file_regexp/; # untaint
468 warn("skipping bad filename $_\n");
471 $f=~s/^\Q$srcdir\E\/?//;
473 $exists{pagename($f)}=1;
481 # check for added or removed pages
483 foreach my $file (@files) {
484 my $page=pagename($file);
485 if (! $oldpagemtime{$page}) {
486 debug("new page $page");
489 $pagesources{$page}=$file;
493 foreach my $page (keys %oldpagemtime) {
494 if (! $exists{$page}) {
495 debug("removing old page $page");
496 push @del, $renderedfiles{$page};
497 prune($destdir."/".$renderedfiles{$page});
498 delete $renderedfiles{$page};
499 $oldpagemtime{$page}=0;
500 delete $pagesources{$page};
504 # render any updated files
505 foreach my $file (@files) {
506 my $page=pagename($file);
508 if (! exists $oldpagemtime{$page} ||
509 mtime("$srcdir/$file") > $oldpagemtime{$page}) {
510 debug("rendering changed file $file");
516 # if any files were added or removed, check to see if each page
517 # needs an update due to linking to them
518 # TODO: inefficient; pages may get rendered above and again here;
519 # problem is the bestlink may have changed and we won't know until
522 FILE: foreach my $file (@files) {
523 my $page=pagename($file);
524 foreach my $f (@add, @del) {
526 foreach my $link (@{$links{$page}}) {
527 if (bestlink($page, $link) eq $p) {
528 debug("rendering $file, which links to $p");
538 # handle backlinks; if a page has added/removed links, update the
540 # TODO: inefficient; pages may get rendered above and again here;
541 # problem is the backlinks could be wrong in the first pass render
545 foreach my $file (keys %rendered, @del) {
546 my $page=pagename($file);
547 if (exists $links{$page}) {
548 foreach my $link (@{$links{$page}}) {
549 $link=bestlink($page, $link);
551 ! exists $oldlinks{$page} ||
552 ! grep { $_ eq $link } @{$oldlinks{$page}}) {
553 $linkchanged{$link}=1;
557 if (exists $oldlinks{$page}) {
558 foreach my $link (@{$oldlinks{$page}}) {
559 $link=bestlink($page, $link);
561 ! exists $links{$page} ||
562 ! grep { $_ eq $link } @{$links{$page}}) {
563 $linkchanged{$link}=1;
568 foreach my $link (keys %linkchanged) {
569 my $linkfile=$pagesources{$link};
570 if (defined $linkfile) {
571 debug("rendering $linkfile, to update its backlinks");
578 # Generates a C wrapper program for running ikiwiki in a specific way.
579 # The wrapper may be safely made suid.
580 sub gen_wrapper ($$) { #{{{
581 my ($svn, $rebuild)=@_;
583 eval q{use Cwd 'abs_path'};
584 $srcdir=abs_path($srcdir);
585 $destdir=abs_path($destdir);
586 my $this=abs_path($0);
588 error("$this doesn't seem to be executable");
591 my @params=($srcdir, $destdir, "--wikiname=$wikiname");
592 push @params, "--verbose" if $verbose;
593 push @params, "--rebuild" if $rebuild;
594 push @params, "--nosvn" if !$svn;
595 push @params, "--cgi" if $cgi;
596 push @params, "--url=$url" if $url;
597 push @params, "--cgiurl=$cgiurl" if $cgiurl;
598 push @params, "--historyurl=$historyurl" if $historyurl;
599 my $params=join(" ", @params);
601 foreach my $p ($this, $this, @params) {
607 push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
608 CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
609 HTTP_COOKIE} if $cgi;
611 foreach my $var (@envsave) {
613 if ((s=getenv("$var")))
614 asprintf(&newenviron[i++], "%s=%s", "$var", s);
618 open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
620 /* A wrapper for ikiwiki, can be safely made suid. */
627 extern char **environ;
629 int main (int argc, char **argv) {
630 /* Sanitize environment. */
632 char *newenviron[$#envsave+3];
635 newenviron[i++]="HOME=$ENV{HOME}";
639 if (argc == 2 && strcmp(argv[1], "--params") == 0) {
640 printf("$params\\n");
645 perror("failed to run $this");
650 if (system("gcc", "ikiwiki-wrap.c", "-o", "ikiwiki-wrap") != 0) {
651 error("failed to compile ikiwiki-wrap.c");
653 unlink("ikiwiki-wrap.c");
654 print "successfully generated ikiwiki-wrap\n";
658 sub cgi_recentchanges ($) { #{{{
664 foreach my $change (rcs_recentchanges(100)) {
666 $list.=join(", ", map { htmllink("", $_, 1) } @{$change->{pages}});
668 $list.="changed ".$change->{when}." by ".
669 htmllink("", $change->{user}, 1).
670 ": <i>".$change->{message}."</i>\n";
676 $q->start_html("RecentChanges"),
677 $q->h1(indexlink()." RecentChanges"),
683 sub cgi_signin ($$) { #{{{
687 eval q{use CGI::FormBuilder};
688 my $form = CGI::FormBuilder->new(
689 title => "$wikiname signin",
690 fields => [qw(do page name password confirm_password email)],
695 confirm_password => {
696 perl => q{eq $form->field("password")},
703 action => $q->request_uri,
706 $form->sessionid($session->id);
707 $form->field(name => "name", required => 0);
708 $form->field(name => "do", type => "hidden");
709 $form->field(name => "page", type => "hidden");
710 $form->field(name => "password", type => "password", required => 0);
711 $form->field(name => "confirm_password", type => "password", required => 0);
712 $form->field(name => "email", required => 0);
713 if ($session->param("name")) {
714 $form->field(name => "name", value => $session->param("name"));
716 if ($q->param("do") ne "signin") {
717 $form->text("You need to log in before you can edit pages.");
720 if ($form->submitted) {
721 # Set required fields based on how form was submitted.
723 "Login" => [qw(name password)],
724 "Register" => [qw(name password confirm_password email)],
725 "Mail Password" => [qw(name)],
727 foreach my $opt (@{$required{$form->submitted}}) {
728 $form->field(name => $opt, required => 1);
731 # Validate password differently depending on how form was
733 if ($form->submitted eq 'Login') {
737 # TODO get real user password
743 $form->field(name => "password", validate => 'VALUE');
747 # Comments only shown first time.
748 $form->field(name => "name", comment => "use FirstnameLastName");
749 $form->field(name => "confirm_password", comment => "(only needed");
750 $form->field(name => "email", comment => "for registration)");
753 if ($form->submitted && $form->validate) {
754 if ($form->submitted eq 'Login') {
755 $session->param("name", $form->field("name"));
756 if (defined $form->field("do")) {
758 "$cgiurl?do=".$form->field("do").
759 "&page=".$form->field("page"));
765 elsif ($form->submitted eq 'Register') {
766 # TODO: save registration info
767 $form->field(name => "confirm_password", type => "hidden");
768 $form->field(name => "email", type => "hidden");
769 $form->text("Registration successful. Now you can Login.");
770 print $form->render(submit => ["Login"]);;
772 elsif ($form->submitted eq 'Mail Password') {
774 $form->text("Your password has been emailed to you.");
775 print $form->render(submit => ["Login", "Register", "Mail Password"]);;
779 print $form->render(submit => ["Login", "Register", "Mail Password"]);;
785 eval q{use CGI::Session};
788 # session id has to be _sessionid for CGI::FormBuilder to work.
789 # TODO: stop having the formbuilder emit cookies and change session
790 # id to something else.
791 CGI::Session->name("_sessionid");
792 my $session = CGI::Session->new(undef, $q,
793 { Directory=> "$srcdir/.ikiwiki/sessions" });
795 my $do=$q->param('do');
796 if (! defined $do || ! length $do) {
797 error("\"do\" parameter missing");
800 if ($do eq 'recentchanges') {
801 cgi_recentchanges($q);
805 if (! defined $session->param("name") || $do eq 'signin') {
806 cgi_signin($q, $session);
810 my ($page)=$q->param('page')=~/$wiki_file_regexp/;
811 if (! defined $page || ! length $page || $page ne $q->param('page') ||
812 $page=~/$wiki_file_prune_regexp/ || $page=~/^\//) {
813 error("bad page name");
817 my $action=$q->request_uri;
820 if ($do eq 'create') {
821 if (exists $pagesources{lc($page)}) {
822 # hmm, someone else made the page in the meantime?
823 print $q->redirect("$url/".htmlpage($page));
827 my ($from)=$q->param('from')=~/$wiki_file_regexp/;
828 if (! defined $from || ! length $from ||
829 $from ne $q->param('from') ||
830 $from=~/$wiki_file_prune_regexp/ || $from=~/^\//) {
836 push @page_locs, $dir.$page;
837 push @page_locs, "$from/$page";
838 while (length $dir) {
840 push @page_locs, $dir.$page;
844 $q->param("do", "save");
846 $q->start_html("Creating $page"),
847 $q->h1(indexlink()." Creating $page"),
848 $q->start_form(-action => $action),
850 "Select page location:",
851 $q->popup_menu('page', \@page_locs),
852 $q->textarea(-name => 'content',
857 "Optional comment about this change:",
859 $q->textfield(-name => "comments", -size => 80),
861 $q->submit("Save Page"),
865 elsif ($do eq 'edit') {
867 if (exists $pagesources{lc($page)}) {
868 $content=readfile("$srcdir/$pagesources{lc($page)}");
869 $content=~s/\n/\r\n/g;
871 $q->param("do", "save");
873 $q->start_html("Editing $page"),
874 $q->h1(indexlink()." Editing $page"),
875 $q->start_form(-action => $action),
878 $q->textarea(-name => 'content',
879 -default => $content,
883 "Optional comment about this change:",
885 $q->textfield(-name => "comments", -size => 80),
887 $q->submit("Save Page"),
891 elsif ($do eq 'save') {
892 my $file=$page.$default_pagetype;
894 if (exists $pagesources{lc($page)}) {
895 $file=$pagesources{lc($page)};
899 my $content=$q->param('content');
900 $content=~s/\r\n/\n/g;
902 writefile("$srcdir/$file", $content);
904 my $message="web commit from $ENV{REMOTE_ADDR}";
905 if (defined $q->param('comments')) {
906 $message.=": ".$q->param('comments');
913 # presumably the commit will trigger an update
915 rcs_commit($message);
921 print $q->redirect("$url/".htmlpage($page));
924 error("unknown do parameter");
931 if (grep /^-/, @ARGV) {
932 eval {use Getopt::Long};
934 "wikiname=s" => \$wikiname,
935 "verbose|v" => \$verbose,
936 "rebuild" => \$rebuild,
937 "wrapper" => \$wrapper,
941 "cgiurl=s" => \$cgiurl,
942 "historyurl=s" => \$historyurl,
945 usage() unless @ARGV == 3;
946 ($srcdir) = possibly_foolish_untaint(shift);
947 ($templatedir) = possibly_foolish_untaint(shift);
948 ($destdir) = possibly_foolish_untaint(shift);
950 if ($cgi && ! length $url) {
951 error("Must specify url to wiki with --url when using --cgi");
954 gen_wrapper($svn, $rebuild) if $wrapper;
957 loadindex() unless $rebuild;
962 rcs_update() if $svn;