3 eval 'exec /usr/bin/perl -T -S $0 ${1+"$@"}'
4 if 0; # not running under some shell
5 $ENV{PATH}="/usr/local/bin:/usr/bin:/bin";
14 my (%links, %oldlinks, %oldpagemtime, %renderedfiles, %pagesources);
16 # Holds global config settings, also used by some modules.
18 wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.html?$)},
19 wiki_link_regexp => qr/\[\[([^\s\]]+)\]\]/,
20 wiki_file_regexp => qr/(^[-A-Za-z0-9_.:\/+]+$)/,
23 default_pageext => ".mdwn",
42 "setup=s" => \$config{setup},
43 "wikiname=s" => \$config{wikiname},
44 "verbose|v!" => \$config{verbose},
45 "rebuild!" => \$config{rebuild},
46 "wrapper=s" => sub { $config{wrapper}=$_[1] ? $_[1] : "ikiwiki-wrap" },
47 "wrappermode=i" => \$config{wrappermode},
48 "svn!" => \$config{svn},
49 "anonok!" => \$config{anonok},
50 "cgi!" => \$config{cgi},
51 "url=s" => \$config{url},
52 "cgiurl=s" => \$config{cgiurl},
53 "historyurl=s" => \$config{historyurl},
54 "diffurl=s" => \$config{diffurl},
56 $config{wiki_file_prune_regexp}=qr/$config{wiki_file_prune_regexp}|$_[1]/;
58 "adminuser=s@" => sub { push @{$config{adminuser}}, $_[1] },
61 if (! $config{setup}) {
62 usage() unless @ARGV == 3;
63 $config{srcdir} = possibly_foolish_untaint(shift);
64 $config{templatedir} = possibly_foolish_untaint(shift);
65 $config{destdir} = possibly_foolish_untaint(shift);
66 if ($config{cgi} && ! length $config{url}) {
67 error("Must specify url to wiki with --url when using --cgi");
73 die "usage: ikiwiki [options] source templates dest\n";
78 print "Content-type: text/html\n\n";
79 print misctemplate("Error", "<p>Error: @_</p>");
85 return unless $config{verbose};
97 return (stat($page))[9];
100 sub possibly_foolish_untaint { #{{{
102 my ($untainted)=$tainted=~/(.*)/;
106 sub basename ($) { #{{{
113 sub dirname ($) { #{{{
120 sub pagetype ($) { #{{{
123 if ($page =~ /\.mdwn$/) {
131 sub pagename ($) { #{{{
134 my $type=pagetype($file);
136 $page=~s/\Q$type\E*$// unless $type eq 'unknown';
140 sub htmlpage ($) { #{{{
143 return $page.".html";
146 sub readfile ($) { #{{{
150 open (IN, "$file") || error("failed to read $file: $!");
156 sub writefile ($$) { #{{{
160 my $dir=dirname($file);
163 foreach my $s (split(m!/+!, $dir)) {
166 mkdir($d) || error("failed to create directory $d: $!");
171 open (OUT, ">$file") || error("failed to write $file: $!");
176 sub findlinks ($$) { #{{{
181 while ($content =~ /(?<!\\)$config{wiki_link_regexp}/g) {
184 # Discussion links are a special case since they're not in the text
185 # of the page, but on its template.
186 return @links, "$page/discussion";
189 sub bestlink ($$) { #{{{
190 # Given a page and the text of a link on the page, determine which
191 # existing page that link best points to. Prefers pages under a
192 # subdirectory with the same name as the source page, failing that
193 # goes down the directory tree to the base looking for matching
201 $l.="/" if length $l;
204 if (exists $links{$l}) {
205 #debug("for $page, \"$link\", use $l");
208 } while $cwd=~s!/?[^/]+$!!;
210 #print STDERR "warning: page $page, broken link: $link\n";
214 sub isinlinableimage ($) { #{{{
217 $file=~/\.(png|gif|jpg|jpeg)$/;
223 my $noimageinline=shift; # don't turn links into inline html images
224 my $forcesubpage=shift; # force a link to a subpage
227 if (! $forcesubpage) {
228 $bestlink=bestlink($page, $link);
231 $bestlink="$page/".lc($link);
234 return $link if length $bestlink && $page eq $bestlink;
236 # TODO BUG: %renderedfiles may not have it, if the linked to page
237 # was also added and isn't yet rendered! Note that this bug is
238 # masked by the bug mentioned below that makes all new files
240 if (! grep { $_ eq $bestlink } values %renderedfiles) {
241 $bestlink=htmlpage($bestlink);
243 if (! grep { $_ eq $bestlink } values %renderedfiles) {
244 return "<a href=\"$config{cgiurl}?do=create&page=$link&from=$page\">?</a>$link"
247 $bestlink=File::Spec->abs2rel($bestlink, dirname($page));
249 if (! $noimageinline && isinlinableimage($bestlink)) {
250 return "<img src=\"$bestlink\">";
252 return "<a href=\"$bestlink\">$link</a>";
255 sub linkify ($$) { #{{{
259 $content =~ s{(\\?)$config{wiki_link_regexp}}{
260 $1 ? "[[$2]]" : htmllink($page, $2)
266 sub htmlize ($$) { #{{{
270 if (! $INC{"/usr/bin/markdown"}) {
272 $blosxom::version="is a proper perl module too much to ask?";
274 do "/usr/bin/markdown";
277 if ($type eq '.mdwn') {
278 return Markdown::Markdown($content);
281 error("htmlization of $type not supported");
285 sub backlinks ($) { #{{{
289 foreach my $p (keys %links) {
290 next if bestlink($page, $p) eq $page;
291 if (grep { length $_ && bestlink($p, $_) eq $page } @{$links{$p}}) {
292 my $href=File::Spec->abs2rel(htmlpage($p), dirname($page));
294 # Trim common dir prefixes from both pages.
296 my $page_trimmed=$page;
298 1 while (($dir)=$page_trimmed=~m!^([^/]+/)!) &&
300 $p_trimmed=~s/^\Q$dir\E// &&
301 $page_trimmed=~s/^\Q$dir\E//;
303 push @links, { url => $href, page => $p_trimmed };
307 return sort { $a->{page} cmp $b->{page} } @links;
310 sub parentlinks ($) { #{{{
317 foreach my $dir (reverse split("/", $page)) {
320 unshift @ret, { url => "$path$dir.html", page => $dir };
326 unshift @ret, { url => length $path ? $path : ".", page => $config{wikiname} };
330 sub indexlink () { #{{{
331 return "<a href=\"$config{url}\">$config{wikiname}</a>";
334 sub finalize ($$$) { #{{{
339 my $title=basename($page);
342 my $template=HTML::Template->new(blind_cache => 1,
343 filename => "$config{templatedir}/page.tmpl");
345 if (length $config{cgiurl}) {
346 $template->param(editurl => "$config{cgiurl}?do=edit&page=$page");
347 $template->param(prefsurl => "$config{cgiurl}?do=prefs");
349 $template->param(recentchangesurl => "$config{cgiurl}?do=recentchanges");
353 if (length $config{historyurl}) {
354 my $u=$config{historyurl};
355 $u=~s/\[\[file\]\]/$pagesources{$page}/g;
356 $template->param(historyurl => $u);
361 wikiname => $config{wikiname},
362 parentlinks => [parentlinks($page)],
364 backlinks => [backlinks($page)],
365 discussionlink => htmllink($page, "Discussion", 1, 1),
366 mtime => scalar(gmtime($mtime)),
369 return $template->output;
372 sub check_overwrite ($$) { #{{{
373 # Important security check. Make sure to call this before saving
374 # any files to the source directory.
378 if (! exists $renderedfiles{$src} && -e $dest && ! $config{rebuild}) {
379 error("$dest already exists and was rendered from ".
380 join(" ",(grep { $renderedfiles{$_} eq $dest } keys
382 ", before, so not rendering from $src");
386 sub render ($) { #{{{
389 my $type=pagetype($file);
390 my $content=readfile("$config{srcdir}/$file");
391 if ($type ne 'unknown') {
392 my $page=pagename($file);
394 $links{$page}=[findlinks($content, $page)];
396 $content=linkify($content, $page);
397 $content=htmlize($type, $content);
398 $content=finalize($content, $page,
399 mtime("$config{srcdir}/$file"));
401 check_overwrite("$config{destdir}/".htmlpage($page), $page);
402 writefile("$config{destdir}/".htmlpage($page), $content);
403 $oldpagemtime{$page}=time;
404 $renderedfiles{$page}=htmlpage($page);
408 check_overwrite("$config{destdir}/$file", $file);
409 writefile("$config{destdir}/$file", $content);
410 $oldpagemtime{$file}=time;
411 $renderedfiles{$file}=$file;
415 sub lockwiki () { #{{{
416 # Take an exclusive lock on the wiki to prevent multiple concurrent
417 # run issues. The lock will be dropped on program exit.
418 if (! -d "$config{srcdir}/.ikiwiki") {
419 mkdir("$config{srcdir}/.ikiwiki");
421 open(WIKILOCK, ">$config{srcdir}/.ikiwiki/lockfile") || error ("cannot write to lockfile: $!");
422 if (! flock(WIKILOCK, 2 | 4)) {
423 debug("wiki seems to be locked, waiting for lock");
424 my $wait=600; # arbitrary, but don't hang forever to
425 # prevent process pileup
427 return if flock(WIKILOCK, 2 | 4);
430 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
434 sub unlockwiki () { #{{{
438 sub loadindex () { #{{{
439 open (IN, "$config{srcdir}/.ikiwiki/index") || return;
441 $_=possibly_foolish_untaint($_);
443 my ($mtime, $file, $rendered, @links)=split(' ', $_);
444 my $page=pagename($file);
445 $pagesources{$page}=$file;
446 $oldpagemtime{$page}=$mtime;
447 $oldlinks{$page}=[@links];
448 $links{$page}=[@links];
449 $renderedfiles{$page}=$rendered;
454 sub saveindex () { #{{{
455 if (! -d "$config{srcdir}/.ikiwiki") {
456 mkdir("$config{srcdir}/.ikiwiki");
458 open (OUT, ">$config{srcdir}/.ikiwiki/index") || error("cannot write to index: $!");
459 foreach my $page (keys %oldpagemtime) {
460 print OUT "$oldpagemtime{$page} $pagesources{$page} $renderedfiles{$page} ".
461 join(" ", @{$links{$page}})."\n"
462 if $oldpagemtime{$page};
467 sub rcs_update () { #{{{
468 if (-d "$config{srcdir}/.svn") {
469 if (system("svn", "update", "--quiet", $config{srcdir}) != 0) {
470 warn("svn update failed\n");
475 sub rcs_prepedit ($) { #{{{
476 # Prepares to edit a file under revision control. Returns a token
477 # that must be passed into rcs_commit when the file is ready
479 # The file is relative to the srcdir.
482 if (-d "$config{srcdir}/.svn") {
483 # For subversion, return the revision of the file when
485 my $rev=svn_info("Revision", "$config{srcdir}/$file");
486 return defined $rev ? $rev : "";
490 sub rcs_commit ($$$) { #{{{
491 # Tries to commit the page; returns undef on _success_ and
492 # a version of the page with the rcs's conflict markers on failure.
493 # The file is relative to the srcdir.
498 if (-d "$config{srcdir}/.svn") {
499 # Check to see if the page has been changed by someone
500 # else since rcs_prepedit was called.
501 my ($oldrev)=$rcstoken=~/^([0-9]+)$/; # untaint
502 my $rev=svn_info("Revision", "$config{srcdir}/$file");
503 if (defined $rev && defined $oldrev && $rev != $oldrev) {
504 # Merge their changes into the file that we've
506 chdir($config{srcdir}); # svn merge wants to be here
507 if (system("svn", "merge", "--quiet", "-r$oldrev:$rev",
508 "$config{srcdir}/$file") != 0) {
509 warn("svn merge -r$oldrev:$rev failed\n");
513 if (system("svn", "commit", "--quiet", "-m",
514 possibly_foolish_untaint($message),
515 "$config{srcdir}") != 0) {
516 my $conflict=readfile("$config{srcdir}/$file");
517 if (system("svn", "revert", "--quiet", "$config{srcdir}/$file") != 0) {
518 warn("svn revert failed\n");
523 return undef # success
526 sub rcs_add ($) { #{{{
527 # filename is relative to the root of the srcdir
530 if (-d "$config{srcdir}/.svn") {
531 my $parent=dirname($file);
532 while (! -d "$config{srcdir}/$parent/.svn") {
534 $parent=dirname($file);
537 if (system("svn", "add", "--quiet", "$config{srcdir}/$file") != 0) {
538 warn("svn add failed\n");
543 sub svn_info ($$) { #{{{
547 my $info=`LANG=C svn info $file`;
548 my ($ret)=$info=~/^$field: (.*)$/m;
552 sub rcs_recentchanges ($) { #{{{
556 eval q{use CGI 'escapeHTML'};
557 eval q{use Date::Parse};
558 eval q{use Time::Duration};
560 if (-d "$config{srcdir}/.svn") {
561 my $svn_url=svn_info("URL", $config{srcdir});
563 # FIXME: currently assumes that the wiki is somewhere
564 # under trunk in svn, doesn't support other layouts.
565 my ($svn_base)=$svn_url=~m!(/trunk(?:/.*)?)$!;
567 my $div=qr/^--------------------+$/;
568 my $infoline=qr/^r(\d+)\s+\|\s+([^\s]+)\s+\|\s+(\d+-\d+-\d+\s+\d+:\d+:\d+\s+[-+]?\d+).*/;
570 my ($rev, $user, $when, @pages, @message);
571 foreach (`LANG=C svn log --limit $num -v '$svn_url'`) {
573 if ($state eq 'start' && /$div/) {
576 elsif ($state eq 'header' && /$infoline/) {
579 $when=concise(ago(time - str2time($3)));
581 elsif ($state eq 'header' && /^\s+[A-Z]\s+\Q$svn_base\E\/([^ ]+)(?:$|\s)/) {
583 my $diffurl=$config{diffurl};
584 $diffurl=~s/\[\[file\]\]/$file/g;
585 $diffurl=~s/\[\[r1\]\]/$rev - 1/eg;
586 $diffurl=~s/\[\[r2\]\]/$rev/g;
588 link => htmllink("", pagename($file), 1),
592 elsif ($state eq 'header' && /^$/) {
595 elsif ($state eq 'body' && /$div/) {
596 my $committype="web";
597 if (defined $message[0] &&
598 $message[0]->{line}=~/^web commit by (\w+):?(.*)/) {
600 $message[0]->{line}=$2;
606 push @ret, { rev => $rev,
607 user => htmllink("", $user, 1),
608 committype => $committype,
609 when => $when, message => [@message],
612 return @ret if @ret >= $num;
615 $rev=$user=$when=undef;
618 elsif ($state eq 'body') {
619 push @message, {line => escapeHTML($_)},
631 my $dir=dirname($file);
632 while (rmdir($dir)) {
637 sub refresh () { #{{{
638 # find existing pages
641 eval q{use File::Find};
645 if (/$config{wiki_file_prune_regexp}/) {
647 $File::Find::prune=1;
650 elsif (! -d $_ && ! -l $_) {
651 my ($f)=/$config{wiki_file_regexp}/; # untaint
653 warn("skipping bad filename $_\n");
656 $f=~s/^\Q$config{srcdir}\E\/?//;
658 $exists{pagename($f)}=1;
666 # check for added or removed pages
668 foreach my $file (@files) {
669 my $page=pagename($file);
670 if (! $oldpagemtime{$page}) {
671 debug("new page $page");
674 $pagesources{$page}=$file;
678 foreach my $page (keys %oldpagemtime) {
679 if (! $exists{$page}) {
680 debug("removing old page $page");
681 push @del, $pagesources{$page};
682 prune($config{destdir}."/".$renderedfiles{$page});
683 delete $renderedfiles{$page};
684 $oldpagemtime{$page}=0;
685 delete $pagesources{$page};
689 # render any updated files
690 foreach my $file (@files) {
691 my $page=pagename($file);
693 if (! exists $oldpagemtime{$page} ||
694 mtime("$config{srcdir}/$file") > $oldpagemtime{$page}) {
695 debug("rendering changed file $file");
701 # if any files were added or removed, check to see if each page
702 # needs an update due to linking to them
703 # TODO: inefficient; pages may get rendered above and again here;
704 # problem is the bestlink may have changed and we won't know until
707 FILE: foreach my $file (@files) {
708 my $page=pagename($file);
709 foreach my $f (@add, @del) {
711 foreach my $link (@{$links{$page}}) {
712 if (bestlink($page, $link) eq $p) {
713 debug("rendering $file, which links to $p");
723 # handle backlinks; if a page has added/removed links, update the
725 # TODO: inefficient; pages may get rendered above and again here;
726 # problem is the backlinks could be wrong in the first pass render
730 foreach my $file (keys %rendered, @del) {
731 my $page=pagename($file);
732 if (exists $links{$page}) {
733 foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
735 ! exists $oldlinks{$page} ||
736 ! grep { $_ eq $link } @{$oldlinks{$page}}) {
737 $linkchanged{$link}=1;
741 if (exists $oldlinks{$page}) {
742 foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
744 ! exists $links{$page} ||
745 ! grep { $_ eq $link } @{$links{$page}}) {
746 $linkchanged{$link}=1;
751 foreach my $link (keys %linkchanged) {
752 my $linkfile=$pagesources{$link};
753 if (defined $linkfile) {
754 debug("rendering $linkfile, to update its backlinks");
761 sub gen_wrapper (@) { #{{{
763 eval q{use Cwd 'abs_path'};
764 $config{srcdir}=abs_path($config{srcdir});
765 $config{destdir}=abs_path($config{destdir});
766 my $this=abs_path($0);
768 error("$this doesn't seem to be executable");
771 if ($config{setup}) {
772 error("cannot create a wrapper that uses a setup file");
775 my @params=($config{srcdir}, $config{templatedir}, $config{destdir},
776 "--wikiname=$config{wikiname}");
777 push @params, "--verbose" if $config{verbose};
778 push @params, "--rebuild" if $config{rebuild};
779 push @params, "--nosvn" if !$config{svn};
780 push @params, "--cgi" if $config{cgi};
781 push @params, "--url=$config{url}" if length $config{url};
782 push @params, "--cgiurl=$config{cgiurl}" if length $config{cgiurl};
783 push @params, "--historyurl=$config{historyurl}" if length $config{historyurl};
784 push @params, "--diffurl=$config{diffurl}" if length $config{diffurl};
785 push @params, "--anonok" if $config{anonok};
786 push @params, "--adminuser=$_" foreach @{$config{adminuser}};
787 my $params=join(" ", @params);
789 foreach my $p ($this, $this, @params) {
795 push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
796 CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
797 HTTP_COOKIE} if $config{cgi};
799 foreach my $var (@envsave) {
801 if ((s=getenv("$var")))
802 asprintf(&newenviron[i++], "%s=%s", "$var", s);
806 open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
808 /* A wrapper for ikiwiki, can be safely made suid. */
815 extern char **environ;
817 int main (int argc, char **argv) {
818 /* Sanitize environment. */
820 char *newenviron[$#envsave+3];
823 newenviron[i++]="HOME=$ENV{HOME}";
827 if (argc == 2 && strcmp(argv[1], "--params") == 0) {
828 printf("$params\\n");
833 perror("failed to run $this");
838 if (system("gcc", "ikiwiki-wrap.c", "-o", possibly_foolish_untaint($config{wrapper})) != 0) {
839 error("failed to compile ikiwiki-wrap.c");
841 unlink("ikiwiki-wrap.c");
842 if (defined $config{wrappermode} &&
843 ! chmod(oct($config{wrappermode}), possibly_foolish_untaint($config{wrapper}))) {
844 error("chmod $config{wrapper}: $!");
846 print "successfully generated $config{wrapper}\n";
849 sub misctemplate ($$) { #{{{
853 my $template=HTML::Template->new(
854 filename => "$config{templatedir}/misc.tmpl"
858 indexlink => indexlink(),
859 wikiname => $config{wikiname},
860 pagebody => $pagebody,
862 return $template->output;
865 sub cgi_recentchanges ($) { #{{{
868 my $template=HTML::Template->new(
869 filename => "$config{templatedir}/recentchanges.tmpl"
872 title => "RecentChanges",
873 indexlink => indexlink(),
874 wikiname => $config{wikiname},
875 changelog => [rcs_recentchanges(100)],
877 print $q->header, $template->output;
880 sub userinfo_get ($$) { #{{{
884 eval q{use Storable};
885 my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
886 if (! defined $userdata || ! ref $userdata ||
887 ! exists $userdata->{$user} || ! ref $userdata->{$user} ||
888 ! exists $userdata->{$user}->{$field}) {
891 return $userdata->{$user}->{$field};
894 sub userinfo_set ($$$) { #{{{
899 eval q{use Storable};
900 my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
901 if (! defined $userdata || ! ref $userdata ||
902 ! exists $userdata->{$user} || ! ref $userdata->{$user}) {
906 $userdata->{$user}->{$field}=$value;
907 my $oldmask=umask(077);
908 my $ret=Storable::lock_store($userdata, "$config{srcdir}/.ikiwiki/userdb");
913 sub userinfo_setall ($$) { #{{{
917 eval q{use Storable};
918 my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
919 if (! defined $userdata || ! ref $userdata) {
922 $userdata->{$user}=$info;
923 my $oldmask=umask(077);
924 my $ret=Storable::lock_store($userdata, "$config{srcdir}/.ikiwiki/userdb");
929 sub cgi_signin ($$) { #{{{
933 eval q{use CGI::FormBuilder};
934 my $form = CGI::FormBuilder->new(
936 fields => [qw(do page from name password confirm_password email)],
940 confirm_password => {
941 perl => q{eq $form->field("password")},
948 action => $q->request_uri,
950 template => (-e "$config{templatedir}/signin.tmpl" ?
951 "$config{templatedir}/signin.tmpl" : "")
954 $form->field(name => "name", required => 0);
955 $form->field(name => "do", type => "hidden");
956 $form->field(name => "page", type => "hidden");
957 $form->field(name => "from", type => "hidden");
958 $form->field(name => "password", type => "password", required => 0);
959 $form->field(name => "confirm_password", type => "password", required => 0);
960 $form->field(name => "email", required => 0);
961 if ($q->param("do") ne "signin") {
962 $form->text("You need to log in first.");
965 if ($form->submitted) {
966 # Set required fields based on how form was submitted.
968 "Login" => [qw(name password)],
969 "Register" => [qw(name password confirm_password email)],
970 "Mail Password" => [qw(name)],
972 foreach my $opt (@{$required{$form->submitted}}) {
973 $form->field(name => $opt, required => 1);
976 # Validate password differently depending on how
977 # form was submitted.
978 if ($form->submitted eq 'Login') {
982 length $form->field("name") &&
983 shift eq userinfo_get($form->field("name"), 'password');
986 $form->field(name => "name", validate => '/^\w+$/');
989 $form->field(name => "password", validate => 'VALUE');
991 # And make sure the entered name exists when logging
992 # in or sending email, and does not when registering.
993 if ($form->submitted eq 'Register') {
999 ! userinfo_get($name, "regdate");
1009 userinfo_get($name, "regdate");
1015 # First time settings.
1016 $form->field(name => "name", comment => "use FirstnameLastName");
1017 $form->field(name => "confirm_password", comment => "(only needed");
1018 $form->field(name => "email", comment => "for registration)");
1019 if ($session->param("name")) {
1020 $form->field(name => "name", value => $session->param("name"));
1024 if ($form->submitted && $form->validate) {
1025 if ($form->submitted eq 'Login') {
1026 $session->param("name", $form->field("name"));
1027 if (defined $form->field("do") &&
1028 $form->field("do") ne 'signin') {
1030 "$config{cgiurl}?do=".$form->field("do").
1031 "&page=".$form->field("page").
1032 "&from=".$form->field("from"));;
1035 print $q->redirect($config{url});
1038 elsif ($form->submitted eq 'Register') {
1039 my $user_name=$form->field('name');
1040 if (userinfo_setall($user_name, {
1041 'email' => $form->field('email'),
1042 'password' => $form->field('password'),
1045 $form->field(name => "confirm_password", type => "hidden");
1046 $form->field(name => "email", type => "hidden");
1047 $form->text("Registration successful. Now you can Login.");
1048 print $session->header();
1049 print misctemplate($form->title, $form->render(submit => ["Login"]));
1052 error("Error saving registration.");
1055 elsif ($form->submitted eq 'Mail Password') {
1056 my $user_name=$form->field("name");
1057 my $template=HTML::Template->new(
1058 filename => "$config{templatedir}/passwordmail.tmpl"
1061 user_name => $user_name,
1062 user_password => userinfo_get($user_name, "password"),
1063 wikiurl => $config{url},
1064 wikiname => $config{wikiname},
1065 REMOTE_ADDR => $ENV{REMOTE_ADDR},
1068 eval q{use Mail::Sendmail};
1069 my ($fromhost) = $config{cgiurl} =~ m!/([^/]+)!;
1071 To => userinfo_get($user_name, "email"),
1072 From => "$config{wikiname} admin <".(getpwuid($>))[0]."@".$fromhost.">",
1073 Subject => "$config{wikiname} information",
1074 Message => $template->output,
1075 ) or error("Failed to send mail");
1077 $form->text("Your password has been emailed to you.");
1078 $form->field(name => "name", required => 0);
1079 print $session->header();
1080 print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
1084 print $session->header();
1085 print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
1089 sub is_admin ($) { #{{{
1090 my $user_name=shift;
1092 return grep { $_ eq $user_name } @{$config{adminuser}};
1095 sub glob_match ($$) { #{{{
1099 # turn glob into safe regexp
1100 $glob=quotemeta($glob);
1108 sub globlist_match ($$) { #{{{
1110 my @globlist=split(" ", shift);
1112 # check any negated globs first
1113 foreach my $glob (@globlist) {
1114 return 0 if $glob=~/^!(.*)/ && glob_match($page, $1);
1117 foreach my $glob (@globlist) {
1118 return 1 if glob_match($page, $glob);
1124 sub page_locked ($$;$) { #{{{
1129 my $user=$session->param("name");
1130 return if length $user && is_admin($user);
1132 foreach my $admin (@{$config{adminuser}}) {
1133 my $locked_pages=userinfo_get($admin, "locked_pages");
1134 if (globlist_match($page, userinfo_get($admin, "locked_pages"))) {
1135 return 1 if $nonfatal;
1136 error(htmllink("", $page, 1)." is locked by ".
1137 htmllink("", $admin, 1)." and cannot be edited.");
1144 sub cgi_prefs ($$) { #{{{
1148 eval q{use CGI::FormBuilder};
1149 my $form = CGI::FormBuilder->new(
1150 title => "preferences",
1151 fields => [qw(do name password confirm_password email locked_pages)],
1155 confirm_password => {
1156 perl => q{eq $form->field("password")},
1163 action => $q->request_uri,
1164 template => (-e "$config{templatedir}/prefs.tmpl" ?
1165 "$config{templatedir}/prefs.tmpl" : "")
1167 my @buttons=("Save Preferences", "Logout", "Cancel");
1169 my $user_name=$session->param("name");
1170 $form->field(name => "do", type => "hidden");
1171 $form->field(name => "name", disabled => 1,
1172 value => $user_name, force => 1);
1173 $form->field(name => "password", type => "password");
1174 $form->field(name => "confirm_password", type => "password");
1175 $form->field(name => "locked_pages", size => 50,
1176 comment => "(".htmllink("", "GlobList", 1).")");
1178 if (! is_admin($user_name)) {
1179 $form->field(name => "locked_pages", type => "hidden");
1182 if (! $form->submitted) {
1183 $form->field(name => "email", force => 1,
1184 value => userinfo_get($user_name, "email"));
1185 $form->field(name => "locked_pages", force => 1,
1186 value => userinfo_get($user_name, "locked_pages"));
1189 if ($form->submitted eq 'Logout') {
1191 print $q->redirect($config{url});
1194 elsif ($form->submitted eq 'Cancel') {
1195 print $q->redirect($config{url});
1198 elsif ($form->submitted eq "Save Preferences" && $form->validate) {
1199 foreach my $field (qw(password email locked_pages)) {
1200 if (length $form->field($field)) {
1201 userinfo_set($user_name, $field, $form->field($field)) || error("failed to set $field");
1204 $form->text("Preferences saved.");
1207 print $session->header();
1208 print misctemplate($form->title, $form->render(submit => \@buttons));
1211 sub cgi_editpage ($$) { #{{{
1215 eval q{use CGI::FormBuilder};
1216 my $form = CGI::FormBuilder->new(
1217 fields => [qw(do rcsinfo from page content comments)],
1223 required => [qw{content}],
1226 action => $q->request_uri,
1228 template => "$config{templatedir}/editpage.tmpl"
1230 my @buttons=("Save Page", "Preview", "Cancel");
1232 my ($page)=$form->param('page')=~/$config{wiki_file_regexp}/;
1233 if (! defined $page || ! length $page || $page ne $q->param('page') ||
1234 $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
1235 error("bad page name");
1239 my $file=$page.$config{default_pageext};
1241 if (exists $pagesources{lc($page)}) {
1242 $file=$pagesources{lc($page)};
1246 $form->field(name => "do", type => 'hidden');
1247 $form->field(name => "from", type => 'hidden');
1248 $form->field(name => "rcsinfo", type => 'hidden');
1249 $form->field(name => "page", value => "$page", force => 1);
1250 $form->field(name => "comments", type => "text", size => 80);
1251 $form->field(name => "content", type => "textarea", rows => 20,
1253 $form->tmpl_param("can_commit", $config{svn});
1254 $form->tmpl_param("indexlink", indexlink());
1255 $form->tmpl_param("helponformattinglink",
1256 htmllink("", "HelpOnFormatting", 1));
1257 if (! $form->submitted) {
1258 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
1262 if ($form->submitted eq "Cancel") {
1263 print $q->redirect("$config{url}/".htmlpage($page));
1266 elsif ($form->submitted eq "Preview") {
1267 $form->tmpl_param("page_preview",
1268 htmlize($config{default_pageext},
1269 linkify($form->field('content'), $page)));
1272 $form->tmpl_param("page_preview", "");
1274 $form->tmpl_param("page_conflict", "");
1276 if (! $form->submitted || $form->submitted eq "Preview" ||
1277 ! $form->validate) {
1278 if ($form->field("do") eq "create") {
1279 if (exists $pagesources{lc($page)}) {
1280 # hmm, someone else made the page in the
1282 print $q->redirect("$config{url}/".htmlpage($page));
1288 my ($from)=$form->param('from')=~/$config{wiki_file_regexp}/;
1289 if (! defined $from || ! length $from ||
1290 $from ne $form->param('from') ||
1291 $from=~/$config{wiki_file_prune_regexp}/ || $from=~/^\//) {
1292 @page_locs=$best_loc=$page;
1298 if ($page eq 'discussion') {
1299 $best_loc="$from/$page";
1302 $best_loc=$dir.$page;
1305 push @page_locs, $dir.$page;
1306 push @page_locs, "$from/$page";
1307 while (length $dir) {
1309 push @page_locs, $dir.$page;
1313 ! exists $pagesources{lc($_)} &&
1314 ! page_locked($_, $session, 1)
1318 $form->tmpl_param("page_select", 1);
1319 $form->field(name => "page", type => 'select',
1320 options => \@page_locs, value => $best_loc);
1321 $form->title("creating $page");
1323 elsif ($form->field("do") eq "edit") {
1324 page_locked($page, $session);
1325 if (! defined $form->field('content') ||
1326 ! length $form->field('content')) {
1328 if (exists $pagesources{lc($page)}) {
1329 $content=readfile("$config{srcdir}/$pagesources{lc($page)}");
1330 $content=~s/\n/\r\n/g;
1332 $form->field(name => "content", value => $content,
1335 $form->tmpl_param("page_select", 0);
1336 $form->field(name => "page", type => 'hidden');
1337 $form->title("editing $page");
1340 print $form->render(submit => \@buttons);
1344 page_locked($page, $session);
1346 my $content=$form->field('content');
1347 $content=~s/\r\n/\n/g;
1348 $content=~s/\r/\n/g;
1349 writefile("$config{srcdir}/$file", $content);
1351 my $message="web commit ";
1352 if (length $session->param("name")) {
1353 $message.="by ".$session->param("name");
1356 $message.="from $ENV{REMOTE_ADDR}";
1358 if (defined $form->field('comments') &&
1359 length $form->field('comments')) {
1360 $message.=": ".$form->field('comments');
1367 # prevent deadlock with post-commit hook
1369 # presumably the commit will trigger an update
1371 my $conflict=rcs_commit($file, $message,
1372 $form->field("rcsinfo"));
1374 if (defined $conflict) {
1375 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
1377 $form->tmpl_param("page_conflict", 1);
1378 $form->field("content", value => $conflict, force => 1);
1379 $form->field("do", "edit)");
1380 $form->tmpl_param("page_select", 0);
1381 $form->field(name => "page", type => 'hidden');
1382 $form->title("editing $page");
1383 print $form->render(submit => \@buttons);
1393 # The trailing question mark tries to avoid broken
1394 # caches and get the most recent version of the page.
1395 print $q->redirect("$config{url}/".htmlpage($page)."?updated");
1401 eval q{use CGI::Session};
1405 my $do=$q->param('do');
1406 if (! defined $do || ! length $do) {
1407 error("\"do\" parameter missing");
1410 # This does not need a session.
1411 if ($do eq 'recentchanges') {
1412 cgi_recentchanges($q);
1416 CGI::Session->name("ikiwiki_session");
1418 my $oldmask=umask(077);
1419 my $session = CGI::Session->new("driver:db_file", $q,
1420 { FileName => "$config{srcdir}/.ikiwiki/sessions.db" });
1423 # Everything below this point needs the user to be signed in.
1424 if ((! $config{anonok} && ! defined $session->param("name") ||
1425 ! defined $session->param("name") ||
1426 ! userinfo_get($session->param("name"), "regdate")) || $do eq 'signin') {
1427 cgi_signin($q, $session);
1429 # Force session flush with safe umask.
1430 my $oldmask=umask(077);
1437 if ($do eq 'create' || $do eq 'edit') {
1438 cgi_editpage($q, $session);
1440 elsif ($do eq 'prefs') {
1441 cgi_prefs($q, $session);
1444 error("unknown do parameter");
1448 sub setup () { # {{{
1449 my $setup=possibly_foolish_untaint($config{setup});
1450 delete $config{setup};
1451 open (IN, $setup) || error("read $setup: $!\n");
1454 ($code)=$code=~/(.*)/s;
1463 setup() if $config{setup};
1465 if ($config{wrapper}) {
1466 gen_wrapper(%config);
1469 memoize('pagename');
1470 memoize('bestlink');
1471 loadindex() unless $config{rebuild};
1476 rcs_update() if $config{svn};