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",
36 templatedir => "/usr/share/ikiwiki/templates",
42 "setup|s=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] },
59 "templatedir=s" => sub { $config{templatedir}=possibly_foolish_untaint($_[1]) },
62 if (! $config{setup}) {
63 usage() unless @ARGV == 2;
64 $config{srcdir} = possibly_foolish_untaint(shift);
65 $config{destdir} = possibly_foolish_untaint(shift);
70 sub checkoptions { #{{{
71 if ($config{cgi} && ! length $config{url}) {
72 error("Must specify url to wiki with --url when using --cgi");
74 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
75 unless exists $config{wikistatedir};
79 die "usage: ikiwiki [options] source dest\n";
84 print "Content-type: text/html\n\n";
85 print misctemplate("Error", "<p>Error: @_</p>");
91 return unless $config{verbose};
103 return (stat($page))[9];
106 sub possibly_foolish_untaint { #{{{
108 my ($untainted)=$tainted=~/(.*)/;
112 sub basename ($) { #{{{
119 sub dirname ($) { #{{{
126 sub pagetype ($) { #{{{
129 if ($page =~ /\.mdwn$/) {
137 sub pagename ($) { #{{{
140 my $type=pagetype($file);
142 $page=~s/\Q$type\E*$// unless $type eq 'unknown';
146 sub htmlpage ($) { #{{{
149 return $page.".html";
152 sub readfile ($) { #{{{
156 open (IN, "$file") || error("failed to read $file: $!");
162 sub writefile ($$) { #{{{
166 my $dir=dirname($file);
169 foreach my $s (split(m!/+!, $dir)) {
172 mkdir($d) || error("failed to create directory $d: $!");
177 open (OUT, ">$file") || error("failed to write $file: $!");
182 sub findlinks ($$) { #{{{
187 while ($content =~ /(?<!\\)$config{wiki_link_regexp}/g) {
190 # Discussion links are a special case since they're not in the text
191 # of the page, but on its template.
192 return @links, "$page/discussion";
195 sub bestlink ($$) { #{{{
196 # Given a page and the text of a link on the page, determine which
197 # existing page that link best points to. Prefers pages under a
198 # subdirectory with the same name as the source page, failing that
199 # goes down the directory tree to the base looking for matching
207 $l.="/" if length $l;
210 if (exists $links{$l}) {
211 #debug("for $page, \"$link\", use $l");
214 } while $cwd=~s!/?[^/]+$!!;
216 #print STDERR "warning: page $page, broken link: $link\n";
220 sub isinlinableimage ($) { #{{{
223 $file=~/\.(png|gif|jpg|jpeg)$/;
229 my $noimageinline=shift; # don't turn links into inline html images
230 my $forcesubpage=shift; # force a link to a subpage
233 if (! $forcesubpage) {
234 $bestlink=bestlink($page, $link);
237 $bestlink="$page/".lc($link);
240 return $link if length $bestlink && $page eq $bestlink;
242 # TODO BUG: %renderedfiles may not have it, if the linked to page
243 # was also added and isn't yet rendered! Note that this bug is
244 # masked by the bug mentioned below that makes all new files
246 if (! grep { $_ eq $bestlink } values %renderedfiles) {
247 $bestlink=htmlpage($bestlink);
249 if (! grep { $_ eq $bestlink } values %renderedfiles) {
250 return "<a href=\"$config{cgiurl}?do=create&page=$link&from=$page\">?</a>$link"
253 $bestlink=File::Spec->abs2rel($bestlink, dirname($page));
255 if (! $noimageinline && isinlinableimage($bestlink)) {
256 return "<img src=\"$bestlink\">";
258 return "<a href=\"$bestlink\">$link</a>";
261 sub linkify ($$) { #{{{
265 $content =~ s{(\\?)$config{wiki_link_regexp}}{
266 $1 ? "[[$2]]" : htmllink($page, $2)
272 sub htmlize ($$) { #{{{
276 if (! $INC{"/usr/bin/markdown"}) {
278 $blosxom::version="is a proper perl module too much to ask?";
280 do "/usr/bin/markdown";
283 if ($type eq '.mdwn') {
284 return Markdown::Markdown($content);
287 error("htmlization of $type not supported");
291 sub backlinks ($) { #{{{
295 foreach my $p (keys %links) {
296 next if bestlink($page, $p) eq $page;
297 if (grep { length $_ && bestlink($p, $_) eq $page } @{$links{$p}}) {
298 my $href=File::Spec->abs2rel(htmlpage($p), dirname($page));
300 # Trim common dir prefixes from both pages.
302 my $page_trimmed=$page;
304 1 while (($dir)=$page_trimmed=~m!^([^/]+/)!) &&
306 $p_trimmed=~s/^\Q$dir\E// &&
307 $page_trimmed=~s/^\Q$dir\E//;
309 push @links, { url => $href, page => $p_trimmed };
313 return sort { $a->{page} cmp $b->{page} } @links;
316 sub parentlinks ($) { #{{{
323 foreach my $dir (reverse split("/", $page)) {
326 unshift @ret, { url => "$path$dir.html", page => $dir };
332 unshift @ret, { url => length $path ? $path : ".", page => $config{wikiname} };
336 sub indexlink () { #{{{
337 return "<a href=\"$config{url}\">$config{wikiname}</a>";
340 sub finalize ($$$) { #{{{
345 my $title=basename($page);
348 my $template=HTML::Template->new(blind_cache => 1,
349 filename => "$config{templatedir}/page.tmpl");
351 if (length $config{cgiurl}) {
352 $template->param(editurl => "$config{cgiurl}?do=edit&page=$page");
353 $template->param(prefsurl => "$config{cgiurl}?do=prefs");
355 $template->param(recentchangesurl => "$config{cgiurl}?do=recentchanges");
359 if (length $config{historyurl}) {
360 my $u=$config{historyurl};
361 $u=~s/\[\[file\]\]/$pagesources{$page}/g;
362 $template->param(historyurl => $u);
367 wikiname => $config{wikiname},
368 parentlinks => [parentlinks($page)],
370 backlinks => [backlinks($page)],
371 discussionlink => htmllink($page, "Discussion", 1, 1),
372 mtime => scalar(gmtime($mtime)),
375 return $template->output;
378 sub check_overwrite ($$) { #{{{
379 # Important security check. Make sure to call this before saving
380 # any files to the source directory.
384 if (! exists $renderedfiles{$src} && -e $dest && ! $config{rebuild}) {
385 error("$dest already exists and was rendered from ".
386 join(" ",(grep { $renderedfiles{$_} eq $dest } keys
388 ", before, so not rendering from $src");
392 sub render ($) { #{{{
395 my $type=pagetype($file);
396 my $content=readfile("$config{srcdir}/$file");
397 if ($type ne 'unknown') {
398 my $page=pagename($file);
400 $links{$page}=[findlinks($content, $page)];
402 $content=linkify($content, $page);
403 $content=htmlize($type, $content);
404 $content=finalize($content, $page,
405 mtime("$config{srcdir}/$file"));
407 check_overwrite("$config{destdir}/".htmlpage($page), $page);
408 writefile("$config{destdir}/".htmlpage($page), $content);
409 $oldpagemtime{$page}=time;
410 $renderedfiles{$page}=htmlpage($page);
414 check_overwrite("$config{destdir}/$file", $file);
415 writefile("$config{destdir}/$file", $content);
416 $oldpagemtime{$file}=time;
417 $renderedfiles{$file}=$file;
421 sub lockwiki () { #{{{
422 # Take an exclusive lock on the wiki to prevent multiple concurrent
423 # run issues. The lock will be dropped on program exit.
424 if (! -d $config{wikistatedir}) {
425 mkdir($config{wikistatedir});
427 open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
428 error ("cannot write to $config{wikistatedir}/lockfile: $!");
429 if (! flock(WIKILOCK, 2 | 4)) {
430 debug("wiki seems to be locked, waiting for lock");
431 my $wait=600; # arbitrary, but don't hang forever to
432 # prevent process pileup
434 return if flock(WIKILOCK, 2 | 4);
437 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
441 sub unlockwiki () { #{{{
445 sub loadindex () { #{{{
446 open (IN, "$config{wikistatedir}/index") || return;
448 $_=possibly_foolish_untaint($_);
450 my ($mtime, $file, $rendered, @links)=split(' ', $_);
451 my $page=pagename($file);
452 $pagesources{$page}=$file;
453 $oldpagemtime{$page}=$mtime;
454 $oldlinks{$page}=[@links];
455 $links{$page}=[@links];
456 $renderedfiles{$page}=$rendered;
461 sub saveindex () { #{{{
462 if (! -d $config{wikistatedir}) {
463 mkdir($config{wikistatedir});
465 open (OUT, ">$config{wikistatedir}/index") ||
466 error("cannot write to $config{wikistatedir}/index: $!");
467 foreach my $page (keys %oldpagemtime) {
468 print OUT "$oldpagemtime{$page} $pagesources{$page} $renderedfiles{$page} ".
469 join(" ", @{$links{$page}})."\n"
470 if $oldpagemtime{$page};
475 sub rcs_update () { #{{{
476 if (-d "$config{srcdir}/.svn") {
477 if (system("svn", "update", "--quiet", $config{srcdir}) != 0) {
478 warn("svn update failed\n");
483 sub rcs_prepedit ($) { #{{{
484 # Prepares to edit a file under revision control. Returns a token
485 # that must be passed into rcs_commit when the file is ready
487 # The file is relative to the srcdir.
490 if (-d "$config{srcdir}/.svn") {
491 # For subversion, return the revision of the file when
493 my $rev=svn_info("Revision", "$config{srcdir}/$file");
494 return defined $rev ? $rev : "";
498 sub rcs_commit ($$$) { #{{{
499 # Tries to commit the page; returns undef on _success_ and
500 # a version of the page with the rcs's conflict markers on failure.
501 # The file is relative to the srcdir.
506 if (-d "$config{srcdir}/.svn") {
507 # Check to see if the page has been changed by someone
508 # else since rcs_prepedit was called.
509 my ($oldrev)=$rcstoken=~/^([0-9]+)$/; # untaint
510 my $rev=svn_info("Revision", "$config{srcdir}/$file");
511 if (defined $rev && defined $oldrev && $rev != $oldrev) {
512 # Merge their changes into the file that we've
514 chdir($config{srcdir}); # svn merge wants to be here
515 if (system("svn", "merge", "--quiet", "-r$oldrev:$rev",
516 "$config{srcdir}/$file") != 0) {
517 warn("svn merge -r$oldrev:$rev failed\n");
521 if (system("svn", "commit", "--quiet", "-m",
522 possibly_foolish_untaint($message),
523 "$config{srcdir}") != 0) {
524 my $conflict=readfile("$config{srcdir}/$file");
525 if (system("svn", "revert", "--quiet", "$config{srcdir}/$file") != 0) {
526 warn("svn revert failed\n");
531 return undef # success
534 sub rcs_add ($) { #{{{
535 # filename is relative to the root of the srcdir
538 if (-d "$config{srcdir}/.svn") {
539 my $parent=dirname($file);
540 while (! -d "$config{srcdir}/$parent/.svn") {
542 $parent=dirname($file);
545 if (system("svn", "add", "--quiet", "$config{srcdir}/$file") != 0) {
546 warn("svn add failed\n");
551 sub svn_info ($$) { #{{{
555 my $info=`LANG=C svn info $file`;
556 my ($ret)=$info=~/^$field: (.*)$/m;
560 sub rcs_recentchanges ($) { #{{{
564 eval q{use CGI 'escapeHTML'};
565 eval q{use Date::Parse};
566 eval q{use Time::Duration};
568 if (-d "$config{srcdir}/.svn") {
569 my $svn_url=svn_info("URL", $config{srcdir});
571 # FIXME: currently assumes that the wiki is somewhere
572 # under trunk in svn, doesn't support other layouts.
573 my ($svn_base)=$svn_url=~m!(/trunk(?:/.*)?)$!;
575 my $div=qr/^--------------------+$/;
576 my $infoline=qr/^r(\d+)\s+\|\s+([^\s]+)\s+\|\s+(\d+-\d+-\d+\s+\d+:\d+:\d+\s+[-+]?\d+).*/;
578 my ($rev, $user, $when, @pages, @message);
579 foreach (`LANG=C svn log --limit $num -v '$svn_url'`) {
581 if ($state eq 'start' && /$div/) {
584 elsif ($state eq 'header' && /$infoline/) {
587 $when=concise(ago(time - str2time($3)));
589 elsif ($state eq 'header' && /^\s+[A-Z]\s+\Q$svn_base\E\/([^ ]+)(?:$|\s)/) {
591 my $diffurl=$config{diffurl};
592 $diffurl=~s/\[\[file\]\]/$file/g;
593 $diffurl=~s/\[\[r1\]\]/$rev - 1/eg;
594 $diffurl=~s/\[\[r2\]\]/$rev/g;
596 link => htmllink("", pagename($file), 1),
600 elsif ($state eq 'header' && /^$/) {
603 elsif ($state eq 'body' && /$div/) {
604 my $committype="web";
605 if (defined $message[0] &&
606 $message[0]->{line}=~/^web commit by (\w+):?(.*)/) {
608 $message[0]->{line}=$2;
614 push @ret, { rev => $rev,
615 user => htmllink("", $user, 1),
616 committype => $committype,
617 when => $when, message => [@message],
620 return @ret if @ret >= $num;
623 $rev=$user=$when=undef;
626 elsif ($state eq 'body') {
627 push @message, {line => escapeHTML($_)},
639 my $dir=dirname($file);
640 while (rmdir($dir)) {
645 sub refresh () { #{{{
646 # find existing pages
649 eval q{use File::Find};
653 if (/$config{wiki_file_prune_regexp}/) {
655 $File::Find::prune=1;
658 elsif (! -d $_ && ! -l $_) {
659 my ($f)=/$config{wiki_file_regexp}/; # untaint
661 warn("skipping bad filename $_\n");
664 $f=~s/^\Q$config{srcdir}\E\/?//;
666 $exists{pagename($f)}=1;
674 # check for added or removed pages
676 foreach my $file (@files) {
677 my $page=pagename($file);
678 if (! $oldpagemtime{$page}) {
679 debug("new page $page");
682 $pagesources{$page}=$file;
686 foreach my $page (keys %oldpagemtime) {
687 if (! $exists{$page}) {
688 debug("removing old page $page");
689 push @del, $pagesources{$page};
690 prune($config{destdir}."/".$renderedfiles{$page});
691 delete $renderedfiles{$page};
692 $oldpagemtime{$page}=0;
693 delete $pagesources{$page};
697 # render any updated files
698 foreach my $file (@files) {
699 my $page=pagename($file);
701 if (! exists $oldpagemtime{$page} ||
702 mtime("$config{srcdir}/$file") > $oldpagemtime{$page}) {
703 debug("rendering changed file $file");
709 # if any files were added or removed, check to see if each page
710 # needs an update due to linking to them
711 # TODO: inefficient; pages may get rendered above and again here;
712 # problem is the bestlink may have changed and we won't know until
715 FILE: foreach my $file (@files) {
716 my $page=pagename($file);
717 foreach my $f (@add, @del) {
719 foreach my $link (@{$links{$page}}) {
720 if (bestlink($page, $link) eq $p) {
721 debug("rendering $file, which links to $p");
731 # handle backlinks; if a page has added/removed links, update the
733 # TODO: inefficient; pages may get rendered above and again here;
734 # problem is the backlinks could be wrong in the first pass render
738 foreach my $file (keys %rendered, @del) {
739 my $page=pagename($file);
740 if (exists $links{$page}) {
741 foreach my $link (map { bestlink($page, $_) } @{$links{$page}}) {
743 ! exists $oldlinks{$page} ||
744 ! grep { $_ eq $link } @{$oldlinks{$page}}) {
745 $linkchanged{$link}=1;
749 if (exists $oldlinks{$page}) {
750 foreach my $link (map { bestlink($page, $_) } @{$oldlinks{$page}}) {
752 ! exists $links{$page} ||
753 ! grep { $_ eq $link } @{$links{$page}}) {
754 $linkchanged{$link}=1;
759 foreach my $link (keys %linkchanged) {
760 my $linkfile=$pagesources{$link};
761 if (defined $linkfile) {
762 debug("rendering $linkfile, to update its backlinks");
769 sub gen_wrapper () { #{{{
770 eval q{use Cwd 'abs_path'};
771 $config{srcdir}=abs_path($config{srcdir});
772 $config{destdir}=abs_path($config{destdir});
773 my $this=abs_path($0);
775 error("$this doesn't seem to be executable");
778 if ($config{setup}) {
779 error("cannot create a wrapper that uses a setup file");
782 my @params=($config{srcdir}, $config{destdir},
783 "--wikiname=$config{wikiname}",
784 "--templatedir=$config{templatedir}");
785 push @params, "--verbose" if $config{verbose};
786 push @params, "--rebuild" if $config{rebuild};
787 push @params, "--nosvn" if !$config{svn};
788 push @params, "--cgi" if $config{cgi};
789 push @params, "--url=$config{url}" if length $config{url};
790 push @params, "--cgiurl=$config{cgiurl}" if length $config{cgiurl};
791 push @params, "--historyurl=$config{historyurl}" if length $config{historyurl};
792 push @params, "--diffurl=$config{diffurl}" if length $config{diffurl};
793 push @params, "--anonok" if $config{anonok};
794 push @params, "--adminuser=$_" foreach @{$config{adminuser}};
795 my $params=join(" ", @params);
797 foreach my $p ($this, $this, @params) {
803 push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
804 CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
805 HTTP_COOKIE} if $config{cgi};
807 foreach my $var (@envsave) {
809 if ((s=getenv("$var")))
810 asprintf(&newenviron[i++], "%s=%s", "$var", s);
814 open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
816 /* A wrapper for ikiwiki, can be safely made suid. */
823 extern char **environ;
825 int main (int argc, char **argv) {
826 /* Sanitize environment. */
828 char *newenviron[$#envsave+3];
831 newenviron[i++]="HOME=$ENV{HOME}";
835 if (argc == 2 && strcmp(argv[1], "--params") == 0) {
836 printf("$params\\n");
841 perror("failed to run $this");
846 if (system("gcc", "ikiwiki-wrap.c", "-o", possibly_foolish_untaint($config{wrapper})) != 0) {
847 error("failed to compile ikiwiki-wrap.c");
849 unlink("ikiwiki-wrap.c");
850 if (defined $config{wrappermode} &&
851 ! chmod(oct($config{wrappermode}), possibly_foolish_untaint($config{wrapper}))) {
852 error("chmod $config{wrapper}: $!");
854 print "successfully generated $config{wrapper}\n";
857 sub misctemplate ($$) { #{{{
861 my $template=HTML::Template->new(
862 filename => "$config{templatedir}/misc.tmpl"
866 indexlink => indexlink(),
867 wikiname => $config{wikiname},
868 pagebody => $pagebody,
870 return $template->output;
873 sub cgi_recentchanges ($) { #{{{
876 my $template=HTML::Template->new(
877 filename => "$config{templatedir}/recentchanges.tmpl"
880 title => "RecentChanges",
881 indexlink => indexlink(),
882 wikiname => $config{wikiname},
883 changelog => [rcs_recentchanges(100)],
885 print $q->header, $template->output;
888 sub userinfo_get ($$) { #{{{
892 eval q{use Storable};
893 my $userdata=eval{ Storable::lock_retrieve("$config{wikistatedir}/userdb") };
894 if (! defined $userdata || ! ref $userdata ||
895 ! exists $userdata->{$user} || ! ref $userdata->{$user} ||
896 ! exists $userdata->{$user}->{$field}) {
899 return $userdata->{$user}->{$field};
902 sub userinfo_set ($$$) { #{{{
907 eval q{use Storable};
908 my $userdata=eval{ Storable::lock_retrieve("$config{wikistatedir}/userdb") };
909 if (! defined $userdata || ! ref $userdata ||
910 ! exists $userdata->{$user} || ! ref $userdata->{$user}) {
914 $userdata->{$user}->{$field}=$value;
915 my $oldmask=umask(077);
916 my $ret=Storable::lock_store($userdata, "$config{wikistatedir}/userdb");
921 sub userinfo_setall ($$) { #{{{
925 eval q{use Storable};
926 my $userdata=eval{ Storable::lock_retrieve("$config{wikistatedir}/userdb") };
927 if (! defined $userdata || ! ref $userdata) {
930 $userdata->{$user}=$info;
931 my $oldmask=umask(077);
932 my $ret=Storable::lock_store($userdata, "$config{wikistatedir}/userdb");
937 sub cgi_signin ($$) { #{{{
941 eval q{use CGI::FormBuilder};
942 my $form = CGI::FormBuilder->new(
944 fields => [qw(do page from name password confirm_password email)],
948 confirm_password => {
949 perl => q{eq $form->field("password")},
956 action => $q->request_uri,
958 template => (-e "$config{templatedir}/signin.tmpl" ?
959 "$config{templatedir}/signin.tmpl" : "")
962 $form->field(name => "name", required => 0);
963 $form->field(name => "do", type => "hidden");
964 $form->field(name => "page", type => "hidden");
965 $form->field(name => "from", type => "hidden");
966 $form->field(name => "password", type => "password", required => 0);
967 $form->field(name => "confirm_password", type => "password", required => 0);
968 $form->field(name => "email", required => 0);
969 if ($q->param("do") ne "signin") {
970 $form->text("You need to log in first.");
973 if ($form->submitted) {
974 # Set required fields based on how form was submitted.
976 "Login" => [qw(name password)],
977 "Register" => [qw(name password confirm_password email)],
978 "Mail Password" => [qw(name)],
980 foreach my $opt (@{$required{$form->submitted}}) {
981 $form->field(name => $opt, required => 1);
984 # Validate password differently depending on how
985 # form was submitted.
986 if ($form->submitted eq 'Login') {
990 length $form->field("name") &&
991 shift eq userinfo_get($form->field("name"), 'password');
994 $form->field(name => "name", validate => '/^\w+$/');
997 $form->field(name => "password", validate => 'VALUE');
999 # And make sure the entered name exists when logging
1000 # in or sending email, and does not when registering.
1001 if ($form->submitted eq 'Register') {
1007 ! userinfo_get($name, "regdate");
1017 userinfo_get($name, "regdate");
1023 # First time settings.
1024 $form->field(name => "name", comment => "use FirstnameLastName");
1025 $form->field(name => "confirm_password", comment => "(only needed");
1026 $form->field(name => "email", comment => "for registration)");
1027 if ($session->param("name")) {
1028 $form->field(name => "name", value => $session->param("name"));
1032 if ($form->submitted && $form->validate) {
1033 if ($form->submitted eq 'Login') {
1034 $session->param("name", $form->field("name"));
1035 if (defined $form->field("do") &&
1036 $form->field("do") ne 'signin') {
1038 "$config{cgiurl}?do=".$form->field("do").
1039 "&page=".$form->field("page").
1040 "&from=".$form->field("from"));;
1043 print $q->redirect($config{url});
1046 elsif ($form->submitted eq 'Register') {
1047 my $user_name=$form->field('name');
1048 if (userinfo_setall($user_name, {
1049 'email' => $form->field('email'),
1050 'password' => $form->field('password'),
1053 $form->field(name => "confirm_password", type => "hidden");
1054 $form->field(name => "email", type => "hidden");
1055 $form->text("Registration successful. Now you can Login.");
1056 print $session->header();
1057 print misctemplate($form->title, $form->render(submit => ["Login"]));
1060 error("Error saving registration.");
1063 elsif ($form->submitted eq 'Mail Password') {
1064 my $user_name=$form->field("name");
1065 my $template=HTML::Template->new(
1066 filename => "$config{templatedir}/passwordmail.tmpl"
1069 user_name => $user_name,
1070 user_password => userinfo_get($user_name, "password"),
1071 wikiurl => $config{url},
1072 wikiname => $config{wikiname},
1073 REMOTE_ADDR => $ENV{REMOTE_ADDR},
1076 eval q{use Mail::Sendmail};
1077 my ($fromhost) = $config{cgiurl} =~ m!/([^/]+)!;
1079 To => userinfo_get($user_name, "email"),
1080 From => "$config{wikiname} admin <".(getpwuid($>))[0]."@".$fromhost.">",
1081 Subject => "$config{wikiname} information",
1082 Message => $template->output,
1083 ) or error("Failed to send mail");
1085 $form->text("Your password has been emailed to you.");
1086 $form->field(name => "name", required => 0);
1087 print $session->header();
1088 print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
1092 print $session->header();
1093 print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
1097 sub is_admin ($) { #{{{
1098 my $user_name=shift;
1100 return grep { $_ eq $user_name } @{$config{adminuser}};
1103 sub glob_match ($$) { #{{{
1107 # turn glob into safe regexp
1108 $glob=quotemeta($glob);
1116 sub globlist_match ($$) { #{{{
1118 my @globlist=split(" ", shift);
1120 # check any negated globs first
1121 foreach my $glob (@globlist) {
1122 return 0 if $glob=~/^!(.*)/ && glob_match($page, $1);
1125 foreach my $glob (@globlist) {
1126 return 1 if glob_match($page, $glob);
1132 sub page_locked ($$;$) { #{{{
1137 my $user=$session->param("name");
1138 return if length $user && is_admin($user);
1140 foreach my $admin (@{$config{adminuser}}) {
1141 my $locked_pages=userinfo_get($admin, "locked_pages");
1142 if (globlist_match($page, userinfo_get($admin, "locked_pages"))) {
1143 return 1 if $nonfatal;
1144 error(htmllink("", $page, 1)." is locked by ".
1145 htmllink("", $admin, 1)." and cannot be edited.");
1152 sub cgi_prefs ($$) { #{{{
1156 eval q{use CGI::FormBuilder};
1157 my $form = CGI::FormBuilder->new(
1158 title => "preferences",
1159 fields => [qw(do name password confirm_password email locked_pages)],
1163 confirm_password => {
1164 perl => q{eq $form->field("password")},
1171 action => $q->request_uri,
1172 template => (-e "$config{templatedir}/prefs.tmpl" ?
1173 "$config{templatedir}/prefs.tmpl" : "")
1175 my @buttons=("Save Preferences", "Logout", "Cancel");
1177 my $user_name=$session->param("name");
1178 $form->field(name => "do", type => "hidden");
1179 $form->field(name => "name", disabled => 1,
1180 value => $user_name, force => 1);
1181 $form->field(name => "password", type => "password");
1182 $form->field(name => "confirm_password", type => "password");
1183 $form->field(name => "locked_pages", size => 50,
1184 comment => "(".htmllink("", "GlobList", 1).")");
1186 if (! is_admin($user_name)) {
1187 $form->field(name => "locked_pages", type => "hidden");
1190 if (! $form->submitted) {
1191 $form->field(name => "email", force => 1,
1192 value => userinfo_get($user_name, "email"));
1193 $form->field(name => "locked_pages", force => 1,
1194 value => userinfo_get($user_name, "locked_pages"));
1197 if ($form->submitted eq 'Logout') {
1199 print $q->redirect($config{url});
1202 elsif ($form->submitted eq 'Cancel') {
1203 print $q->redirect($config{url});
1206 elsif ($form->submitted eq "Save Preferences" && $form->validate) {
1207 foreach my $field (qw(password email locked_pages)) {
1208 if (length $form->field($field)) {
1209 userinfo_set($user_name, $field, $form->field($field)) || error("failed to set $field");
1212 $form->text("Preferences saved.");
1215 print $session->header();
1216 print misctemplate($form->title, $form->render(submit => \@buttons));
1219 sub cgi_editpage ($$) { #{{{
1223 eval q{use CGI::FormBuilder};
1224 my $form = CGI::FormBuilder->new(
1225 fields => [qw(do rcsinfo from page content comments)],
1231 required => [qw{content}],
1234 action => $q->request_uri,
1236 template => "$config{templatedir}/editpage.tmpl"
1238 my @buttons=("Save Page", "Preview", "Cancel");
1240 my ($page)=$form->param('page')=~/$config{wiki_file_regexp}/;
1241 if (! defined $page || ! length $page || $page ne $q->param('page') ||
1242 $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
1243 error("bad page name");
1247 my $file=$page.$config{default_pageext};
1249 if (exists $pagesources{lc($page)}) {
1250 $file=$pagesources{lc($page)};
1254 $form->field(name => "do", type => 'hidden');
1255 $form->field(name => "from", type => 'hidden');
1256 $form->field(name => "rcsinfo", type => 'hidden');
1257 $form->field(name => "page", value => "$page", force => 1);
1258 $form->field(name => "comments", type => "text", size => 80);
1259 $form->field(name => "content", type => "textarea", rows => 20,
1261 $form->tmpl_param("can_commit", $config{svn});
1262 $form->tmpl_param("indexlink", indexlink());
1263 $form->tmpl_param("helponformattinglink",
1264 htmllink("", "HelpOnFormatting", 1));
1265 if (! $form->submitted) {
1266 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
1270 if ($form->submitted eq "Cancel") {
1271 print $q->redirect("$config{url}/".htmlpage($page));
1274 elsif ($form->submitted eq "Preview") {
1275 $form->tmpl_param("page_preview",
1276 htmlize($config{default_pageext},
1277 linkify($form->field('content'), $page)));
1280 $form->tmpl_param("page_preview", "");
1282 $form->tmpl_param("page_conflict", "");
1284 if (! $form->submitted || $form->submitted eq "Preview" ||
1285 ! $form->validate) {
1286 if ($form->field("do") eq "create") {
1287 if (exists $pagesources{lc($page)}) {
1288 # hmm, someone else made the page in the
1290 print $q->redirect("$config{url}/".htmlpage($page));
1296 my ($from)=$form->param('from')=~/$config{wiki_file_regexp}/;
1297 if (! defined $from || ! length $from ||
1298 $from ne $form->param('from') ||
1299 $from=~/$config{wiki_file_prune_regexp}/ || $from=~/^\//) {
1300 @page_locs=$best_loc=$page;
1306 if ($page eq 'discussion') {
1307 $best_loc="$from/$page";
1310 $best_loc=$dir.$page;
1313 push @page_locs, $dir.$page;
1314 push @page_locs, "$from/$page";
1315 while (length $dir) {
1317 push @page_locs, $dir.$page;
1321 ! exists $pagesources{lc($_)} &&
1322 ! page_locked($_, $session, 1)
1326 $form->tmpl_param("page_select", 1);
1327 $form->field(name => "page", type => 'select',
1328 options => \@page_locs, value => $best_loc);
1329 $form->title("creating $page");
1331 elsif ($form->field("do") eq "edit") {
1332 page_locked($page, $session);
1333 if (! defined $form->field('content') ||
1334 ! length $form->field('content')) {
1336 if (exists $pagesources{lc($page)}) {
1337 $content=readfile("$config{srcdir}/$pagesources{lc($page)}");
1338 $content=~s/\n/\r\n/g;
1340 $form->field(name => "content", value => $content,
1343 $form->tmpl_param("page_select", 0);
1344 $form->field(name => "page", type => 'hidden');
1345 $form->title("editing $page");
1348 print $form->render(submit => \@buttons);
1352 page_locked($page, $session);
1354 my $content=$form->field('content');
1355 $content=~s/\r\n/\n/g;
1356 $content=~s/\r/\n/g;
1357 writefile("$config{srcdir}/$file", $content);
1359 my $message="web commit ";
1360 if (length $session->param("name")) {
1361 $message.="by ".$session->param("name");
1364 $message.="from $ENV{REMOTE_ADDR}";
1366 if (defined $form->field('comments') &&
1367 length $form->field('comments')) {
1368 $message.=": ".$form->field('comments');
1375 # prevent deadlock with post-commit hook
1377 # presumably the commit will trigger an update
1379 my $conflict=rcs_commit($file, $message,
1380 $form->field("rcsinfo"));
1382 if (defined $conflict) {
1383 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
1385 $form->tmpl_param("page_conflict", 1);
1386 $form->field("content", value => $conflict, force => 1);
1387 $form->field("do", "edit)");
1388 $form->tmpl_param("page_select", 0);
1389 $form->field(name => "page", type => 'hidden');
1390 $form->title("editing $page");
1391 print $form->render(submit => \@buttons);
1401 # The trailing question mark tries to avoid broken
1402 # caches and get the most recent version of the page.
1403 print $q->redirect("$config{url}/".htmlpage($page)."?updated");
1409 eval q{use CGI::Session};
1413 my $do=$q->param('do');
1414 if (! defined $do || ! length $do) {
1415 error("\"do\" parameter missing");
1418 # This does not need a session.
1419 if ($do eq 'recentchanges') {
1420 cgi_recentchanges($q);
1424 CGI::Session->name("ikiwiki_session");
1426 my $oldmask=umask(077);
1427 my $session = CGI::Session->new("driver:db_file", $q,
1428 { FileName => "$config{wikistatedir}/sessions.db" });
1431 # Everything below this point needs the user to be signed in.
1432 if ((! $config{anonok} && ! defined $session->param("name") ||
1433 ! defined $session->param("name") ||
1434 ! userinfo_get($session->param("name"), "regdate")) || $do eq 'signin') {
1435 cgi_signin($q, $session);
1437 # Force session flush with safe umask.
1438 my $oldmask=umask(077);
1445 if ($do eq 'create' || $do eq 'edit') {
1446 cgi_editpage($q, $session);
1448 elsif ($do eq 'prefs') {
1449 cgi_prefs($q, $session);
1452 error("unknown do parameter");
1456 sub setup () { # {{{
1457 my $setup=possibly_foolish_untaint($config{setup});
1458 delete $config{setup};
1459 open (IN, $setup) || error("read $setup: $!\n");
1462 ($code)=$code=~/(.*)/s;
1471 setup() if $config{setup};
1473 if ($config{wrapper}) {
1477 memoize('pagename');
1478 memoize('bestlink');
1479 loadindex() unless $config{rebuild};
1484 rcs_update() if $config{svn};