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 %renderedfiles %oldrenderedfiles %pagesources
16 %destsources %depends %hooks %forcerebuild $gettext_obj
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
24 %config %links %pagestate %renderedfiles
25 %pagesources %destsources);
26 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
27 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
28 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
33 memoize("pagespec_translate");
34 memoize("file_pruned");
36 sub getsetup () { #{{{
40 description => "name of the wiki",
47 example => "$ENV{HOME}/wiki",
48 description => "where the source of the wiki is located",
55 example => "/var/www/wiki",
56 description => "where to build the wiki",
63 description => "user names of wiki admins",
70 example => 'me@example.com',
71 description => "contact email for wiki",
78 example => "http://example.com/wiki",
79 description => "base url to the wiki",
86 example => "http://example.com/wiki/ikiwiki.cgi",
87 description => "url to the ikiwiki.cgi",
94 example => "/var/www/wiki/ikiwiki.cgi",
95 description => "cgi executable to generate",
102 description => "mode for cgi_wrapper (can safely be made suid)",
109 description => "rcs backend to use",
110 safe => 0, # don't allow overriding
115 default => [qw{mdwn link inline htmlscrubber passwordauth
116 openid signinedit lockedit conditional
117 recentchanges parentlinks}],
118 description => "plugins to enable by default",
125 description => "plugins to add to the default configuration",
132 description => "plugins to disable",
138 default => "$installdir/share/ikiwiki/templates",
139 description => "location of template files",
145 default => "$installdir/share/ikiwiki/basewiki",
146 description => "base wiki source location",
153 description => "wrappers to generate",
160 description => "additional underlays to use",
167 description => "display verbose messages when building?",
174 description => "log to syslog?",
181 description => "create output files named page/index.html?",
182 safe => 0, # changing requires manual transition
185 prefix_directives => {
188 description => "use '!'-prefixed preprocessor directives?",
189 safe => 0, # changing requires manual transition
195 description => "enable Discussion pages?",
202 description => "extension to use for new pages",
203 safe => 0, # not sanitized
209 description => "extension to use for html files",
210 safe => 0, # not sanitized
216 description => "strftime format string to display date",
223 example => "en_US.UTF-8",
224 description => "UTF-8 locale to use",
231 description => "only send cookies over SSL connections?",
239 description => "put user pages below specified page",
246 description => "how many backlinks to show before hiding excess (0 to show all)",
253 description => "attempt to hardlink source files? (optimisation for large files)",
254 safe => 0, # paranoia
261 description => "force ikiwiki to use a particular umask",
262 safe => 0, # paranoia
268 example => "$ENV{HOME}/.ikiwiki/",
269 description => "extra library and plugin directory",
270 safe => 0, # directory
276 description => "environment variables",
277 safe => 0, # paranoia
284 description => "regexp of source files to ignore",
291 description => "users who cannot use the wiki",
295 wiki_file_prune_regexps => {
297 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
298 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
299 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
302 description => "regexps of source files to ignore",
306 wiki_file_regexp => {
308 default => qr/(^[-[:alnum:]_.:\/+]+$)/,
309 description => "regexp of legal source files",
313 web_commit_regexp => {
315 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
316 description => "regexp to parse web commits from logs",
323 description => "run as a cgi",
327 cgi_disable_uploads => {
330 description => "whether CGI should accept file uploads",
337 description => "run as a post-commit hook",
344 description => "running in rebuild mode",
351 description => "running in refresh mode",
358 description => "running in getctime mode",
365 description => "running in w3mmode",
372 description => "setup file to read",
378 sub defaultconfig () { #{{{
381 foreach my $key (keys %s) {
382 push @ret, $key, $s{$key}->{default};
388 sub checkconfig () { #{{{
389 # locale stuff; avoid LC_ALL since it overrides everything
390 if (defined $ENV{LC_ALL}) {
391 $ENV{LANG} = $ENV{LC_ALL};
394 if (defined $config{locale}) {
395 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
396 $ENV{LANG}=$config{locale};
401 if (ref $config{ENV} eq 'HASH') {
402 foreach my $val (keys %{$config{ENV}}) {
403 $ENV{$val}=$config{ENV}{$val};
407 if ($config{w3mmode}) {
408 eval q{use Cwd q{abs_path}};
410 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
411 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
412 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
413 unless $config{cgiurl} =~ m!file:///!;
414 $config{url}="file://".$config{destdir};
417 if ($config{cgi} && ! length $config{url}) {
418 error(gettext("Must specify url to wiki with --url when using --cgi"));
421 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
422 unless exists $config{wikistatedir};
424 if (defined $config{umask}) {
425 umask(possibly_foolish_untaint($config{umask}));
428 run_hooks(checkconfig => sub { shift->() });
433 sub listplugins () { #{{{
436 foreach my $dir (@INC, $config{libdir}) {
437 next unless defined $dir && length $dir;
438 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
439 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
443 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
444 next unless defined $dir && length $dir;
445 foreach my $file (glob("$dir/plugins/*")) {
446 $ret{basename($file)}=1 if -x $file;
453 sub loadplugins () { #{{{
454 if (defined $config{libdir} && length $config{libdir}) {
455 unshift @INC, possibly_foolish_untaint($config{libdir});
458 loadplugin($_) foreach @{$config{default_plugins}}, @{$config{add_plugins}};
461 if (exists $IkiWiki::hooks{rcs}) {
462 error(gettext("cannot use multiple rcs plugins"));
464 loadplugin($config{rcs});
466 if (! exists $IkiWiki::hooks{rcs}) {
470 run_hooks(getopt => sub { shift->() });
471 if (grep /^-/, @ARGV) {
472 print STDERR "Unknown option: $_\n"
473 foreach grep /^-/, @ARGV;
480 sub loadplugin ($) { #{{{
483 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
485 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
486 "$installdir/lib/ikiwiki") {
487 if (defined $dir && -x "$dir/plugins/$plugin") {
488 require IkiWiki::Plugin::external;
489 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
490 $loaded_plugins{$plugin}=1;
495 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
498 error("Failed to load plugin $mod: $@");
500 $loaded_plugins{$plugin}=1;
504 sub error ($;$) { #{{{
507 log_message('err' => $message) if $config{syslog};
508 if (defined $cleaner) {
515 return unless $config{verbose};
516 return log_message(debug => @_);
520 sub log_message ($$) { #{{{
523 if ($config{syslog}) {
526 Sys::Syslog::setlogsock('unix');
527 Sys::Syslog::openlog('ikiwiki', '', 'user');
531 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
534 elsif (! $config{cgi}) {
538 return print STDERR "@_\n";
542 sub possibly_foolish_untaint ($) { #{{{
544 my ($untainted)=$tainted=~/(.*)/s;
548 sub basename ($) { #{{{
555 sub dirname ($) { #{{{
562 sub pagetype ($) { #{{{
565 if ($page =~ /\.([^.]+)$/) {
566 return $1 if exists $hooks{htmlize}{$1};
571 sub isinternal ($) { #{{{
573 return exists $pagesources{$page} &&
574 $pagesources{$page} =~ /\._([^.]+)$/;
577 sub pagename ($) { #{{{
580 my $type=pagetype($file);
582 $page=~s/\Q.$type\E*$// if defined $type;
586 sub targetpage ($$) { #{{{
590 if (! $config{usedirs} || $page =~ /^index$/ ) {
591 return $page.".".$ext;
593 return $page."/index.".$ext;
597 sub htmlpage ($) { #{{{
600 return targetpage($page, $config{htmlext});
603 sub srcfile_stat { #{{{
607 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
608 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
609 return "$dir/$file", stat(_) if -e "$dir/$file";
611 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
615 sub srcfile ($;$) { #{{{
616 return (srcfile_stat(@_))[0];
619 sub add_underlay ($) { #{{{
623 unshift @{$config{underlaydirs}}, $dir;
626 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
632 sub readfile ($;$$) { #{{{
638 error("cannot read a symlink ($file)");
642 open (my $in, "<", $file) || error("failed to read $file: $!");
643 binmode($in) if ($binary);
644 return \*$in if $wantfd;
646 close $in || error("failed to read $file: $!");
650 sub prep_writefile ($$) { #{{{
655 while (length $test) {
656 if (-l "$destdir/$test") {
657 error("cannot write to a symlink ($test)");
659 $test=dirname($test);
662 my $dir=dirname("$destdir/$file");
665 foreach my $s (split(m!/+!, $dir)) {
668 mkdir($d) || error("failed to create directory $d: $!");
676 sub writefile ($$$;$$) { #{{{
677 my $file=shift; # can include subdirs
678 my $destdir=shift; # directory to put file in
683 prep_writefile($file, $destdir);
685 my $newfile="$destdir/$file.ikiwiki-new";
687 error("cannot write to a symlink ($newfile)");
690 my $cleanup = sub { unlink($newfile) };
691 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
692 binmode($out) if ($binary);
694 $writer->(\*$out, $cleanup);
697 print $out $content or error("failed writing to $newfile: $!", $cleanup);
699 close $out || error("failed saving $newfile: $!", $cleanup);
700 rename($newfile, "$destdir/$file") ||
701 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
707 sub will_render ($$;$) { #{{{
712 # Important security check.
713 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
714 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
715 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
718 if (! $clear || $cleared{$page}) {
719 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
722 foreach my $old (@{$renderedfiles{$page}}) {
723 delete $destsources{$old};
725 $renderedfiles{$page}=[$dest];
728 $destsources{$dest}=$page;
733 sub bestlink ($$) { #{{{
738 if ($link=~s/^\/+//) {
746 $l.="/" if length $l;
749 if (exists $links{$l}) {
752 elsif (exists $pagecase{lc $l}) {
753 return $pagecase{lc $l};
755 } while $cwd=~s!/?[^/]+$!!;
757 if (length $config{userdir}) {
758 my $l = "$config{userdir}/".lc($link);
759 if (exists $links{$l}) {
762 elsif (exists $pagecase{lc $l}) {
763 return $pagecase{lc $l};
767 #print STDERR "warning: page $page, broken link: $link\n";
771 sub isinlinableimage ($) { #{{{
774 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
777 sub pagetitle ($;$) { #{{{
782 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
785 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
791 sub titlepage ($) { #{{{
793 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
797 sub linkpage ($) { #{{{
799 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
803 sub cgiurl (@) { #{{{
806 return $config{cgiurl}."?".
807 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
810 sub baseurl (;$) { #{{{
813 return "$config{url}/" if ! defined $page;
815 $page=htmlpage($page);
817 $page=~s/[^\/]+\//..\//g;
821 sub abs2rel ($$) { #{{{
822 # Work around very innefficient behavior in File::Spec if abs2rel
823 # is passed two relative paths. It's much faster if paths are
824 # absolute! (Debian bug #376658; fixed in debian unstable now)
829 my $ret=File::Spec->abs2rel($path, $base);
830 $ret=~s/^// if defined $ret;
834 sub displaytime ($;$) { #{{{
837 if (! defined $format) {
838 $format=$config{timeformat};
841 # strftime doesn't know about encodings, so make sure
842 # its output is properly treated as utf8
843 return decode_utf8(POSIX::strftime($format, localtime($time)));
846 sub beautify_urlpath ($) { #{{{
849 if ($config{usedirs}) {
850 $url =~ s!/index.$config{htmlext}$!/!;
853 # Ensure url is not an empty link, and
854 # if it's relative, make that explicit to avoid colon confusion.
862 sub urlto ($$;$) { #{{{
868 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
871 if (! $destsources{$to}) {
876 return $config{url}.beautify_urlpath("/".$to);
879 my $link = abs2rel($to, dirname(htmlpage($from)));
881 return beautify_urlpath($link);
884 sub htmllink ($$$;@) { #{{{
885 my $lpage=shift; # the page doing the linking
886 my $page=shift; # the page that will contain the link (different for inline)
893 if (! $opts{forcesubpage}) {
894 $bestlink=bestlink($lpage, $link);
897 $bestlink="$lpage/".lc($link);
901 if (defined $opts{linktext}) {
902 $linktext=$opts{linktext};
905 $linktext=pagetitle(basename($link));
908 return "<span class=\"selflink\">$linktext</span>"
909 if length $bestlink && $page eq $bestlink &&
910 ! defined $opts{anchor};
912 if (! $destsources{$bestlink}) {
913 $bestlink=htmlpage($bestlink);
915 if (! $destsources{$bestlink}) {
916 return $linktext unless length $config{cgiurl};
917 return "<span class=\"createlink\"><a href=\"".
923 "\" rel=\"nofollow\">?</a>$linktext</span>"
927 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
928 $bestlink=beautify_urlpath($bestlink);
930 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
931 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
934 if (defined $opts{anchor}) {
935 $bestlink.="#".$opts{anchor};
939 if (defined $opts{rel}) {
940 push @attrs, ' rel="'.$opts{rel}.'"';
942 if (defined $opts{class}) {
943 push @attrs, ' class="'.$opts{class}.'"';
946 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
949 sub userlink ($) { #{{{
952 my $oiduser=eval { openiduser($user) };
953 if (defined $oiduser) {
954 return "<a href=\"$user\">$oiduser</a>";
957 eval q{use CGI 'escapeHTML'};
960 return htmllink("", "", escapeHTML(
961 length $config{userdir} ? $config{userdir}."/".$user : $user
962 ), noimageinline => 1);
966 sub htmlize ($$$$) { #{{{
972 my $oneline = $content !~ /\n/;
974 if (exists $hooks{htmlize}{$type}) {
975 $content=$hooks{htmlize}{$type}{call}->(
981 error("htmlization of $type not supported");
984 run_hooks(sanitize => sub {
987 destpage => $destpage,
993 # hack to get rid of enclosing junk added by markdown
994 # and other htmlizers
996 $content=~s/<\/p>$//i;
1003 sub linkify ($$$) { #{{{
1008 run_hooks(linkify => sub {
1011 destpage => $destpage,
1012 content => $content,
1020 our $preprocess_preview=0;
1021 sub preprocess ($$$;$$) { #{{{
1022 my $page=shift; # the page the data comes from
1023 my $destpage=shift; # the page the data will appear in (different for inline)
1028 # Using local because it needs to be set within any nested calls
1030 local $preprocess_preview=$preview if defined $preview;
1037 if (length $escape) {
1038 return "[[$prefix$command $params]]";
1040 elsif (exists $hooks{preprocess}{$command}) {
1041 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1042 # Note: preserve order of params, some plugins may
1043 # consider it significant.
1045 while ($params =~ m{
1046 (?:([-\w]+)=)? # 1: named parameter key?
1048 """(.*?)""" # 2: triple-quoted value
1050 "([^"]+)" # 3: single-quoted value
1052 (\S+) # 4: unquoted value
1054 (?:\s+|$) # delimiter to next param
1064 elsif (defined $3) {
1067 elsif (defined $4) {
1072 push @params, $key, $val;
1075 push @params, $val, '';
1078 if ($preprocessing{$page}++ > 3) {
1079 # Avoid loops of preprocessed pages preprocessing
1080 # other pages that preprocess them, etc.
1081 return "[[!$command <span class=\"error\">".
1082 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1083 $page, $preprocessing{$page}).
1089 $hooks{preprocess}{$command}{call}->(
1092 destpage => $destpage,
1093 preview => $preprocess_preview,
1098 $ret="[[!$command <span class=\"error\">".
1099 gettext("Error").": $@"."</span>]]";
1103 # use void context during scan pass
1105 $hooks{preprocess}{$command}{call}->(
1108 destpage => $destpage,
1109 preview => $preprocess_preview,
1114 $preprocessing{$page}--;
1118 return "[[$prefix$command $params]]";
1123 if ($config{prefix_directives}) {
1126 \[\[(!) # directive open; 2: prefix
1127 ([-\w]+) # 3: command
1128 ( # 4: the parameters..
1129 \s+ # Must have space if parameters present
1131 (?:[-\w]+=)? # named parameter key?
1133 """.*?""" # triple-quoted value
1135 "[^"]+" # single-quoted value
1137 [^\s\]]+ # unquoted value
1139 \s* # whitespace or end
1142 *)? # 0 or more parameters
1143 \]\] # directive closed
1149 \[\[(!?) # directive open; 2: optional prefix
1150 ([-\w]+) # 3: command
1152 ( # 4: the parameters..
1154 (?:[-\w]+=)? # named parameter key?
1156 """.*?""" # triple-quoted value
1158 "[^"]+" # single-quoted value
1160 [^\s\]]+ # unquoted value
1162 \s* # whitespace or end
1165 *) # 0 or more parameters
1166 \]\] # directive closed
1170 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1174 sub filter ($$$) { #{{{
1179 run_hooks(filter => sub {
1180 $content=shift->(page => $page, destpage => $destpage,
1181 content => $content);
1187 sub indexlink () { #{{{
1188 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1193 sub lockwiki (;$) { #{{{
1194 my $wait=@_ ? shift : 1;
1195 # Take an exclusive lock on the wiki to prevent multiple concurrent
1196 # run issues. The lock will be dropped on program exit.
1197 if (! -d $config{wikistatedir}) {
1198 mkdir($config{wikistatedir});
1200 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1201 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1202 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1204 debug("wiki seems to be locked, waiting for lock");
1205 my $wait=600; # arbitrary, but don't hang forever to
1206 # prevent process pileup
1208 return if flock($wikilock, 2 | 4);
1211 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1220 sub unlockwiki () { #{{{
1221 return close($wikilock) if $wikilock;
1227 sub commit_hook_enabled () { #{{{
1228 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1229 error("cannot write to $config{wikistatedir}/commitlock: $!");
1230 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1231 close($commitlock) || error("failed closing commitlock: $!");
1234 close($commitlock) || error("failed closing commitlock: $!");
1238 sub disable_commit_hook () { #{{{
1239 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1240 error("cannot write to $config{wikistatedir}/commitlock: $!");
1241 if (! flock($commitlock, 2)) { # LOCK_EX
1242 error("failed to get commit lock");
1247 sub enable_commit_hook () { #{{{
1248 return close($commitlock) if $commitlock;
1252 sub loadindex () { #{{{
1253 %oldrenderedfiles=%pagectime=();
1254 if (! $config{rebuild}) {
1255 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1256 %destsources=%renderedfiles=%pagecase=%pagestate=();
1259 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1260 if (-e "$config{wikistatedir}/index") {
1261 system("ikiwiki-transition", "indexdb", $config{srcdir});
1262 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1268 my $ret=Storable::fd_retrieve($in);
1269 if (! defined $ret) {
1273 foreach my $src (keys %index) {
1274 my %d=%{$index{$src}};
1275 my $page=pagename($src);
1276 $pagectime{$page}=$d{ctime};
1277 if (! $config{rebuild}) {
1278 $pagesources{$page}=$src;
1279 $pagemtime{$page}=$d{mtime};
1280 $renderedfiles{$page}=$d{dest};
1281 if (exists $d{links} && ref $d{links}) {
1282 $links{$page}=$d{links};
1283 $oldlinks{$page}=[@{$d{links}}];
1285 if (exists $d{depends}) {
1286 $depends{$page}=$d{depends};
1288 if (exists $d{state}) {
1289 $pagestate{$page}=$d{state};
1292 $oldrenderedfiles{$page}=[@{$d{dest}}];
1294 foreach my $page (keys %pagesources) {
1295 $pagecase{lc $page}=$page;
1297 foreach my $page (keys %renderedfiles) {
1298 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1303 sub saveindex () { #{{{
1304 run_hooks(savestate => sub { shift->() });
1307 foreach my $type (keys %hooks) {
1308 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1310 my @hookids=keys %hookids;
1312 if (! -d $config{wikistatedir}) {
1313 mkdir($config{wikistatedir});
1315 my $newfile="$config{wikistatedir}/indexdb.new";
1316 my $cleanup = sub { unlink($newfile) };
1317 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1319 foreach my $page (keys %pagemtime) {
1320 next unless $pagemtime{$page};
1321 my $src=$pagesources{$page};
1324 ctime => $pagectime{$page},
1325 mtime => $pagemtime{$page},
1326 dest => $renderedfiles{$page},
1327 links => $links{$page},
1330 if (exists $depends{$page}) {
1331 $index{$src}{depends} = $depends{$page};
1334 if (exists $pagestate{$page}) {
1335 foreach my $id (@hookids) {
1336 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1337 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1342 my $ret=Storable::nstore_fd(\%index, $out);
1343 return if ! defined $ret || ! $ret;
1344 close $out || error("failed saving to $newfile: $!", $cleanup);
1345 rename($newfile, "$config{wikistatedir}/indexdb") ||
1346 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1351 sub template_file ($) { #{{{
1354 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1355 return "$dir/$template" if -e "$dir/$template";
1360 sub template_params (@) { #{{{
1361 my $filename=template_file(shift);
1363 if (! defined $filename) {
1364 return if wantarray;
1370 my $text_ref = shift;
1371 ${$text_ref} = decode_utf8(${$text_ref});
1373 filename => $filename,
1374 loop_context_vars => 1,
1375 die_on_bad_params => 0,
1378 return wantarray ? @ret : {@ret};
1381 sub template ($;@) { #{{{
1382 require HTML::Template;
1383 return HTML::Template->new(template_params(@_));
1386 sub misctemplate ($$;@) { #{{{
1390 my $template=template("misc.tmpl");
1393 indexlink => indexlink(),
1394 wikiname => $config{wikiname},
1395 pagebody => $pagebody,
1396 baseurl => baseurl(),
1399 run_hooks(pagetemplate => sub {
1400 shift->(page => "", destpage => "", template => $template);
1402 return $template->output;
1405 sub hook (@) { # {{{
1408 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1409 error 'hook requires type, call, and id parameters';
1412 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1414 $hooks{$param{type}}{$param{id}}=\%param;
1418 sub run_hooks ($$) { # {{{
1419 # Calls the given sub for each hook of the given type,
1420 # passing it the hook function to call.
1424 if (exists $hooks{$type}) {
1426 foreach my $id (keys %{$hooks{$type}}) {
1427 if ($hooks{$type}{$id}{last}) {
1428 push @deferred, $id;
1431 $sub->($hooks{$type}{$id}{call});
1433 foreach my $id (@deferred) {
1434 $sub->($hooks{$type}{$id}{call});
1441 sub rcs_update () { #{{{
1442 $hooks{rcs}{rcs_update}{call}->(@_);
1445 sub rcs_prepedit ($) { #{{{
1446 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1449 sub rcs_commit ($$$;$$) { #{{{
1450 $hooks{rcs}{rcs_commit}{call}->(@_);
1453 sub rcs_commit_staged ($$$) { #{{{
1454 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1457 sub rcs_add ($) { #{{{
1458 $hooks{rcs}{rcs_add}{call}->(@_);
1461 sub rcs_remove ($) { #{{{
1462 $hooks{rcs}{rcs_remove}{call}->(@_);
1465 sub rcs_rename ($$) { #{{{
1466 $hooks{rcs}{rcs_rename}{call}->(@_);
1469 sub rcs_recentchanges ($) { #{{{
1470 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1473 sub rcs_diff ($) { #{{{
1474 $hooks{rcs}{rcs_diff}{call}->(@_);
1477 sub rcs_getctime ($) { #{{{
1478 $hooks{rcs}{rcs_getctime}{call}->(@_);
1481 sub globlist_to_pagespec ($) { #{{{
1482 my @globlist=split(' ', shift);
1485 foreach my $glob (@globlist) {
1486 if ($glob=~/^!(.*)/) {
1494 my $spec=join(' or ', @spec);
1496 my $skip=join(' and ', @skip);
1498 $spec="$skip and ($spec)";
1507 sub is_globlist ($) { #{{{
1509 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1512 sub safequote ($) { #{{{
1518 sub add_depends ($$) { #{{{
1522 return unless pagespec_valid($pagespec);
1524 if (! exists $depends{$page}) {
1525 $depends{$page}=$pagespec;
1528 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1534 sub file_pruned ($$) { #{{{
1536 my $file=File::Spec->canonpath(shift);
1537 my $base=File::Spec->canonpath(shift);
1538 $file =~ s#^\Q$base\E/+##;
1540 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1541 return $file =~ m/$regexp/ && $file ne $base;
1545 # Only use gettext in the rare cases it's needed.
1546 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1547 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1548 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1549 if (! $gettext_obj) {
1550 $gettext_obj=eval q{
1551 use Locale::gettext q{textdomain};
1552 Locale::gettext->domain('ikiwiki')
1560 return $gettext_obj->get(shift);
1567 sub yesno ($) { #{{{
1570 return (defined $val && lc($val) eq gettext("yes"));
1573 sub pagespec_merge ($$) { #{{{
1577 return $a if $a eq $b;
1579 # Support for old-style GlobLists.
1580 if (is_globlist($a)) {
1581 $a=globlist_to_pagespec($a);
1583 if (is_globlist($b)) {
1584 $b=globlist_to_pagespec($b);
1587 return "($a) or ($b)";
1590 sub pagespec_translate ($) { #{{{
1593 # Support for old-style GlobLists.
1594 if (is_globlist($spec)) {
1595 $spec=globlist_to_pagespec($spec);
1598 # Convert spec to perl code.
1601 \s* # ignore whitespace
1602 ( # 1: match a single word
1609 \w+\([^\)]*\) # command(params)
1611 [^\s()]+ # any other text
1613 \s* # ignore whitespace
1616 if (lc $word eq 'and') {
1619 elsif (lc $word eq 'or') {
1622 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1625 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1626 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1627 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1634 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1638 if (! length $code) {
1643 return eval 'sub { my $page=shift; '.$code.' }';
1646 sub pagespec_match ($$;@) { #{{{
1651 # Backwards compatability with old calling convention.
1653 unshift @params, 'location';
1656 my $sub=pagespec_translate($spec);
1657 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1658 return $sub->($page, @params);
1661 sub pagespec_valid ($) { #{{{
1664 my $sub=pagespec_translate($spec);
1668 sub glob2re ($) { #{{{
1669 my $re=quotemeta(shift);
1675 package IkiWiki::FailReason;
1678 '""' => sub { ${$_[0]} },
1680 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1687 return bless \$value, $class;
1690 package IkiWiki::SuccessReason;
1693 '""' => sub { ${$_[0]} },
1695 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1702 return bless \$value, $class;
1705 package IkiWiki::PageSpec;
1707 sub match_glob ($$;@) { #{{{
1712 my $from=exists $params{location} ? $params{location} : '';
1715 if ($glob =~ m!^\./!) {
1716 $from=~s#/?[^/]+$##;
1718 $glob="$from/$glob" if length $from;
1721 my $regexp=IkiWiki::glob2re($glob);
1722 if ($page=~/^$regexp$/i) {
1723 if (! IkiWiki::isinternal($page) || $params{internal}) {
1724 return IkiWiki::SuccessReason->new("$glob matches $page");
1727 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1731 return IkiWiki::FailReason->new("$glob does not match $page");
1735 sub match_internal ($$;@) { #{{{
1736 return match_glob($_[0], $_[1], @_, internal => 1)
1739 sub match_link ($$;@) { #{{{
1744 my $from=exists $params{location} ? $params{location} : '';
1747 if ($link =~ m!^\.! && defined $from) {
1748 $from=~s#/?[^/]+$##;
1750 $link="$from/$link" if length $from;
1753 my $links = $IkiWiki::links{$page};
1754 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1755 my $bestlink = IkiWiki::bestlink($from, $link);
1756 foreach my $p (@{$links}) {
1757 if (length $bestlink) {
1758 return IkiWiki::SuccessReason->new("$page links to $link")
1759 if $bestlink eq IkiWiki::bestlink($page, $p);
1762 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1763 if match_glob($p, $link, %params);
1766 return IkiWiki::FailReason->new("$page does not link to $link");
1769 sub match_backlink ($$;@) { #{{{
1770 return match_link($_[1], $_[0], @_);
1773 sub match_created_before ($$;@) { #{{{
1777 if (exists $IkiWiki::pagectime{$testpage}) {
1778 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1779 return IkiWiki::SuccessReason->new("$page created before $testpage");
1782 return IkiWiki::FailReason->new("$page not created before $testpage");
1786 return IkiWiki::FailReason->new("$testpage has no ctime");
1790 sub match_created_after ($$;@) { #{{{
1794 if (exists $IkiWiki::pagectime{$testpage}) {
1795 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1796 return IkiWiki::SuccessReason->new("$page created after $testpage");
1799 return IkiWiki::FailReason->new("$page not created after $testpage");
1803 return IkiWiki::FailReason->new("$testpage has no ctime");
1807 sub match_creation_day ($$;@) { #{{{
1808 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1809 return IkiWiki::SuccessReason->new('creation_day matched');
1812 return IkiWiki::FailReason->new('creation_day did not match');
1816 sub match_creation_month ($$;@) { #{{{
1817 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1818 return IkiWiki::SuccessReason->new('creation_month matched');
1821 return IkiWiki::FailReason->new('creation_month did not match');
1825 sub match_creation_year ($$;@) { #{{{
1826 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1827 return IkiWiki::SuccessReason->new('creation_year matched');
1830 return IkiWiki::FailReason->new('creation_year did not match');