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};
18 use Exporter q{import};
19 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
20 bestlink htmllink readfile writefile pagetype srcfile pagename
21 displaytime will_render gettext urlto targetpage
23 %config %links %pagestate %renderedfiles
24 %pagesources %destsources);
25 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
26 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
27 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
32 memoize("pagespec_translate");
33 memoize("file_pruned");
35 sub getsetup () { #{{{
39 description => "name of the wiki",
46 example => "$ENV{HOME}/wiki",
47 description => "where the source of the wiki is located",
54 example => "/var/www/wiki",
55 description => "where to build the wiki",
62 description => "user names of wiki admins",
69 example => 'me@example.com',
70 description => "contact email for wiki",
77 example => "http://example.com/wiki",
78 description => "base url to the wiki",
85 examples => "http://example.com/wiki/ikiwiki.cgi",
86 description => "url to the ikiwiki.cgi",
93 description => "rcs backend to use",
94 safe => 0, # don't allow overriding
99 default => [qw{mdwn link inline htmlscrubber passwordauth
100 openid signinedit lockedit conditional
101 recentchanges parentlinks}],
102 description => "plugins to enable by default",
109 description => "plugins to add to the default configuration",
116 description => "plugins to disable",
123 description => "definitions of wrappers to generate",
130 description => "wrapper filename",
137 description => "mode of wrapper file",
143 default => "$installdir/share/ikiwiki/templates",
144 description => "location of template files",
150 default => "$installdir/share/ikiwiki/basewiki",
151 description => "base wiki source location",
158 description => "additional underlays to use",
165 description => "display verbose messages when building?",
172 description => "log to syslog?",
179 description => "create output files named page/index.html?",
180 safe => 0, # changing requires manual transition
183 prefix_directives => {
186 description => "use '!'-prefixed preprocessor directives?",
187 safe => 0, # changing requires manual transition
193 description => "enable Discussion pages?",
200 description => "extension to use for new pages",
201 safe => 0, # not sanitized
207 description => "extension to use for html files",
208 safe => 0, # not sanitized
214 description => "strftime format string to display date",
221 example => "en_US.UTF-8",
222 description => "UTF-8 locale to use",
229 description => "only send cookies over SSL connections?",
237 description => "put user pages below specified page",
244 description => "how many backlinks to show before hiding excess (0 to show all)",
251 description => "attempt to hardlink source files? (optimisation for large files)",
252 safe => 0, # paranoia
260 description => "regexp of source files to ignore",
264 wiki_file_prune_regexps => {
266 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
267 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
268 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
271 description => "regexps of source files to ignore",
275 wiki_file_regexp => {
277 default => qr/(^[-[:alnum:]_.:\/+]+$)/,
278 description => "regexp of legal source files",
282 web_commit_regexp => {
284 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
285 description => "regexp to parse web commits from logs",
292 description => "run as a cgi",
296 cgi_disable_uploads => {
299 description => "whether CGI should accept file uploads",
306 description => "run as a post-commit hook",
313 description => "running in rebuild mode",
320 description => "running in refresh mode",
327 description => "running in getctime mode",
334 description => "running in w3mmode",
341 description => "setup file to read",
348 example => "$ENV{HOME}/.ikiwiki/",
349 description => "extra library and plugin directory",
355 sub defaultconfig () { #{{{
358 foreach my $key (keys %s) {
359 push @ret, $key, $s{$key}->{default};
365 sub checkconfig () { #{{{
366 # locale stuff; avoid LC_ALL since it overrides everything
367 if (defined $ENV{LC_ALL}) {
368 $ENV{LANG} = $ENV{LC_ALL};
371 if (defined $config{locale}) {
372 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
373 $ENV{LANG}=$config{locale};
378 if (ref $config{ENV} eq 'HASH') {
379 foreach my $val (keys %{$config{ENV}}) {
380 $ENV{$val}=$config{ENV}{$val};
384 if ($config{w3mmode}) {
385 eval q{use Cwd q{abs_path}};
387 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
388 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
389 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
390 unless $config{cgiurl} =~ m!file:///!;
391 $config{url}="file://".$config{destdir};
394 if ($config{cgi} && ! length $config{url}) {
395 error(gettext("Must specify url to wiki with --url when using --cgi"));
398 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
399 unless exists $config{wikistatedir};
402 eval qq{use IkiWiki::Rcs::$config{rcs}};
404 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
408 require IkiWiki::Rcs::Stub;
411 if (exists $config{umask}) {
412 umask(possibly_foolish_untaint($config{umask}));
415 run_hooks(checkconfig => sub { shift->() });
420 sub listplugins () { #{{{
423 foreach my $dir (@INC, $config{libdir}) {
424 next unless defined $dir;
425 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
426 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
430 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
431 next unless defined $dir;
432 foreach my $file (glob("$dir/plugins/*")) {
433 $ret{basename($file)}=1 if -x $file;
440 sub loadplugins () { #{{{
441 if (defined $config{libdir}) {
442 unshift @INC, possibly_foolish_untaint($config{libdir});
445 loadplugin($_) foreach @{$config{default_plugins}}, @{$config{add_plugins}};
447 run_hooks(getopt => sub { shift->() });
448 if (grep /^-/, @ARGV) {
449 print STDERR "Unknown option: $_\n"
450 foreach grep /^-/, @ARGV;
457 sub loadplugin ($) { #{{{
460 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
462 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
463 "$installdir/lib/ikiwiki") {
464 if (defined $dir && -x "$dir/plugins/$plugin") {
465 require IkiWiki::Plugin::external;
466 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
471 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
474 error("Failed to load plugin $mod: $@");
479 sub error ($;$) { #{{{
482 log_message('err' => $message) if $config{syslog};
483 if (defined $cleaner) {
490 return unless $config{verbose};
491 return log_message(debug => @_);
495 sub log_message ($$) { #{{{
498 if ($config{syslog}) {
501 Sys::Syslog::setlogsock('unix');
502 Sys::Syslog::openlog('ikiwiki', '', 'user');
506 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
509 elsif (! $config{cgi}) {
513 return print STDERR "@_\n";
517 sub possibly_foolish_untaint ($) { #{{{
519 my ($untainted)=$tainted=~/(.*)/s;
523 sub basename ($) { #{{{
530 sub dirname ($) { #{{{
537 sub pagetype ($) { #{{{
540 if ($page =~ /\.([^.]+)$/) {
541 return $1 if exists $hooks{htmlize}{$1};
546 sub isinternal ($) { #{{{
548 return exists $pagesources{$page} &&
549 $pagesources{$page} =~ /\._([^.]+)$/;
552 sub pagename ($) { #{{{
555 my $type=pagetype($file);
557 $page=~s/\Q.$type\E*$// if defined $type;
561 sub targetpage ($$) { #{{{
565 if (! $config{usedirs} || $page =~ /^index$/ ) {
566 return $page.".".$ext;
568 return $page."/index.".$ext;
572 sub htmlpage ($) { #{{{
575 return targetpage($page, $config{htmlext});
578 sub srcfile_stat { #{{{
582 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
583 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
584 return "$dir/$file", stat(_) if -e "$dir/$file";
586 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
590 sub srcfile ($;$) { #{{{
591 return (srcfile_stat(@_))[0];
594 sub add_underlay ($) { #{{{
598 unshift @{$config{underlaydirs}}, $dir;
601 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
607 sub readfile ($;$$) { #{{{
613 error("cannot read a symlink ($file)");
617 open (my $in, "<", $file) || error("failed to read $file: $!");
618 binmode($in) if ($binary);
619 return \*$in if $wantfd;
621 close $in || error("failed to read $file: $!");
625 sub prep_writefile ($$) { #{{{
630 while (length $test) {
631 if (-l "$destdir/$test") {
632 error("cannot write to a symlink ($test)");
634 $test=dirname($test);
637 my $dir=dirname("$destdir/$file");
640 foreach my $s (split(m!/+!, $dir)) {
643 mkdir($d) || error("failed to create directory $d: $!");
651 sub writefile ($$$;$$) { #{{{
652 my $file=shift; # can include subdirs
653 my $destdir=shift; # directory to put file in
658 prep_writefile($file, $destdir);
660 my $newfile="$destdir/$file.ikiwiki-new";
662 error("cannot write to a symlink ($newfile)");
665 my $cleanup = sub { unlink($newfile) };
666 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
667 binmode($out) if ($binary);
669 $writer->(\*$out, $cleanup);
672 print $out $content or error("failed writing to $newfile: $!", $cleanup);
674 close $out || error("failed saving $newfile: $!", $cleanup);
675 rename($newfile, "$destdir/$file") ||
676 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
682 sub will_render ($$;$) { #{{{
687 # Important security check.
688 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
689 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
690 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
693 if (! $clear || $cleared{$page}) {
694 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
697 foreach my $old (@{$renderedfiles{$page}}) {
698 delete $destsources{$old};
700 $renderedfiles{$page}=[$dest];
703 $destsources{$dest}=$page;
708 sub bestlink ($$) { #{{{
713 if ($link=~s/^\/+//) {
721 $l.="/" if length $l;
724 if (exists $links{$l}) {
727 elsif (exists $pagecase{lc $l}) {
728 return $pagecase{lc $l};
730 } while $cwd=~s!/?[^/]+$!!;
732 if (length $config{userdir}) {
733 my $l = "$config{userdir}/".lc($link);
734 if (exists $links{$l}) {
737 elsif (exists $pagecase{lc $l}) {
738 return $pagecase{lc $l};
742 #print STDERR "warning: page $page, broken link: $link\n";
746 sub isinlinableimage ($) { #{{{
749 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
752 sub pagetitle ($;$) { #{{{
757 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
760 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
766 sub titlepage ($) { #{{{
768 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
772 sub linkpage ($) { #{{{
774 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
778 sub cgiurl (@) { #{{{
781 return $config{cgiurl}."?".
782 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
785 sub baseurl (;$) { #{{{
788 return "$config{url}/" if ! defined $page;
790 $page=htmlpage($page);
792 $page=~s/[^\/]+\//..\//g;
796 sub abs2rel ($$) { #{{{
797 # Work around very innefficient behavior in File::Spec if abs2rel
798 # is passed two relative paths. It's much faster if paths are
799 # absolute! (Debian bug #376658; fixed in debian unstable now)
804 my $ret=File::Spec->abs2rel($path, $base);
805 $ret=~s/^// if defined $ret;
809 sub displaytime ($;$) { #{{{
812 if (! defined $format) {
813 $format=$config{timeformat};
816 # strftime doesn't know about encodings, so make sure
817 # its output is properly treated as utf8
818 return decode_utf8(POSIX::strftime($format, localtime($time)));
821 sub beautify_urlpath ($) { #{{{
824 if ($config{usedirs}) {
825 $url =~ s!/index.$config{htmlext}$!/!;
828 # Ensure url is not an empty link, and
829 # if it's relative, make that explicit to avoid colon confusion.
837 sub urlto ($$;$) { #{{{
843 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
846 if (! $destsources{$to}) {
851 return $config{url}.beautify_urlpath("/".$to);
854 my $link = abs2rel($to, dirname(htmlpage($from)));
856 return beautify_urlpath($link);
859 sub htmllink ($$$;@) { #{{{
860 my $lpage=shift; # the page doing the linking
861 my $page=shift; # the page that will contain the link (different for inline)
868 if (! $opts{forcesubpage}) {
869 $bestlink=bestlink($lpage, $link);
872 $bestlink="$lpage/".lc($link);
876 if (defined $opts{linktext}) {
877 $linktext=$opts{linktext};
880 $linktext=pagetitle(basename($link));
883 return "<span class=\"selflink\">$linktext</span>"
884 if length $bestlink && $page eq $bestlink &&
885 ! defined $opts{anchor};
887 if (! $destsources{$bestlink}) {
888 $bestlink=htmlpage($bestlink);
890 if (! $destsources{$bestlink}) {
891 return $linktext unless length $config{cgiurl};
892 return "<span class=\"createlink\"><a href=\"".
898 "\" rel=\"nofollow\">?</a>$linktext</span>"
902 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
903 $bestlink=beautify_urlpath($bestlink);
905 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
906 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
909 if (defined $opts{anchor}) {
910 $bestlink.="#".$opts{anchor};
914 if (defined $opts{rel}) {
915 push @attrs, ' rel="'.$opts{rel}.'"';
917 if (defined $opts{class}) {
918 push @attrs, ' class="'.$opts{class}.'"';
921 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
924 sub userlink ($) { #{{{
927 my $oiduser=eval { openiduser($user) };
928 if (defined $oiduser) {
929 return "<a href=\"$user\">$oiduser</a>";
932 eval q{use CGI 'escapeHTML'};
935 return htmllink("", "", escapeHTML(
936 length $config{userdir} ? $config{userdir}."/".$user : $user
937 ), noimageinline => 1);
941 sub htmlize ($$$$) { #{{{
947 my $oneline = $content !~ /\n/;
949 if (exists $hooks{htmlize}{$type}) {
950 $content=$hooks{htmlize}{$type}{call}->(
956 error("htmlization of $type not supported");
959 run_hooks(sanitize => sub {
962 destpage => $destpage,
968 # hack to get rid of enclosing junk added by markdown
969 # and other htmlizers
971 $content=~s/<\/p>$//i;
978 sub linkify ($$$) { #{{{
983 run_hooks(linkify => sub {
986 destpage => $destpage,
995 our $preprocess_preview=0;
996 sub preprocess ($$$;$$) { #{{{
997 my $page=shift; # the page the data comes from
998 my $destpage=shift; # the page the data will appear in (different for inline)
1003 # Using local because it needs to be set within any nested calls
1005 local $preprocess_preview=$preview if defined $preview;
1012 if (length $escape) {
1013 return "[[$prefix$command $params]]";
1015 elsif (exists $hooks{preprocess}{$command}) {
1016 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1017 # Note: preserve order of params, some plugins may
1018 # consider it significant.
1020 while ($params =~ m{
1021 (?:([-\w]+)=)? # 1: named parameter key?
1023 """(.*?)""" # 2: triple-quoted value
1025 "([^"]+)" # 3: single-quoted value
1027 (\S+) # 4: unquoted value
1029 (?:\s+|$) # delimiter to next param
1039 elsif (defined $3) {
1042 elsif (defined $4) {
1047 push @params, $key, $val;
1050 push @params, $val, '';
1053 if ($preprocessing{$page}++ > 3) {
1054 # Avoid loops of preprocessed pages preprocessing
1055 # other pages that preprocess them, etc.
1056 #translators: The first parameter is a
1057 #translators: preprocessor directive name,
1058 #translators: the second a page name, the
1059 #translators: third a number.
1060 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
1061 $command, $page, $preprocessing{$page}).
1067 $hooks{preprocess}{$command}{call}->(
1070 destpage => $destpage,
1071 preview => $preprocess_preview,
1076 $ret="[[!$command <span class=\"error\">".
1077 gettext("Error").": $@"."</span>]]";
1081 # use void context during scan pass
1083 $hooks{preprocess}{$command}{call}->(
1086 destpage => $destpage,
1087 preview => $preprocess_preview,
1092 $preprocessing{$page}--;
1096 return "[[$prefix$command $params]]";
1101 if ($config{prefix_directives}) {
1104 \[\[(!) # directive open; 2: prefix
1105 ([-\w]+) # 3: command
1106 ( # 4: the parameters..
1107 \s+ # Must have space if parameters present
1109 (?:[-\w]+=)? # named parameter key?
1111 """.*?""" # triple-quoted value
1113 "[^"]+" # single-quoted value
1115 [^\s\]]+ # unquoted value
1117 \s* # whitespace or end
1120 *)? # 0 or more parameters
1121 \]\] # directive closed
1127 \[\[(!?) # directive open; 2: optional prefix
1128 ([-\w]+) # 3: command
1130 ( # 4: the parameters..
1132 (?:[-\w]+=)? # named parameter key?
1134 """.*?""" # triple-quoted value
1136 "[^"]+" # single-quoted value
1138 [^\s\]]+ # unquoted value
1140 \s* # whitespace or end
1143 *) # 0 or more parameters
1144 \]\] # directive closed
1148 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1152 sub filter ($$$) { #{{{
1157 run_hooks(filter => sub {
1158 $content=shift->(page => $page, destpage => $destpage,
1159 content => $content);
1165 sub indexlink () { #{{{
1166 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1171 sub lockwiki (;$) { #{{{
1172 my $wait=@_ ? shift : 1;
1173 # Take an exclusive lock on the wiki to prevent multiple concurrent
1174 # run issues. The lock will be dropped on program exit.
1175 if (! -d $config{wikistatedir}) {
1176 mkdir($config{wikistatedir});
1178 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1179 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1180 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1182 debug("wiki seems to be locked, waiting for lock");
1183 my $wait=600; # arbitrary, but don't hang forever to
1184 # prevent process pileup
1186 return if flock($wikilock, 2 | 4);
1189 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1198 sub unlockwiki () { #{{{
1199 return close($wikilock) if $wikilock;
1205 sub commit_hook_enabled () { #{{{
1206 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1207 error("cannot write to $config{wikistatedir}/commitlock: $!");
1208 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1209 close($commitlock) || error("failed closing commitlock: $!");
1212 close($commitlock) || error("failed closing commitlock: $!");
1216 sub disable_commit_hook () { #{{{
1217 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1218 error("cannot write to $config{wikistatedir}/commitlock: $!");
1219 if (! flock($commitlock, 2)) { # LOCK_EX
1220 error("failed to get commit lock");
1225 sub enable_commit_hook () { #{{{
1226 return close($commitlock) if $commitlock;
1230 sub loadindex () { #{{{
1231 %oldrenderedfiles=%pagectime=();
1232 if (! $config{rebuild}) {
1233 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1234 %destsources=%renderedfiles=%pagecase=%pagestate=();
1237 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1238 if (-e "$config{wikistatedir}/index") {
1239 system("ikiwiki-transition", "indexdb", $config{srcdir});
1240 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1246 my $ret=Storable::fd_retrieve($in);
1247 if (! defined $ret) {
1251 foreach my $src (keys %index) {
1252 my %d=%{$index{$src}};
1253 my $page=pagename($src);
1254 $pagectime{$page}=$d{ctime};
1255 if (! $config{rebuild}) {
1256 $pagesources{$page}=$src;
1257 $pagemtime{$page}=$d{mtime};
1258 $renderedfiles{$page}=$d{dest};
1259 if (exists $d{links} && ref $d{links}) {
1260 $links{$page}=$d{links};
1261 $oldlinks{$page}=[@{$d{links}}];
1263 if (exists $d{depends}) {
1264 $depends{$page}=$d{depends};
1266 if (exists $d{state}) {
1267 $pagestate{$page}=$d{state};
1270 $oldrenderedfiles{$page}=[@{$d{dest}}];
1272 foreach my $page (keys %pagesources) {
1273 $pagecase{lc $page}=$page;
1275 foreach my $page (keys %renderedfiles) {
1276 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1281 sub saveindex () { #{{{
1282 run_hooks(savestate => sub { shift->() });
1285 foreach my $type (keys %hooks) {
1286 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1288 my @hookids=keys %hookids;
1290 if (! -d $config{wikistatedir}) {
1291 mkdir($config{wikistatedir});
1293 my $newfile="$config{wikistatedir}/indexdb.new";
1294 my $cleanup = sub { unlink($newfile) };
1295 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1297 foreach my $page (keys %pagemtime) {
1298 next unless $pagemtime{$page};
1299 my $src=$pagesources{$page};
1302 ctime => $pagectime{$page},
1303 mtime => $pagemtime{$page},
1304 dest => $renderedfiles{$page},
1305 links => $links{$page},
1308 if (exists $depends{$page}) {
1309 $index{$src}{depends} = $depends{$page};
1312 if (exists $pagestate{$page}) {
1313 foreach my $id (@hookids) {
1314 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1315 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1320 my $ret=Storable::nstore_fd(\%index, $out);
1321 return if ! defined $ret || ! $ret;
1322 close $out || error("failed saving to $newfile: $!", $cleanup);
1323 rename($newfile, "$config{wikistatedir}/indexdb") ||
1324 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1329 sub template_file ($) { #{{{
1332 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1333 return "$dir/$template" if -e "$dir/$template";
1338 sub template_params (@) { #{{{
1339 my $filename=template_file(shift);
1341 if (! defined $filename) {
1342 return if wantarray;
1348 my $text_ref = shift;
1349 ${$text_ref} = decode_utf8(${$text_ref});
1351 filename => $filename,
1352 loop_context_vars => 1,
1353 die_on_bad_params => 0,
1356 return wantarray ? @ret : {@ret};
1359 sub template ($;@) { #{{{
1360 require HTML::Template;
1361 return HTML::Template->new(template_params(@_));
1364 sub misctemplate ($$;@) { #{{{
1368 my $template=template("misc.tmpl");
1371 indexlink => indexlink(),
1372 wikiname => $config{wikiname},
1373 pagebody => $pagebody,
1374 baseurl => baseurl(),
1377 run_hooks(pagetemplate => sub {
1378 shift->(page => "", destpage => "", template => $template);
1380 return $template->output;
1383 sub hook (@) { # {{{
1386 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1387 error 'hook requires type, call, and id parameters';
1390 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1392 $hooks{$param{type}}{$param{id}}=\%param;
1396 sub run_hooks ($$) { # {{{
1397 # Calls the given sub for each hook of the given type,
1398 # passing it the hook function to call.
1402 if (exists $hooks{$type}) {
1404 foreach my $id (keys %{$hooks{$type}}) {
1405 if ($hooks{$type}{$id}{last}) {
1406 push @deferred, $id;
1409 $sub->($hooks{$type}{$id}{call});
1411 foreach my $id (@deferred) {
1412 $sub->($hooks{$type}{$id}{call});
1419 sub globlist_to_pagespec ($) { #{{{
1420 my @globlist=split(' ', shift);
1423 foreach my $glob (@globlist) {
1424 if ($glob=~/^!(.*)/) {
1432 my $spec=join(' or ', @spec);
1434 my $skip=join(' and ', @skip);
1436 $spec="$skip and ($spec)";
1445 sub is_globlist ($) { #{{{
1447 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1450 sub safequote ($) { #{{{
1456 sub add_depends ($$) { #{{{
1460 return unless pagespec_valid($pagespec);
1462 if (! exists $depends{$page}) {
1463 $depends{$page}=$pagespec;
1466 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1472 sub file_pruned ($$) { #{{{
1474 my $file=File::Spec->canonpath(shift);
1475 my $base=File::Spec->canonpath(shift);
1476 $file =~ s#^\Q$base\E/+##;
1478 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1479 return $file =~ m/$regexp/ && $file ne $base;
1483 # Only use gettext in the rare cases it's needed.
1484 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1485 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1486 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1487 if (! $gettext_obj) {
1488 $gettext_obj=eval q{
1489 use Locale::gettext q{textdomain};
1490 Locale::gettext->domain('ikiwiki')
1498 return $gettext_obj->get(shift);
1505 sub yesno ($) { #{{{
1508 return (defined $val && lc($val) eq gettext("yes"));
1511 sub pagespec_merge ($$) { #{{{
1515 return $a if $a eq $b;
1517 # Support for old-style GlobLists.
1518 if (is_globlist($a)) {
1519 $a=globlist_to_pagespec($a);
1521 if (is_globlist($b)) {
1522 $b=globlist_to_pagespec($b);
1525 return "($a) or ($b)";
1528 sub pagespec_translate ($) { #{{{
1531 # Support for old-style GlobLists.
1532 if (is_globlist($spec)) {
1533 $spec=globlist_to_pagespec($spec);
1536 # Convert spec to perl code.
1539 \s* # ignore whitespace
1540 ( # 1: match a single word
1547 \w+\([^\)]*\) # command(params)
1549 [^\s()]+ # any other text
1551 \s* # ignore whitespace
1554 if (lc $word eq 'and') {
1557 elsif (lc $word eq 'or') {
1560 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1563 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1564 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1565 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1572 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1576 if (! length $code) {
1581 return eval 'sub { my $page=shift; '.$code.' }';
1584 sub pagespec_match ($$;@) { #{{{
1589 # Backwards compatability with old calling convention.
1591 unshift @params, 'location';
1594 my $sub=pagespec_translate($spec);
1595 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1596 return $sub->($page, @params);
1599 sub pagespec_valid ($) { #{{{
1602 my $sub=pagespec_translate($spec);
1606 sub glob2re ($) { #{{{
1607 my $re=quotemeta(shift);
1613 package IkiWiki::FailReason;
1616 '""' => sub { ${$_[0]} },
1618 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1625 return bless \$value, $class;
1628 package IkiWiki::SuccessReason;
1631 '""' => sub { ${$_[0]} },
1633 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1640 return bless \$value, $class;
1643 package IkiWiki::PageSpec;
1645 sub match_glob ($$;@) { #{{{
1650 my $from=exists $params{location} ? $params{location} : '';
1653 if ($glob =~ m!^\./!) {
1654 $from=~s#/?[^/]+$##;
1656 $glob="$from/$glob" if length $from;
1659 my $regexp=IkiWiki::glob2re($glob);
1660 if ($page=~/^$regexp$/i) {
1661 if (! IkiWiki::isinternal($page) || $params{internal}) {
1662 return IkiWiki::SuccessReason->new("$glob matches $page");
1665 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1669 return IkiWiki::FailReason->new("$glob does not match $page");
1673 sub match_internal ($$;@) { #{{{
1674 return match_glob($_[0], $_[1], @_, internal => 1)
1677 sub match_link ($$;@) { #{{{
1682 my $from=exists $params{location} ? $params{location} : '';
1685 if ($link =~ m!^\.! && defined $from) {
1686 $from=~s#/?[^/]+$##;
1688 $link="$from/$link" if length $from;
1691 my $links = $IkiWiki::links{$page};
1692 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1693 my $bestlink = IkiWiki::bestlink($from, $link);
1694 foreach my $p (@{$links}) {
1695 if (length $bestlink) {
1696 return IkiWiki::SuccessReason->new("$page links to $link")
1697 if $bestlink eq IkiWiki::bestlink($page, $p);
1700 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1701 if match_glob($p, $link, %params);
1704 return IkiWiki::FailReason->new("$page does not link to $link");
1707 sub match_backlink ($$;@) { #{{{
1708 return match_link($_[1], $_[0], @_);
1711 sub match_created_before ($$;@) { #{{{
1715 if (exists $IkiWiki::pagectime{$testpage}) {
1716 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1717 return IkiWiki::SuccessReason->new("$page created before $testpage");
1720 return IkiWiki::FailReason->new("$page not created before $testpage");
1724 return IkiWiki::FailReason->new("$testpage has no ctime");
1728 sub match_created_after ($$;@) { #{{{
1732 if (exists $IkiWiki::pagectime{$testpage}) {
1733 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1734 return IkiWiki::SuccessReason->new("$page created after $testpage");
1737 return IkiWiki::FailReason->new("$page not created after $testpage");
1741 return IkiWiki::FailReason->new("$testpage has no ctime");
1745 sub match_creation_day ($$;@) { #{{{
1746 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1747 return IkiWiki::SuccessReason->new('creation_day matched');
1750 return IkiWiki::FailReason->new('creation_day did not match');
1754 sub match_creation_month ($$;@) { #{{{
1755 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1756 return IkiWiki::SuccessReason->new('creation_month matched');
1759 return IkiWiki::FailReason->new('creation_month did not match');
1763 sub match_creation_year ($$;@) { #{{{
1764 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1765 return IkiWiki::SuccessReason->new('creation_year matched');
1768 return IkiWiki::FailReason->new('creation_year did not match');