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" => \$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);
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 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{destdir},
776 "--wikiname=$config{wikiname}",
777 "--templatedir=$config{templatedir}");
778 push @params, "--verbose" if $config{verbose};
779 push @params, "--rebuild" if $config{rebuild};
780 push @params, "--nosvn" if !$config{svn};
781 push @params, "--cgi" if $config{cgi};
782 push @params, "--url=$config{url}" if length $config{url};
783 push @params, "--cgiurl=$config{cgiurl}" if length $config{cgiurl};
784 push @params, "--historyurl=$config{historyurl}" if length $config{historyurl};
785 push @params, "--diffurl=$config{diffurl}" if length $config{diffurl};
786 push @params, "--anonok" if $config{anonok};
787 push @params, "--adminuser=$_" foreach @{$config{adminuser}};
788 my $params=join(" ", @params);
790 foreach my $p ($this, $this, @params) {
796 push @envsave, qw{REMOTE_ADDR QUERY_STRING REQUEST_METHOD REQUEST_URI
797 CONTENT_TYPE CONTENT_LENGTH GATEWAY_INTERFACE
798 HTTP_COOKIE} if $config{cgi};
800 foreach my $var (@envsave) {
802 if ((s=getenv("$var")))
803 asprintf(&newenviron[i++], "%s=%s", "$var", s);
807 open(OUT, ">ikiwiki-wrap.c") || error("failed to write ikiwiki-wrap.c: $!");;
809 /* A wrapper for ikiwiki, can be safely made suid. */
816 extern char **environ;
818 int main (int argc, char **argv) {
819 /* Sanitize environment. */
821 char *newenviron[$#envsave+3];
824 newenviron[i++]="HOME=$ENV{HOME}";
828 if (argc == 2 && strcmp(argv[1], "--params") == 0) {
829 printf("$params\\n");
834 perror("failed to run $this");
839 if (system("gcc", "ikiwiki-wrap.c", "-o", possibly_foolish_untaint($config{wrapper})) != 0) {
840 error("failed to compile ikiwiki-wrap.c");
842 unlink("ikiwiki-wrap.c");
843 if (defined $config{wrappermode} &&
844 ! chmod(oct($config{wrappermode}), possibly_foolish_untaint($config{wrapper}))) {
845 error("chmod $config{wrapper}: $!");
847 print "successfully generated $config{wrapper}\n";
850 sub misctemplate ($$) { #{{{
854 my $template=HTML::Template->new(
855 filename => "$config{templatedir}/misc.tmpl"
859 indexlink => indexlink(),
860 wikiname => $config{wikiname},
861 pagebody => $pagebody,
863 return $template->output;
866 sub cgi_recentchanges ($) { #{{{
869 my $template=HTML::Template->new(
870 filename => "$config{templatedir}/recentchanges.tmpl"
873 title => "RecentChanges",
874 indexlink => indexlink(),
875 wikiname => $config{wikiname},
876 changelog => [rcs_recentchanges(100)],
878 print $q->header, $template->output;
881 sub userinfo_get ($$) { #{{{
885 eval q{use Storable};
886 my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
887 if (! defined $userdata || ! ref $userdata ||
888 ! exists $userdata->{$user} || ! ref $userdata->{$user} ||
889 ! exists $userdata->{$user}->{$field}) {
892 return $userdata->{$user}->{$field};
895 sub userinfo_set ($$$) { #{{{
900 eval q{use Storable};
901 my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
902 if (! defined $userdata || ! ref $userdata ||
903 ! exists $userdata->{$user} || ! ref $userdata->{$user}) {
907 $userdata->{$user}->{$field}=$value;
908 my $oldmask=umask(077);
909 my $ret=Storable::lock_store($userdata, "$config{srcdir}/.ikiwiki/userdb");
914 sub userinfo_setall ($$) { #{{{
918 eval q{use Storable};
919 my $userdata=eval{ Storable::lock_retrieve("$config{srcdir}/.ikiwiki/userdb") };
920 if (! defined $userdata || ! ref $userdata) {
923 $userdata->{$user}=$info;
924 my $oldmask=umask(077);
925 my $ret=Storable::lock_store($userdata, "$config{srcdir}/.ikiwiki/userdb");
930 sub cgi_signin ($$) { #{{{
934 eval q{use CGI::FormBuilder};
935 my $form = CGI::FormBuilder->new(
937 fields => [qw(do page from name password confirm_password email)],
941 confirm_password => {
942 perl => q{eq $form->field("password")},
949 action => $q->request_uri,
951 template => (-e "$config{templatedir}/signin.tmpl" ?
952 "$config{templatedir}/signin.tmpl" : "")
955 $form->field(name => "name", required => 0);
956 $form->field(name => "do", type => "hidden");
957 $form->field(name => "page", type => "hidden");
958 $form->field(name => "from", type => "hidden");
959 $form->field(name => "password", type => "password", required => 0);
960 $form->field(name => "confirm_password", type => "password", required => 0);
961 $form->field(name => "email", required => 0);
962 if ($q->param("do") ne "signin") {
963 $form->text("You need to log in first.");
966 if ($form->submitted) {
967 # Set required fields based on how form was submitted.
969 "Login" => [qw(name password)],
970 "Register" => [qw(name password confirm_password email)],
971 "Mail Password" => [qw(name)],
973 foreach my $opt (@{$required{$form->submitted}}) {
974 $form->field(name => $opt, required => 1);
977 # Validate password differently depending on how
978 # form was submitted.
979 if ($form->submitted eq 'Login') {
983 length $form->field("name") &&
984 shift eq userinfo_get($form->field("name"), 'password');
987 $form->field(name => "name", validate => '/^\w+$/');
990 $form->field(name => "password", validate => 'VALUE');
992 # And make sure the entered name exists when logging
993 # in or sending email, and does not when registering.
994 if ($form->submitted eq 'Register') {
1000 ! userinfo_get($name, "regdate");
1010 userinfo_get($name, "regdate");
1016 # First time settings.
1017 $form->field(name => "name", comment => "use FirstnameLastName");
1018 $form->field(name => "confirm_password", comment => "(only needed");
1019 $form->field(name => "email", comment => "for registration)");
1020 if ($session->param("name")) {
1021 $form->field(name => "name", value => $session->param("name"));
1025 if ($form->submitted && $form->validate) {
1026 if ($form->submitted eq 'Login') {
1027 $session->param("name", $form->field("name"));
1028 if (defined $form->field("do") &&
1029 $form->field("do") ne 'signin') {
1031 "$config{cgiurl}?do=".$form->field("do").
1032 "&page=".$form->field("page").
1033 "&from=".$form->field("from"));;
1036 print $q->redirect($config{url});
1039 elsif ($form->submitted eq 'Register') {
1040 my $user_name=$form->field('name');
1041 if (userinfo_setall($user_name, {
1042 'email' => $form->field('email'),
1043 'password' => $form->field('password'),
1046 $form->field(name => "confirm_password", type => "hidden");
1047 $form->field(name => "email", type => "hidden");
1048 $form->text("Registration successful. Now you can Login.");
1049 print $session->header();
1050 print misctemplate($form->title, $form->render(submit => ["Login"]));
1053 error("Error saving registration.");
1056 elsif ($form->submitted eq 'Mail Password') {
1057 my $user_name=$form->field("name");
1058 my $template=HTML::Template->new(
1059 filename => "$config{templatedir}/passwordmail.tmpl"
1062 user_name => $user_name,
1063 user_password => userinfo_get($user_name, "password"),
1064 wikiurl => $config{url},
1065 wikiname => $config{wikiname},
1066 REMOTE_ADDR => $ENV{REMOTE_ADDR},
1069 eval q{use Mail::Sendmail};
1070 my ($fromhost) = $config{cgiurl} =~ m!/([^/]+)!;
1072 To => userinfo_get($user_name, "email"),
1073 From => "$config{wikiname} admin <".(getpwuid($>))[0]."@".$fromhost.">",
1074 Subject => "$config{wikiname} information",
1075 Message => $template->output,
1076 ) or error("Failed to send mail");
1078 $form->text("Your password has been emailed to you.");
1079 $form->field(name => "name", required => 0);
1080 print $session->header();
1081 print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
1085 print $session->header();
1086 print misctemplate($form->title, $form->render(submit => ["Login", "Register", "Mail Password"]));
1090 sub is_admin ($) { #{{{
1091 my $user_name=shift;
1093 return grep { $_ eq $user_name } @{$config{adminuser}};
1096 sub glob_match ($$) { #{{{
1100 # turn glob into safe regexp
1101 $glob=quotemeta($glob);
1109 sub globlist_match ($$) { #{{{
1111 my @globlist=split(" ", shift);
1113 # check any negated globs first
1114 foreach my $glob (@globlist) {
1115 return 0 if $glob=~/^!(.*)/ && glob_match($page, $1);
1118 foreach my $glob (@globlist) {
1119 return 1 if glob_match($page, $glob);
1125 sub page_locked ($$;$) { #{{{
1130 my $user=$session->param("name");
1131 return if length $user && is_admin($user);
1133 foreach my $admin (@{$config{adminuser}}) {
1134 my $locked_pages=userinfo_get($admin, "locked_pages");
1135 if (globlist_match($page, userinfo_get($admin, "locked_pages"))) {
1136 return 1 if $nonfatal;
1137 error(htmllink("", $page, 1)." is locked by ".
1138 htmllink("", $admin, 1)." and cannot be edited.");
1145 sub cgi_prefs ($$) { #{{{
1149 eval q{use CGI::FormBuilder};
1150 my $form = CGI::FormBuilder->new(
1151 title => "preferences",
1152 fields => [qw(do name password confirm_password email locked_pages)],
1156 confirm_password => {
1157 perl => q{eq $form->field("password")},
1164 action => $q->request_uri,
1165 template => (-e "$config{templatedir}/prefs.tmpl" ?
1166 "$config{templatedir}/prefs.tmpl" : "")
1168 my @buttons=("Save Preferences", "Logout", "Cancel");
1170 my $user_name=$session->param("name");
1171 $form->field(name => "do", type => "hidden");
1172 $form->field(name => "name", disabled => 1,
1173 value => $user_name, force => 1);
1174 $form->field(name => "password", type => "password");
1175 $form->field(name => "confirm_password", type => "password");
1176 $form->field(name => "locked_pages", size => 50,
1177 comment => "(".htmllink("", "GlobList", 1).")");
1179 if (! is_admin($user_name)) {
1180 $form->field(name => "locked_pages", type => "hidden");
1183 if (! $form->submitted) {
1184 $form->field(name => "email", force => 1,
1185 value => userinfo_get($user_name, "email"));
1186 $form->field(name => "locked_pages", force => 1,
1187 value => userinfo_get($user_name, "locked_pages"));
1190 if ($form->submitted eq 'Logout') {
1192 print $q->redirect($config{url});
1195 elsif ($form->submitted eq 'Cancel') {
1196 print $q->redirect($config{url});
1199 elsif ($form->submitted eq "Save Preferences" && $form->validate) {
1200 foreach my $field (qw(password email locked_pages)) {
1201 if (length $form->field($field)) {
1202 userinfo_set($user_name, $field, $form->field($field)) || error("failed to set $field");
1205 $form->text("Preferences saved.");
1208 print $session->header();
1209 print misctemplate($form->title, $form->render(submit => \@buttons));
1212 sub cgi_editpage ($$) { #{{{
1216 eval q{use CGI::FormBuilder};
1217 my $form = CGI::FormBuilder->new(
1218 fields => [qw(do rcsinfo from page content comments)],
1224 required => [qw{content}],
1227 action => $q->request_uri,
1229 template => "$config{templatedir}/editpage.tmpl"
1231 my @buttons=("Save Page", "Preview", "Cancel");
1233 my ($page)=$form->param('page')=~/$config{wiki_file_regexp}/;
1234 if (! defined $page || ! length $page || $page ne $q->param('page') ||
1235 $page=~/$config{wiki_file_prune_regexp}/ || $page=~/^\//) {
1236 error("bad page name");
1240 my $file=$page.$config{default_pageext};
1242 if (exists $pagesources{lc($page)}) {
1243 $file=$pagesources{lc($page)};
1247 $form->field(name => "do", type => 'hidden');
1248 $form->field(name => "from", type => 'hidden');
1249 $form->field(name => "rcsinfo", type => 'hidden');
1250 $form->field(name => "page", value => "$page", force => 1);
1251 $form->field(name => "comments", type => "text", size => 80);
1252 $form->field(name => "content", type => "textarea", rows => 20,
1254 $form->tmpl_param("can_commit", $config{svn});
1255 $form->tmpl_param("indexlink", indexlink());
1256 $form->tmpl_param("helponformattinglink",
1257 htmllink("", "HelpOnFormatting", 1));
1258 if (! $form->submitted) {
1259 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
1263 if ($form->submitted eq "Cancel") {
1264 print $q->redirect("$config{url}/".htmlpage($page));
1267 elsif ($form->submitted eq "Preview") {
1268 $form->tmpl_param("page_preview",
1269 htmlize($config{default_pageext},
1270 linkify($form->field('content'), $page)));
1273 $form->tmpl_param("page_preview", "");
1275 $form->tmpl_param("page_conflict", "");
1277 if (! $form->submitted || $form->submitted eq "Preview" ||
1278 ! $form->validate) {
1279 if ($form->field("do") eq "create") {
1280 if (exists $pagesources{lc($page)}) {
1281 # hmm, someone else made the page in the
1283 print $q->redirect("$config{url}/".htmlpage($page));
1289 my ($from)=$form->param('from')=~/$config{wiki_file_regexp}/;
1290 if (! defined $from || ! length $from ||
1291 $from ne $form->param('from') ||
1292 $from=~/$config{wiki_file_prune_regexp}/ || $from=~/^\//) {
1293 @page_locs=$best_loc=$page;
1299 if ($page eq 'discussion') {
1300 $best_loc="$from/$page";
1303 $best_loc=$dir.$page;
1306 push @page_locs, $dir.$page;
1307 push @page_locs, "$from/$page";
1308 while (length $dir) {
1310 push @page_locs, $dir.$page;
1314 ! exists $pagesources{lc($_)} &&
1315 ! page_locked($_, $session, 1)
1319 $form->tmpl_param("page_select", 1);
1320 $form->field(name => "page", type => 'select',
1321 options => \@page_locs, value => $best_loc);
1322 $form->title("creating $page");
1324 elsif ($form->field("do") eq "edit") {
1325 page_locked($page, $session);
1326 if (! defined $form->field('content') ||
1327 ! length $form->field('content')) {
1329 if (exists $pagesources{lc($page)}) {
1330 $content=readfile("$config{srcdir}/$pagesources{lc($page)}");
1331 $content=~s/\n/\r\n/g;
1333 $form->field(name => "content", value => $content,
1336 $form->tmpl_param("page_select", 0);
1337 $form->field(name => "page", type => 'hidden');
1338 $form->title("editing $page");
1341 print $form->render(submit => \@buttons);
1345 page_locked($page, $session);
1347 my $content=$form->field('content');
1348 $content=~s/\r\n/\n/g;
1349 $content=~s/\r/\n/g;
1350 writefile("$config{srcdir}/$file", $content);
1352 my $message="web commit ";
1353 if (length $session->param("name")) {
1354 $message.="by ".$session->param("name");
1357 $message.="from $ENV{REMOTE_ADDR}";
1359 if (defined $form->field('comments') &&
1360 length $form->field('comments')) {
1361 $message.=": ".$form->field('comments');
1368 # prevent deadlock with post-commit hook
1370 # presumably the commit will trigger an update
1372 my $conflict=rcs_commit($file, $message,
1373 $form->field("rcsinfo"));
1375 if (defined $conflict) {
1376 $form->field(name => "rcsinfo", value => rcs_prepedit($file),
1378 $form->tmpl_param("page_conflict", 1);
1379 $form->field("content", value => $conflict, force => 1);
1380 $form->field("do", "edit)");
1381 $form->tmpl_param("page_select", 0);
1382 $form->field(name => "page", type => 'hidden');
1383 $form->title("editing $page");
1384 print $form->render(submit => \@buttons);
1394 # The trailing question mark tries to avoid broken
1395 # caches and get the most recent version of the page.
1396 print $q->redirect("$config{url}/".htmlpage($page)."?updated");
1402 eval q{use CGI::Session};
1406 my $do=$q->param('do');
1407 if (! defined $do || ! length $do) {
1408 error("\"do\" parameter missing");
1411 # This does not need a session.
1412 if ($do eq 'recentchanges') {
1413 cgi_recentchanges($q);
1417 CGI::Session->name("ikiwiki_session");
1419 my $oldmask=umask(077);
1420 my $session = CGI::Session->new("driver:db_file", $q,
1421 { FileName => "$config{srcdir}/.ikiwiki/sessions.db" });
1424 # Everything below this point needs the user to be signed in.
1425 if ((! $config{anonok} && ! defined $session->param("name") ||
1426 ! defined $session->param("name") ||
1427 ! userinfo_get($session->param("name"), "regdate")) || $do eq 'signin') {
1428 cgi_signin($q, $session);
1430 # Force session flush with safe umask.
1431 my $oldmask=umask(077);
1438 if ($do eq 'create' || $do eq 'edit') {
1439 cgi_editpage($q, $session);
1441 elsif ($do eq 'prefs') {
1442 cgi_prefs($q, $session);
1445 error("unknown do parameter");
1449 sub setup () { # {{{
1450 my $setup=possibly_foolish_untaint($config{setup});
1451 delete $config{setup};
1452 open (IN, $setup) || error("read $setup: $!\n");
1455 ($code)=$code=~/(.*)/s;
1464 setup() if $config{setup};
1466 if ($config{wrapper}) {
1467 gen_wrapper(%config);
1470 memoize('pagename');
1471 memoize('bestlink');
1472 loadindex() unless $config{rebuild};
1477 rcs_update() if $config{svn};