9 use URI::Escape q{uri_escape_utf8};
12 use open qw{:utf8 :std};
14 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
15 %pagestate %wikistate %renderedfiles %oldrenderedfiles
16 %pagesources %destsources %depends %hooks %forcerebuild
17 $gettext_obj %loaded_plugins};
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
21 bestlink htmllink readfile writefile pagetype srcfile pagename
22 displaytime will_render gettext urlto targetpage
23 add_underlay pagetitle titlepage linkpage newpagefile
25 %config %links %pagestate %wikistate %renderedfiles
26 %pagesources %destsources);
27 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
28 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
29 our $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
34 memoize("pagespec_translate");
35 memoize("file_pruned");
41 description => "name of the wiki",
48 example => 'me@example.com',
49 description => "contact email for wiki",
56 description => "users who are wiki admins",
63 description => "users who are banned from the wiki",
70 example => "$ENV{HOME}/wiki",
71 description => "where the source of the wiki is located",
78 example => "/var/www/wiki",
79 description => "where to build the wiki",
86 example => "http://example.com/wiki",
87 description => "base url to the wiki",
94 example => "http://example.com/wiki/ikiwiki.cgi",
95 description => "url to the ikiwiki.cgi",
102 example => "/var/www/wiki/ikiwiki.cgi",
103 description => "filename of cgi wrapper to generate",
110 description => "mode for cgi_wrapper (can safely be made suid)",
117 description => "rcs backend to use",
118 safe => 0, # don't allow overriding
123 default => [qw{mdwn link inline meta htmlscrubber passwordauth
124 openid signinedit lockedit conditional
125 recentchanges parentlinks editpage}],
126 description => "plugins to enable by default",
133 description => "plugins to add to the default configuration",
140 description => "plugins to disable",
146 default => "$installdir/share/ikiwiki/templates",
147 description => "location of template files",
154 default => "$installdir/share/ikiwiki/basewiki",
155 description => "base wiki source location",
163 description => "wrappers to generate",
170 description => "additional underlays to use",
177 description => "display verbose messages?",
184 description => "log to syslog?",
191 description => "create output files named page/index.html?",
192 safe => 0, # changing requires manual transition
195 prefix_directives => {
198 description => "use '!'-prefixed preprocessor directives?",
199 safe => 0, # changing requires manual transition
205 description => "use page/index.mdwn source files",
212 description => "enable Discussion pages?",
219 description => "only send cookies over SSL connections?",
227 description => "extension to use for new pages",
228 safe => 0, # not sanitized
234 description => "extension to use for html files",
235 safe => 0, # not sanitized
241 description => "strftime format string to display date",
249 example => "en_US.UTF-8",
250 description => "UTF-8 locale to use",
259 description => "put user pages below specified page",
266 description => "how many backlinks to show before hiding excess (0 to show all)",
273 description => "attempt to hardlink source files? (optimisation for large files)",
275 safe => 0, # paranoia
281 description => "force ikiwiki to use a particular umask",
283 safe => 0, # paranoia
288 example => "ikiwiki",
289 description => "group for wrappers to run in",
291 safe => 0, # paranoia
297 example => "$ENV{HOME}/.ikiwiki/",
298 description => "extra library and plugin directory",
300 safe => 0, # directory
306 description => "environment variables",
307 safe => 0, # paranoia
314 description => "regexp of source files to ignore",
319 wiki_file_prune_regexps => {
321 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
322 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
323 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
326 description => "regexps of source files to ignore",
332 description => "specifies the characters that are allowed in source filenames",
333 default => "-[:alnum:]+/.:_",
337 wiki_file_regexp => {
339 description => "regexp of legal source files",
343 web_commit_regexp => {
345 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
346 description => "regexp to parse web commits from logs",
353 description => "run as a cgi",
357 cgi_disable_uploads => {
360 description => "whether CGI should accept file uploads",
367 description => "run as a post-commit hook",
374 description => "running in rebuild mode",
381 description => "running in setup mode",
388 description => "running in refresh mode",
395 description => "running in receive test mode",
402 description => "running in getctime mode",
409 description => "running in w3mmode",
416 description => "path to the .ikiwiki directory holding ikiwiki state",
423 description => "path to setup file",
427 allow_symlinks_before_srcdir => {
430 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
436 sub defaultconfig () {
439 foreach my $key (keys %s) {
440 push @ret, $key, $s{$key}->{default};
447 # locale stuff; avoid LC_ALL since it overrides everything
448 if (defined $ENV{LC_ALL}) {
449 $ENV{LANG} = $ENV{LC_ALL};
452 if (defined $config{locale}) {
453 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
454 $ENV{LANG}=$config{locale};
459 if (! defined $config{wiki_file_regexp}) {
460 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
463 if (ref $config{ENV} eq 'HASH') {
464 foreach my $val (keys %{$config{ENV}}) {
465 $ENV{$val}=$config{ENV}{$val};
469 if ($config{w3mmode}) {
470 eval q{use Cwd q{abs_path}};
472 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
473 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
474 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
475 unless $config{cgiurl} =~ m!file:///!;
476 $config{url}="file://".$config{destdir};
479 if ($config{cgi} && ! length $config{url}) {
480 error(gettext("Must specify url to wiki with --url when using --cgi"));
483 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
484 unless exists $config{wikistatedir} && defined $config{wikistatedir};
486 if (defined $config{umask}) {
487 umask(possibly_foolish_untaint($config{umask}));
490 run_hooks(checkconfig => sub { shift->() });
498 foreach my $dir (@INC, $config{libdir}) {
499 next unless defined $dir && length $dir;
500 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
501 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
505 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
506 next unless defined $dir && length $dir;
507 foreach my $file (glob("$dir/plugins/*")) {
508 $ret{basename($file)}=1 if -x $file;
516 if (defined $config{libdir} && length $config{libdir}) {
517 unshift @INC, possibly_foolish_untaint($config{libdir});
520 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
525 if (exists $IkiWiki::hooks{rcs}) {
526 error(gettext("cannot use multiple rcs plugins"));
528 loadplugin($config{rcs});
530 if (! exists $IkiWiki::hooks{rcs}) {
534 run_hooks(getopt => sub { shift->() });
535 if (grep /^-/, @ARGV) {
536 print STDERR "Unknown option (or missing parameter): $_\n"
537 foreach grep /^-/, @ARGV;
547 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
549 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
550 "$installdir/lib/ikiwiki") {
551 if (defined $dir && -x "$dir/plugins/$plugin") {
552 eval { require IkiWiki::Plugin::external };
555 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
557 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
558 $loaded_plugins{$plugin}=1;
563 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
566 error("Failed to load plugin $mod: $@");
568 $loaded_plugins{$plugin}=1;
575 log_message('err' => $message) if $config{syslog};
576 if (defined $cleaner) {
583 return unless $config{verbose};
584 return log_message(debug => @_);
588 sub log_message ($$) {
591 if ($config{syslog}) {
594 Sys::Syslog::setlogsock('unix');
595 Sys::Syslog::openlog('ikiwiki', '', 'user');
599 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
602 elsif (! $config{cgi}) {
606 return print STDERR "@_\n";
610 sub possibly_foolish_untaint ($) {
612 my ($untainted)=$tainted=~/(.*)/s;
632 return exists $pagesources{$page} &&
633 $pagesources{$page} =~ /\._([^.]+)$/;
639 if ($file =~ /\.([^.]+)$/) {
640 return $1 if exists $hooks{htmlize}{$1};
642 my $base=basename($file);
643 if (exists $hooks{htmlize}{$base} &&
644 $hooks{htmlize}{$base}{noextension}) {
653 my $type=pagetype($file);
655 $page=~s/\Q.$type\E*$//
656 if defined $type && !$hooks{htmlize}{$type}{keepextension}
657 && !$hooks{htmlize}{$type}{noextension};
658 if ($config{indexpages} && $page=~/(.*)\/index$/) {
664 sub newpagefile ($$) {
668 if (! $config{indexpages} || $page eq 'index') {
669 return $page.".".$type;
672 return $page."/index.".$type;
676 sub targetpage ($$;$) {
681 if (defined $filename) {
682 return $page."/".$filename.".".$ext;
684 elsif (! $config{usedirs} || $page eq 'index') {
685 return $page.".".$ext;
688 return $page."/index.".$ext;
695 return targetpage($page, $config{htmlext});
702 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
703 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
704 return "$dir/$file", stat(_) if -e "$dir/$file";
706 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
711 return (srcfile_stat(@_))[0];
714 sub add_underlay ($) {
718 $dir="$config{underlaydir}/../$dir";
721 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
722 unshift @{$config{underlaydirs}}, $dir;
728 sub readfile ($;$$) {
734 error("cannot read a symlink ($file)");
738 open (my $in, "<", $file) || error("failed to read $file: $!");
739 binmode($in) if ($binary);
740 return \*$in if $wantfd;
742 # check for invalid utf-8, and toss it back to avoid crashes
743 if (! utf8::valid($ret)) {
744 $ret=encode_utf8($ret);
746 close $in || error("failed to read $file: $!");
750 sub prep_writefile ($$) {
755 while (length $test) {
756 if (-l "$destdir/$test") {
757 error("cannot write to a symlink ($test)");
759 $test=dirname($test);
762 my $dir=dirname("$destdir/$file");
765 foreach my $s (split(m!/+!, $dir)) {
768 mkdir($d) || error("failed to create directory $d: $!");
776 sub writefile ($$$;$$) {
777 my $file=shift; # can include subdirs
778 my $destdir=shift; # directory to put file in
783 prep_writefile($file, $destdir);
785 my $newfile="$destdir/$file.ikiwiki-new";
787 error("cannot write to a symlink ($newfile)");
790 my $cleanup = sub { unlink($newfile) };
791 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
792 binmode($out) if ($binary);
794 $writer->(\*$out, $cleanup);
797 print $out $content or error("failed writing to $newfile: $!", $cleanup);
799 close $out || error("failed saving $newfile: $!", $cleanup);
800 rename($newfile, "$destdir/$file") ||
801 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
807 sub will_render ($$;$) {
812 # Important security check.
813 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
814 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
815 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
818 if (! $clear || $cleared{$page}) {
819 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
822 foreach my $old (@{$renderedfiles{$page}}) {
823 delete $destsources{$old};
825 $renderedfiles{$page}=[$dest];
828 $destsources{$dest}=$page;
838 if ($link=~s/^\/+//) {
846 $l.="/" if length $l;
849 if (exists $links{$l}) {
852 elsif (exists $pagecase{lc $l}) {
853 return $pagecase{lc $l};
855 } while $cwd=~s{/?[^/]+$}{};
857 if (length $config{userdir}) {
858 my $l = "$config{userdir}/".lc($link);
859 if (exists $links{$l}) {
862 elsif (exists $pagecase{lc $l}) {
863 return $pagecase{lc $l};
867 #print STDERR "warning: page $page, broken link: $link\n";
871 sub isinlinableimage ($) {
874 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
877 sub pagetitle ($;$) {
882 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
885 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
893 # support use w/o %config set
894 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
895 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
901 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
902 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
909 return $config{cgiurl}."?".
910 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
916 return "$config{url}/" if ! defined $page;
918 $page=htmlpage($page);
920 $page=~s/[^\/]+\//..\//g;
925 # Work around very innefficient behavior in File::Spec if abs2rel
926 # is passed two relative paths. It's much faster if paths are
927 # absolute! (Debian bug #376658; fixed in debian unstable now)
932 my $ret=File::Spec->abs2rel($path, $base);
933 $ret=~s/^// if defined $ret;
937 sub displaytime ($;$) {
938 # Plugins can override this function to mark up the time to
940 return '<span class="date">'.formattime(@_).'</span>';
943 sub formattime ($;$) {
944 # Plugins can override this function to format the time.
947 if (! defined $format) {
948 $format=$config{timeformat};
951 # strftime doesn't know about encodings, so make sure
952 # its output is properly treated as utf8
953 return decode_utf8(POSIX::strftime($format, localtime($time)));
956 sub beautify_urlpath ($) {
959 # Ensure url is not an empty link, and if necessary,
960 # add ./ to avoid colon confusion.
961 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
965 if ($config{usedirs}) {
966 $url =~ s!/index.$config{htmlext}$!/!;
978 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
981 if (! $destsources{$to}) {
986 return $config{url}.beautify_urlpath("/".$to);
989 my $link = abs2rel($to, dirname(htmlpage($from)));
991 return beautify_urlpath($link);
994 sub htmllink ($$$;@) {
995 my $lpage=shift; # the page doing the linking
996 my $page=shift; # the page that will contain the link (different for inline)
1003 if (! $opts{forcesubpage}) {
1004 $bestlink=bestlink($lpage, $link);
1007 $bestlink="$lpage/".lc($link);
1011 if (defined $opts{linktext}) {
1012 $linktext=$opts{linktext};
1015 $linktext=pagetitle(basename($link));
1018 return "<span class=\"selflink\">$linktext</span>"
1019 if length $bestlink && $page eq $bestlink &&
1020 ! defined $opts{anchor};
1022 if (! $destsources{$bestlink}) {
1023 $bestlink=htmlpage($bestlink);
1025 if (! $destsources{$bestlink}) {
1026 return $linktext unless length $config{cgiurl};
1027 return "<span class=\"createlink\"><a href=\"".
1033 "\" rel=\"nofollow\">?</a>$linktext</span>"
1037 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1038 $bestlink=beautify_urlpath($bestlink);
1040 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1041 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1044 if (defined $opts{anchor}) {
1045 $bestlink.="#".$opts{anchor};
1049 if (defined $opts{rel}) {
1050 push @attrs, ' rel="'.$opts{rel}.'"';
1052 if (defined $opts{class}) {
1053 push @attrs, ' class="'.$opts{class}.'"';
1056 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1062 my $oiduser=eval { openiduser($user) };
1063 if (defined $oiduser) {
1064 return "<a href=\"$user\">$oiduser</a>";
1067 eval q{use CGI 'escapeHTML'};
1070 return htmllink("", "", escapeHTML(
1071 length $config{userdir} ? $config{userdir}."/".$user : $user
1072 ), noimageinline => 1);
1076 sub htmlize ($$$$) {
1082 my $oneline = $content !~ /\n/;
1084 if (exists $hooks{htmlize}{$type}) {
1085 $content=$hooks{htmlize}{$type}{call}->(
1087 content => $content,
1091 error("htmlization of $type not supported");
1094 run_hooks(sanitize => sub {
1097 destpage => $destpage,
1098 content => $content,
1103 # hack to get rid of enclosing junk added by markdown
1104 # and other htmlizers
1105 $content=~s/^<p>//i;
1106 $content=~s/<\/p>$//i;
1118 run_hooks(linkify => sub {
1121 destpage => $destpage,
1122 content => $content,
1130 our $preprocess_preview=0;
1131 sub preprocess ($$$;$$) {
1132 my $page=shift; # the page the data comes from
1133 my $destpage=shift; # the page the data will appear in (different for inline)
1138 # Using local because it needs to be set within any nested calls
1140 local $preprocess_preview=$preview if defined $preview;
1147 $params="" if ! defined $params;
1149 if (length $escape) {
1150 return "[[$prefix$command $params]]";
1152 elsif (exists $hooks{preprocess}{$command}) {
1153 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1154 # Note: preserve order of params, some plugins may
1155 # consider it significant.
1157 while ($params =~ m{
1158 (?:([-\w]+)=)? # 1: named parameter key?
1160 """(.*?)""" # 2: triple-quoted value
1162 "([^"]+)" # 3: single-quoted value
1164 (\S+) # 4: unquoted value
1166 (?:\s+|$) # delimiter to next param
1176 elsif (defined $3) {
1179 elsif (defined $4) {
1184 push @params, $key, $val;
1187 push @params, $val, '';
1190 if ($preprocessing{$page}++ > 3) {
1191 # Avoid loops of preprocessed pages preprocessing
1192 # other pages that preprocess them, etc.
1193 return "[[!$command <span class=\"error\">".
1194 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1195 $page, $preprocessing{$page}).
1201 $hooks{preprocess}{$command}{call}->(
1204 destpage => $destpage,
1205 preview => $preprocess_preview,
1210 $ret="[[!$command <span class=\"error\">".
1211 gettext("Error").": $@"."</span>]]";
1215 # use void context during scan pass
1217 $hooks{preprocess}{$command}{call}->(
1220 destpage => $destpage,
1221 preview => $preprocess_preview,
1226 $preprocessing{$page}--;
1230 return "[[$prefix$command $params]]";
1235 if ($config{prefix_directives}) {
1238 \[\[(!) # directive open; 2: prefix
1239 ([-\w]+) # 3: command
1240 ( # 4: the parameters..
1241 \s+ # Must have space if parameters present
1243 (?:[-\w]+=)? # named parameter key?
1245 """.*?""" # triple-quoted value
1247 "[^"]+" # single-quoted value
1249 [^\s\]]+ # unquoted value
1251 \s* # whitespace or end
1254 *)? # 0 or more parameters
1255 \]\] # directive closed
1261 \[\[(!?) # directive open; 2: optional prefix
1262 ([-\w]+) # 3: command
1264 ( # 4: the parameters..
1266 (?:[-\w]+=)? # named parameter key?
1268 """.*?""" # triple-quoted value
1270 "[^"]+" # single-quoted value
1272 [^\s\]]+ # unquoted value
1274 \s* # whitespace or end
1277 *) # 0 or more parameters
1278 \]\] # directive closed
1282 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1291 run_hooks(filter => sub {
1292 $content=shift->(page => $page, destpage => $destpage,
1293 content => $content);
1300 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1303 sub check_canedit ($$$;$) {
1310 run_hooks(canedit => sub {
1311 return if defined $canedit;
1312 my $ret=shift->($page, $q, $session);
1317 elsif (ref $ret eq 'CODE') {
1318 $ret->() unless $nonfatal;
1321 elsif (defined $ret) {
1322 error($ret) unless $nonfatal;
1327 return defined $canedit ? $canedit : 1;
1330 sub check_content (@) {
1333 return 1 if ! exists $hooks{checkcontent}; # optimisation
1335 if (exists $pagesources{$params{page}}) {
1337 my %old=map { $_ => 1 }
1338 split("\n", readfile(srcfile($pagesources{$params{page}})));
1339 foreach my $line (split("\n", $params{content})) {
1340 push @diff, $line if ! exists $old{$_};
1342 $params{content}=join("\n", @diff);
1346 run_hooks(checkcontent => sub {
1347 return if defined $ok;
1348 my $ret=shift->(%params);
1353 elsif (ref $ret eq 'CODE') {
1354 $ret->() unless $params{nonfatal};
1357 elsif (defined $ret) {
1358 error($ret) unless $params{nonfatal};
1364 return defined $ok ? $ok : 1;
1370 # Take an exclusive lock on the wiki to prevent multiple concurrent
1371 # run issues. The lock will be dropped on program exit.
1372 if (! -d $config{wikistatedir}) {
1373 mkdir($config{wikistatedir});
1375 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1376 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1377 if (! flock($wikilock, 2)) { # LOCK_EX
1378 error("failed to get lock");
1384 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1385 return close($wikilock) if $wikilock;
1391 sub commit_hook_enabled () {
1392 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1393 error("cannot write to $config{wikistatedir}/commitlock: $!");
1394 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1395 close($commitlock) || error("failed closing commitlock: $!");
1398 close($commitlock) || error("failed closing commitlock: $!");
1402 sub disable_commit_hook () {
1403 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1404 error("cannot write to $config{wikistatedir}/commitlock: $!");
1405 if (! flock($commitlock, 2)) { # LOCK_EX
1406 error("failed to get commit lock");
1411 sub enable_commit_hook () {
1412 return close($commitlock) if $commitlock;
1417 %oldrenderedfiles=%pagectime=();
1418 if (! $config{rebuild}) {
1419 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1420 %destsources=%renderedfiles=%pagecase=%pagestate=();
1423 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1424 if (-e "$config{wikistatedir}/index") {
1425 system("ikiwiki-transition", "indexdb", $config{srcdir});
1426 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1433 my $index=Storable::fd_retrieve($in);
1434 if (! defined $index) {
1439 if (exists $index->{version} && ! ref $index->{version}) {
1440 $pages=$index->{page};
1441 %wikistate=%{$index->{state}};
1448 foreach my $src (keys %$pages) {
1449 my $d=$pages->{$src};
1450 my $page=pagename($src);
1451 $pagectime{$page}=$d->{ctime};
1452 if (! $config{rebuild}) {
1453 $pagesources{$page}=$src;
1454 $pagemtime{$page}=$d->{mtime};
1455 $renderedfiles{$page}=$d->{dest};
1456 if (exists $d->{links} && ref $d->{links}) {
1457 $links{$page}=$d->{links};
1458 $oldlinks{$page}=[@{$d->{links}}];
1460 if (exists $d->{depends}) {
1461 $depends{$page}=$d->{depends};
1463 if (exists $d->{state}) {
1464 $pagestate{$page}=$d->{state};
1467 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1469 foreach my $page (keys %pagesources) {
1470 $pagecase{lc $page}=$page;
1472 foreach my $page (keys %renderedfiles) {
1473 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1479 run_hooks(savestate => sub { shift->() });
1482 foreach my $type (keys %hooks) {
1483 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1485 my @hookids=keys %hookids;
1487 if (! -d $config{wikistatedir}) {
1488 mkdir($config{wikistatedir});
1490 my $newfile="$config{wikistatedir}/indexdb.new";
1491 my $cleanup = sub { unlink($newfile) };
1492 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1495 foreach my $page (keys %pagemtime) {
1496 next unless $pagemtime{$page};
1497 my $src=$pagesources{$page};
1499 $index{page}{$src}={
1500 ctime => $pagectime{$page},
1501 mtime => $pagemtime{$page},
1502 dest => $renderedfiles{$page},
1503 links => $links{$page},
1506 if (exists $depends{$page}) {
1507 $index{page}{$src}{depends} = $depends{$page};
1510 if (exists $pagestate{$page}) {
1511 foreach my $id (@hookids) {
1512 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1513 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1520 foreach my $id (@hookids) {
1521 foreach my $key (keys %{$wikistate{$id}}) {
1522 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1526 $index{version}="3";
1527 my $ret=Storable::nstore_fd(\%index, $out);
1528 return if ! defined $ret || ! $ret;
1529 close $out || error("failed saving to $newfile: $!", $cleanup);
1530 rename($newfile, "$config{wikistatedir}/indexdb") ||
1531 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1536 sub template_file ($) {
1539 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1540 return "$dir/$template" if -e "$dir/$template";
1545 sub template_params (@) {
1546 my $filename=template_file(shift);
1548 if (! defined $filename) {
1549 return if wantarray;
1555 my $text_ref = shift;
1556 ${$text_ref} = decode_utf8(${$text_ref});
1558 filename => $filename,
1559 loop_context_vars => 1,
1560 die_on_bad_params => 0,
1563 return wantarray ? @ret : {@ret};
1566 sub template ($;@) {
1567 require HTML::Template;
1568 return HTML::Template->new(template_params(@_));
1571 sub misctemplate ($$;@) {
1575 my $template=template("misc.tmpl");
1578 indexlink => indexlink(),
1579 wikiname => $config{wikiname},
1580 pagebody => $pagebody,
1581 baseurl => baseurl(),
1584 run_hooks(pagetemplate => sub {
1585 shift->(page => "", destpage => "", template => $template);
1587 return $template->output;
1593 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1594 error 'hook requires type, call, and id parameters';
1597 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1599 $hooks{$param{type}}{$param{id}}=\%param;
1603 sub run_hooks ($$) {
1604 # Calls the given sub for each hook of the given type,
1605 # passing it the hook function to call.
1609 if (exists $hooks{$type}) {
1610 my (@first, @middle, @last);
1611 foreach my $id (keys %{$hooks{$type}}) {
1612 if ($hooks{$type}{$id}{first}) {
1615 elsif ($hooks{$type}{$id}{last}) {
1622 foreach my $id (@first, @middle, @last) {
1623 $sub->($hooks{$type}{$id}{call});
1631 $hooks{rcs}{rcs_update}{call}->(@_);
1634 sub rcs_prepedit ($) {
1635 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1638 sub rcs_commit ($$$;$$) {
1639 $hooks{rcs}{rcs_commit}{call}->(@_);
1642 sub rcs_commit_staged ($$$) {
1643 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1647 $hooks{rcs}{rcs_add}{call}->(@_);
1650 sub rcs_remove ($) {
1651 $hooks{rcs}{rcs_remove}{call}->(@_);
1654 sub rcs_rename ($$) {
1655 $hooks{rcs}{rcs_rename}{call}->(@_);
1658 sub rcs_recentchanges ($) {
1659 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1663 $hooks{rcs}{rcs_diff}{call}->(@_);
1666 sub rcs_getctime ($) {
1667 $hooks{rcs}{rcs_getctime}{call}->(@_);
1670 sub rcs_receive () {
1671 $hooks{rcs}{rcs_receive}{call}->();
1680 sub add_depends ($$) {
1684 return unless pagespec_valid($pagespec);
1686 if (! exists $depends{$page}) {
1687 $depends{$page}=$pagespec;
1690 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1696 sub file_pruned ($$) {
1698 my $file=File::Spec->canonpath(shift);
1699 my $base=File::Spec->canonpath(shift);
1700 $file =~ s#^\Q$base\E/+##;
1702 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1703 return $file =~ m/$regexp/ && $file ne $base;
1707 # Only use gettext in the rare cases it's needed.
1708 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1709 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1710 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1711 if (! $gettext_obj) {
1712 $gettext_obj=eval q{
1713 use Locale::gettext q{textdomain};
1714 Locale::gettext->domain('ikiwiki')
1722 return $gettext_obj->get(shift);
1732 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1736 # Injects a new function into the symbol table to replace an
1737 # exported function.
1740 # This is deep ugly perl foo, beware.
1743 if (! defined $params{parent}) {
1744 $params{parent}='::';
1745 $params{old}=\&{$params{name}};
1746 $params{name}=~s/.*:://;
1748 my $parent=$params{parent};
1749 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1750 $ns = $params{parent} . $ns;
1751 inject(%params, parent => $ns) unless $ns eq '::main::';
1752 *{$ns . $params{name}} = $params{call}
1753 if exists ${$ns}{$params{name}} &&
1754 \&{${$ns}{$params{name}}} == $params{old};
1760 sub pagespec_merge ($$) {
1764 return $a if $a eq $b;
1765 return "($a) or ($b)";
1768 sub pagespec_translate ($) {
1771 # Convert spec to perl code.
1774 \s* # ignore whitespace
1775 ( # 1: match a single word
1782 \w+\([^\)]*\) # command(params)
1784 [^\s()]+ # any other text
1786 \s* # ignore whitespace
1789 if (lc $word eq 'and') {
1792 elsif (lc $word eq 'or') {
1795 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1798 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1799 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1800 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1803 $code.="IkiWiki::FailReason->new(".safequote(qq{unknown function in pagespec "$word"}).")";
1807 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1811 if (! length $code) {
1812 $code="IkiWiki::FailReason->new('empty pagespec')";
1816 return eval 'sub { my $page=shift; '.$code.' }';
1819 sub pagespec_match ($$;@) {
1824 # Backwards compatability with old calling convention.
1826 unshift @params, 'location';
1829 my $sub=pagespec_translate($spec);
1830 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"")
1831 if $@ || ! defined $sub;
1832 return $sub->($page, @params);
1835 sub pagespec_valid ($) {
1838 my $sub=pagespec_translate($spec);
1843 my $re=quotemeta(shift);
1849 package IkiWiki::FailReason;
1852 '""' => sub { ${$_[0]} },
1854 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1861 return bless \$value, $class;
1864 package IkiWiki::SuccessReason;
1867 '""' => sub { ${$_[0]} },
1869 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1876 return bless \$value, $class;
1879 package IkiWiki::PageSpec;
1885 if ($path =~ m!^\./!) {
1886 $from=~s#/?[^/]+$## if defined $from;
1888 $path="$from/$path" if length $from;
1894 sub match_glob ($$;@) {
1899 $glob=derel($glob, $params{location});
1901 my $regexp=IkiWiki::glob2re($glob);
1902 if ($page=~/^$regexp$/i) {
1903 if (! IkiWiki::isinternal($page) || $params{internal}) {
1904 return IkiWiki::SuccessReason->new("$glob matches $page");
1907 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1911 return IkiWiki::FailReason->new("$glob does not match $page");
1915 sub match_internal ($$;@) {
1916 return match_glob($_[0], $_[1], @_, internal => 1)
1919 sub match_link ($$;@) {
1924 $link=derel($link, $params{location});
1925 my $from=exists $params{location} ? $params{location} : '';
1927 my $links = $IkiWiki::links{$page};
1928 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1929 my $bestlink = IkiWiki::bestlink($from, $link);
1930 foreach my $p (@{$links}) {
1931 if (length $bestlink) {
1932 return IkiWiki::SuccessReason->new("$page links to $link")
1933 if $bestlink eq IkiWiki::bestlink($page, $p);
1936 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1937 if match_glob($p, $link, %params);
1940 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1941 if match_glob($p, $link, %params);
1944 return IkiWiki::FailReason->new("$page does not link to $link");
1947 sub match_backlink ($$;@) {
1948 return match_link($_[1], $_[0], @_);
1951 sub match_created_before ($$;@) {
1956 $testpage=derel($testpage, $params{location});
1958 if (exists $IkiWiki::pagectime{$testpage}) {
1959 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1960 return IkiWiki::SuccessReason->new("$page created before $testpage");
1963 return IkiWiki::FailReason->new("$page not created before $testpage");
1967 return IkiWiki::FailReason->new("$testpage has no ctime");
1971 sub match_created_after ($$;@) {
1976 $testpage=derel($testpage, $params{location});
1978 if (exists $IkiWiki::pagectime{$testpage}) {
1979 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1980 return IkiWiki::SuccessReason->new("$page created after $testpage");
1983 return IkiWiki::FailReason->new("$page not created after $testpage");
1987 return IkiWiki::FailReason->new("$testpage has no ctime");
1991 sub match_creation_day ($$;@) {
1992 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1993 return IkiWiki::SuccessReason->new('creation_day matched');
1996 return IkiWiki::FailReason->new('creation_day did not match');
2000 sub match_creation_month ($$;@) {
2001 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2002 return IkiWiki::SuccessReason->new('creation_month matched');
2005 return IkiWiki::FailReason->new('creation_month did not match');
2009 sub match_creation_year ($$;@) {
2010 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2011 return IkiWiki::SuccessReason->new('creation_year matched');
2014 return IkiWiki::FailReason->new('creation_year did not match');
2018 sub match_user ($$;@) {
2023 if (! exists $params{user}) {
2024 return IkiWiki::FailReason->new("no user specified");
2027 if (defined $params{user} && lc $params{user} eq lc $user) {
2028 return IkiWiki::SuccessReason->new("user is $user");
2030 elsif (! defined $params{user}) {
2031 return IkiWiki::FailReason->new("not logged in");
2034 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2038 sub match_admin ($$;@) {
2043 if (! exists $params{user}) {
2044 return IkiWiki::FailReason->new("no user specified");
2047 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2048 return IkiWiki::SuccessReason->new("user is an admin");
2050 elsif (! defined $params{user}) {
2051 return IkiWiki::FailReason->new("not logged in");
2054 return IkiWiki::FailReason->new("user is not an admin");
2058 sub match_ip ($$;@) {
2063 if (! exists $params{ip}) {
2064 return IkiWiki::FailReason->new("no IP specified");
2067 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2068 return IkiWiki::SuccessReason->new("IP is $ip");
2071 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");