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 # TODO should be set per-rcs to allow different
100 # examples and descriptions
103 description => "XXX",
112 description => "XXX",
119 description => "enable Discussion pages?",
127 description => "path inside svn repo where wiki is located",
128 safe => 0, # could expose/overwrite data
131 gitorigin_branch => {
134 description => "the git origin to pull from",
135 safe => 0, # paranoia
138 gitmaster_branch => {
141 description => "the git master branch",
142 safe => 0, # paranoia
148 description => "definitions of wrappers to generate",
155 description => "wrapper filename",
162 description => "mode of wrapper file",
168 default => "$installdir/share/ikiwiki/templates",
169 description => "location of template files",
175 default => "$installdir/share/ikiwiki/basewiki",
176 description => "base wiki source location",
183 description => "additional underlays to use",
190 description => "display verbose messages when building?",
197 description => "log to syslog?",
204 description => "create output files named page/index.html?",
205 safe => 0, # changing requires manual transition
208 prefix_directives => {
211 description => "use '!'-prefixed preprocessor directives?",
212 safe => 0, # changing requires manual transition
218 description => "extension to use for new pages",
219 safe => 0, # not sanitized
225 description => "extension to use for html files",
226 safe => 0, # not sanitized
232 description => "strftime format string to display date",
239 example => "en_US.UTF-8",
240 description => "UTF-8 locale to use",
247 description => "only send cookies over SSL connections?",
255 description => "put user pages below specified page",
262 description => "how many backlinks to show before hiding excess (0 to show all)",
269 description => "attempt to hardlink source files? (optimisation for large files)",
270 safe => 0, # paranoia
278 description => "regexp of source files to ignore",
282 wiki_file_prune_regexps => {
284 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
285 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
286 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
289 description => "regexps of source files to ignore",
293 wiki_file_regexp => {
295 default => qr/(^[-[:alnum:]_.:\/+]+$)/,
296 description => "regexp of legal source files",
300 web_commit_regexp => {
302 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
303 description => "regexp to parse web commits from logs",
310 description => "run as a cgi",
314 cgi_disable_uploads => {
317 description => "whether CGI should accept file uploads",
324 description => "run as a post-commit hook",
331 description => "running in rebuild mode",
338 description => "running in refresh mode",
345 description => "running in getctime mode",
352 description => "running in w3mmode",
359 description => "setup file to read",
365 default => [qw{mdwn link inline htmlscrubber passwordauth
366 openid signinedit lockedit conditional
367 recentchanges parentlinks}],
368 description => "plugins to enable by default",
375 description => "plugins to add to the default configuration",
382 description => "plugins to disable",
389 example => "$ENV{HOME}/.ikiwiki/",
390 description => "extra library and plugin directory",
396 sub defaultconfig () { #{{{
399 foreach my $key (keys %s) {
400 push @ret, $key, $s{$key}->{default};
406 sub checkconfig () { #{{{
407 # locale stuff; avoid LC_ALL since it overrides everything
408 if (defined $ENV{LC_ALL}) {
409 $ENV{LANG} = $ENV{LC_ALL};
412 if (defined $config{locale}) {
413 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
414 $ENV{LANG}=$config{locale};
419 if (ref $config{ENV} eq 'HASH') {
420 foreach my $val (keys %{$config{ENV}}) {
421 $ENV{$val}=$config{ENV}{$val};
425 if ($config{w3mmode}) {
426 eval q{use Cwd q{abs_path}};
428 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
429 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
430 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
431 unless $config{cgiurl} =~ m!file:///!;
432 $config{url}="file://".$config{destdir};
435 if ($config{cgi} && ! length $config{url}) {
436 error(gettext("Must specify url to wiki with --url when using --cgi"));
439 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
440 unless exists $config{wikistatedir};
443 eval qq{use IkiWiki::Rcs::$config{rcs}};
445 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
449 require IkiWiki::Rcs::Stub;
452 if (exists $config{umask}) {
453 umask(possibly_foolish_untaint($config{umask}));
456 run_hooks(checkconfig => sub { shift->() });
461 sub loadplugins () { #{{{
462 if (defined $config{libdir}) {
463 unshift @INC, possibly_foolish_untaint($config{libdir});
466 loadplugin($_) foreach @{$config{default_plugins}}, @{$config{add_plugins}};
468 run_hooks(getopt => sub { shift->() });
469 if (grep /^-/, @ARGV) {
470 print STDERR "Unknown option: $_\n"
471 foreach grep /^-/, @ARGV;
478 sub loadplugin ($) { #{{{
481 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
483 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
484 "$installdir/lib/ikiwiki") {
485 if (defined $dir && -x "$dir/plugins/$plugin") {
486 require IkiWiki::Plugin::external;
487 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
492 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
495 error("Failed to load plugin $mod: $@");
500 sub error ($;$) { #{{{
503 log_message('err' => $message) if $config{syslog};
504 if (defined $cleaner) {
511 return unless $config{verbose};
512 return log_message(debug => @_);
516 sub log_message ($$) { #{{{
519 if ($config{syslog}) {
522 Sys::Syslog::setlogsock('unix');
523 Sys::Syslog::openlog('ikiwiki', '', 'user');
527 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
530 elsif (! $config{cgi}) {
534 return print STDERR "@_\n";
538 sub possibly_foolish_untaint ($) { #{{{
540 my ($untainted)=$tainted=~/(.*)/s;
544 sub basename ($) { #{{{
551 sub dirname ($) { #{{{
558 sub pagetype ($) { #{{{
561 if ($page =~ /\.([^.]+)$/) {
562 return $1 if exists $hooks{htmlize}{$1};
567 sub isinternal ($) { #{{{
569 return exists $pagesources{$page} &&
570 $pagesources{$page} =~ /\._([^.]+)$/;
573 sub pagename ($) { #{{{
576 my $type=pagetype($file);
578 $page=~s/\Q.$type\E*$// if defined $type;
582 sub targetpage ($$) { #{{{
586 if (! $config{usedirs} || $page =~ /^index$/ ) {
587 return $page.".".$ext;
589 return $page."/index.".$ext;
593 sub htmlpage ($) { #{{{
596 return targetpage($page, $config{htmlext});
599 sub srcfile_stat { #{{{
603 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
604 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
605 return "$dir/$file", stat(_) if -e "$dir/$file";
607 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
611 sub srcfile ($;$) { #{{{
612 return (srcfile_stat(@_))[0];
615 sub add_underlay ($) { #{{{
619 unshift @{$config{underlaydirs}}, $dir;
622 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
628 sub readfile ($;$$) { #{{{
634 error("cannot read a symlink ($file)");
638 open (my $in, "<", $file) || error("failed to read $file: $!");
639 binmode($in) if ($binary);
640 return \*$in if $wantfd;
642 close $in || error("failed to read $file: $!");
646 sub prep_writefile ($$) { #{{{
651 while (length $test) {
652 if (-l "$destdir/$test") {
653 error("cannot write to a symlink ($test)");
655 $test=dirname($test);
658 my $dir=dirname("$destdir/$file");
661 foreach my $s (split(m!/+!, $dir)) {
664 mkdir($d) || error("failed to create directory $d: $!");
672 sub writefile ($$$;$$) { #{{{
673 my $file=shift; # can include subdirs
674 my $destdir=shift; # directory to put file in
679 prep_writefile($file, $destdir);
681 my $newfile="$destdir/$file.ikiwiki-new";
683 error("cannot write to a symlink ($newfile)");
686 my $cleanup = sub { unlink($newfile) };
687 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
688 binmode($out) if ($binary);
690 $writer->(\*$out, $cleanup);
693 print $out $content or error("failed writing to $newfile: $!", $cleanup);
695 close $out || error("failed saving $newfile: $!", $cleanup);
696 rename($newfile, "$destdir/$file") ||
697 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
703 sub will_render ($$;$) { #{{{
708 # Important security check.
709 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
710 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
711 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
714 if (! $clear || $cleared{$page}) {
715 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
718 foreach my $old (@{$renderedfiles{$page}}) {
719 delete $destsources{$old};
721 $renderedfiles{$page}=[$dest];
724 $destsources{$dest}=$page;
729 sub bestlink ($$) { #{{{
734 if ($link=~s/^\/+//) {
742 $l.="/" if length $l;
745 if (exists $links{$l}) {
748 elsif (exists $pagecase{lc $l}) {
749 return $pagecase{lc $l};
751 } while $cwd=~s!/?[^/]+$!!;
753 if (length $config{userdir}) {
754 my $l = "$config{userdir}/".lc($link);
755 if (exists $links{$l}) {
758 elsif (exists $pagecase{lc $l}) {
759 return $pagecase{lc $l};
763 #print STDERR "warning: page $page, broken link: $link\n";
767 sub isinlinableimage ($) { #{{{
770 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
773 sub pagetitle ($;$) { #{{{
778 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
781 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
787 sub titlepage ($) { #{{{
789 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
793 sub linkpage ($) { #{{{
795 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
799 sub cgiurl (@) { #{{{
802 return $config{cgiurl}."?".
803 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
806 sub baseurl (;$) { #{{{
809 return "$config{url}/" if ! defined $page;
811 $page=htmlpage($page);
813 $page=~s/[^\/]+\//..\//g;
817 sub abs2rel ($$) { #{{{
818 # Work around very innefficient behavior in File::Spec if abs2rel
819 # is passed two relative paths. It's much faster if paths are
820 # absolute! (Debian bug #376658; fixed in debian unstable now)
825 my $ret=File::Spec->abs2rel($path, $base);
826 $ret=~s/^// if defined $ret;
830 sub displaytime ($;$) { #{{{
833 if (! defined $format) {
834 $format=$config{timeformat};
837 # strftime doesn't know about encodings, so make sure
838 # its output is properly treated as utf8
839 return decode_utf8(POSIX::strftime($format, localtime($time)));
842 sub beautify_urlpath ($) { #{{{
845 if ($config{usedirs}) {
846 $url =~ s!/index.$config{htmlext}$!/!;
849 # Ensure url is not an empty link, and
850 # if it's relative, make that explicit to avoid colon confusion.
858 sub urlto ($$;$) { #{{{
864 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
867 if (! $destsources{$to}) {
872 return $config{url}.beautify_urlpath("/".$to);
875 my $link = abs2rel($to, dirname(htmlpage($from)));
877 return beautify_urlpath($link);
880 sub htmllink ($$$;@) { #{{{
881 my $lpage=shift; # the page doing the linking
882 my $page=shift; # the page that will contain the link (different for inline)
889 if (! $opts{forcesubpage}) {
890 $bestlink=bestlink($lpage, $link);
893 $bestlink="$lpage/".lc($link);
897 if (defined $opts{linktext}) {
898 $linktext=$opts{linktext};
901 $linktext=pagetitle(basename($link));
904 return "<span class=\"selflink\">$linktext</span>"
905 if length $bestlink && $page eq $bestlink &&
906 ! defined $opts{anchor};
908 if (! $destsources{$bestlink}) {
909 $bestlink=htmlpage($bestlink);
911 if (! $destsources{$bestlink}) {
912 return $linktext unless length $config{cgiurl};
913 return "<span class=\"createlink\"><a href=\"".
919 "\" rel=\"nofollow\">?</a>$linktext</span>"
923 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
924 $bestlink=beautify_urlpath($bestlink);
926 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
927 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
930 if (defined $opts{anchor}) {
931 $bestlink.="#".$opts{anchor};
935 if (defined $opts{rel}) {
936 push @attrs, ' rel="'.$opts{rel}.'"';
938 if (defined $opts{class}) {
939 push @attrs, ' class="'.$opts{class}.'"';
942 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
945 sub userlink ($) { #{{{
948 my $oiduser=eval { openiduser($user) };
949 if (defined $oiduser) {
950 return "<a href=\"$user\">$oiduser</a>";
953 eval q{use CGI 'escapeHTML'};
956 return htmllink("", "", escapeHTML(
957 length $config{userdir} ? $config{userdir}."/".$user : $user
958 ), noimageinline => 1);
962 sub htmlize ($$$$) { #{{{
968 my $oneline = $content !~ /\n/;
970 if (exists $hooks{htmlize}{$type}) {
971 $content=$hooks{htmlize}{$type}{call}->(
977 error("htmlization of $type not supported");
980 run_hooks(sanitize => sub {
983 destpage => $destpage,
989 # hack to get rid of enclosing junk added by markdown
990 # and other htmlizers
992 $content=~s/<\/p>$//i;
999 sub linkify ($$$) { #{{{
1004 run_hooks(linkify => sub {
1007 destpage => $destpage,
1008 content => $content,
1016 our $preprocess_preview=0;
1017 sub preprocess ($$$;$$) { #{{{
1018 my $page=shift; # the page the data comes from
1019 my $destpage=shift; # the page the data will appear in (different for inline)
1024 # Using local because it needs to be set within any nested calls
1026 local $preprocess_preview=$preview if defined $preview;
1033 if (length $escape) {
1034 return "[[$prefix$command $params]]";
1036 elsif (exists $hooks{preprocess}{$command}) {
1037 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1038 # Note: preserve order of params, some plugins may
1039 # consider it significant.
1041 while ($params =~ m{
1042 (?:([-\w]+)=)? # 1: named parameter key?
1044 """(.*?)""" # 2: triple-quoted value
1046 "([^"]+)" # 3: single-quoted value
1048 (\S+) # 4: unquoted value
1050 (?:\s+|$) # delimiter to next param
1060 elsif (defined $3) {
1063 elsif (defined $4) {
1068 push @params, $key, $val;
1071 push @params, $val, '';
1074 if ($preprocessing{$page}++ > 3) {
1075 # Avoid loops of preprocessed pages preprocessing
1076 # other pages that preprocess them, etc.
1077 #translators: The first parameter is a
1078 #translators: preprocessor directive name,
1079 #translators: the second a page name, the
1080 #translators: third a number.
1081 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
1082 $command, $page, $preprocessing{$page}).
1088 $hooks{preprocess}{$command}{call}->(
1091 destpage => $destpage,
1092 preview => $preprocess_preview,
1097 $ret="[[!$command <span class=\"error\">".
1098 gettext("Error").": $@"."</span>]]";
1102 # use void context during scan pass
1104 $hooks{preprocess}{$command}{call}->(
1107 destpage => $destpage,
1108 preview => $preprocess_preview,
1113 $preprocessing{$page}--;
1117 return "[[$prefix$command $params]]";
1122 if ($config{prefix_directives}) {
1125 \[\[(!) # directive open; 2: prefix
1126 ([-\w]+) # 3: command
1127 ( # 4: the parameters..
1128 \s+ # Must have space if parameters present
1130 (?:[-\w]+=)? # named parameter key?
1132 """.*?""" # triple-quoted value
1134 "[^"]+" # single-quoted value
1136 [^\s\]]+ # unquoted value
1138 \s* # whitespace or end
1141 *)? # 0 or more parameters
1142 \]\] # directive closed
1148 \[\[(!?) # directive open; 2: optional prefix
1149 ([-\w]+) # 3: command
1151 ( # 4: the parameters..
1153 (?:[-\w]+=)? # named parameter key?
1155 """.*?""" # triple-quoted value
1157 "[^"]+" # single-quoted value
1159 [^\s\]]+ # unquoted value
1161 \s* # whitespace or end
1164 *) # 0 or more parameters
1165 \]\] # directive closed
1169 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1173 sub filter ($$$) { #{{{
1178 run_hooks(filter => sub {
1179 $content=shift->(page => $page, destpage => $destpage,
1180 content => $content);
1186 sub indexlink () { #{{{
1187 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1192 sub lockwiki (;$) { #{{{
1193 my $wait=@_ ? shift : 1;
1194 # Take an exclusive lock on the wiki to prevent multiple concurrent
1195 # run issues. The lock will be dropped on program exit.
1196 if (! -d $config{wikistatedir}) {
1197 mkdir($config{wikistatedir});
1199 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1200 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1201 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1203 debug("wiki seems to be locked, waiting for lock");
1204 my $wait=600; # arbitrary, but don't hang forever to
1205 # prevent process pileup
1207 return if flock($wikilock, 2 | 4);
1210 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1219 sub unlockwiki () { #{{{
1220 return close($wikilock) if $wikilock;
1226 sub commit_hook_enabled () { #{{{
1227 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1228 error("cannot write to $config{wikistatedir}/commitlock: $!");
1229 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1230 close($commitlock) || error("failed closing commitlock: $!");
1233 close($commitlock) || error("failed closing commitlock: $!");
1237 sub disable_commit_hook () { #{{{
1238 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1239 error("cannot write to $config{wikistatedir}/commitlock: $!");
1240 if (! flock($commitlock, 2)) { # LOCK_EX
1241 error("failed to get commit lock");
1246 sub enable_commit_hook () { #{{{
1247 return close($commitlock) if $commitlock;
1251 sub loadindex () { #{{{
1252 %oldrenderedfiles=%pagectime=();
1253 if (! $config{rebuild}) {
1254 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1255 %destsources=%renderedfiles=%pagecase=%pagestate=();
1258 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1259 if (-e "$config{wikistatedir}/index") {
1260 system("ikiwiki-transition", "indexdb", $config{srcdir});
1261 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1267 my $ret=Storable::fd_retrieve($in);
1268 if (! defined $ret) {
1272 foreach my $src (keys %index) {
1273 my %d=%{$index{$src}};
1274 my $page=pagename($src);
1275 $pagectime{$page}=$d{ctime};
1276 if (! $config{rebuild}) {
1277 $pagesources{$page}=$src;
1278 $pagemtime{$page}=$d{mtime};
1279 $renderedfiles{$page}=$d{dest};
1280 if (exists $d{links} && ref $d{links}) {
1281 $links{$page}=$d{links};
1282 $oldlinks{$page}=[@{$d{links}}];
1284 if (exists $d{depends}) {
1285 $depends{$page}=$d{depends};
1287 if (exists $d{state}) {
1288 $pagestate{$page}=$d{state};
1291 $oldrenderedfiles{$page}=[@{$d{dest}}];
1293 foreach my $page (keys %pagesources) {
1294 $pagecase{lc $page}=$page;
1296 foreach my $page (keys %renderedfiles) {
1297 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1302 sub saveindex () { #{{{
1303 run_hooks(savestate => sub { shift->() });
1306 foreach my $type (keys %hooks) {
1307 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1309 my @hookids=keys %hookids;
1311 if (! -d $config{wikistatedir}) {
1312 mkdir($config{wikistatedir});
1314 my $newfile="$config{wikistatedir}/indexdb.new";
1315 my $cleanup = sub { unlink($newfile) };
1316 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1318 foreach my $page (keys %pagemtime) {
1319 next unless $pagemtime{$page};
1320 my $src=$pagesources{$page};
1323 ctime => $pagectime{$page},
1324 mtime => $pagemtime{$page},
1325 dest => $renderedfiles{$page},
1326 links => $links{$page},
1329 if (exists $depends{$page}) {
1330 $index{$src}{depends} = $depends{$page};
1333 if (exists $pagestate{$page}) {
1334 foreach my $id (@hookids) {
1335 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1336 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1341 my $ret=Storable::nstore_fd(\%index, $out);
1342 return if ! defined $ret || ! $ret;
1343 close $out || error("failed saving to $newfile: $!", $cleanup);
1344 rename($newfile, "$config{wikistatedir}/indexdb") ||
1345 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1350 sub template_file ($) { #{{{
1353 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1354 return "$dir/$template" if -e "$dir/$template";
1359 sub template_params (@) { #{{{
1360 my $filename=template_file(shift);
1362 if (! defined $filename) {
1363 return if wantarray;
1369 my $text_ref = shift;
1370 ${$text_ref} = decode_utf8(${$text_ref});
1372 filename => $filename,
1373 loop_context_vars => 1,
1374 die_on_bad_params => 0,
1377 return wantarray ? @ret : {@ret};
1380 sub template ($;@) { #{{{
1381 require HTML::Template;
1382 return HTML::Template->new(template_params(@_));
1385 sub misctemplate ($$;@) { #{{{
1389 my $template=template("misc.tmpl");
1392 indexlink => indexlink(),
1393 wikiname => $config{wikiname},
1394 pagebody => $pagebody,
1395 baseurl => baseurl(),
1398 run_hooks(pagetemplate => sub {
1399 shift->(page => "", destpage => "", template => $template);
1401 return $template->output;
1404 sub hook (@) { # {{{
1407 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1408 error 'hook requires type, call, and id parameters';
1411 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1413 $hooks{$param{type}}{$param{id}}=\%param;
1417 sub run_hooks ($$) { # {{{
1418 # Calls the given sub for each hook of the given type,
1419 # passing it the hook function to call.
1423 if (exists $hooks{$type}) {
1425 foreach my $id (keys %{$hooks{$type}}) {
1426 if ($hooks{$type}{$id}{last}) {
1427 push @deferred, $id;
1430 $sub->($hooks{$type}{$id}{call});
1432 foreach my $id (@deferred) {
1433 $sub->($hooks{$type}{$id}{call});
1440 sub globlist_to_pagespec ($) { #{{{
1441 my @globlist=split(' ', shift);
1444 foreach my $glob (@globlist) {
1445 if ($glob=~/^!(.*)/) {
1453 my $spec=join(' or ', @spec);
1455 my $skip=join(' and ', @skip);
1457 $spec="$skip and ($spec)";
1466 sub is_globlist ($) { #{{{
1468 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1471 sub safequote ($) { #{{{
1477 sub add_depends ($$) { #{{{
1481 return unless pagespec_valid($pagespec);
1483 if (! exists $depends{$page}) {
1484 $depends{$page}=$pagespec;
1487 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1493 sub file_pruned ($$) { #{{{
1495 my $file=File::Spec->canonpath(shift);
1496 my $base=File::Spec->canonpath(shift);
1497 $file =~ s#^\Q$base\E/+##;
1499 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1500 return $file =~ m/$regexp/ && $file ne $base;
1504 # Only use gettext in the rare cases it's needed.
1505 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1506 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1507 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1508 if (! $gettext_obj) {
1509 $gettext_obj=eval q{
1510 use Locale::gettext q{textdomain};
1511 Locale::gettext->domain('ikiwiki')
1519 return $gettext_obj->get(shift);
1526 sub yesno ($) { #{{{
1529 return (defined $val && lc($val) eq gettext("yes"));
1532 sub pagespec_merge ($$) { #{{{
1536 return $a if $a eq $b;
1538 # Support for old-style GlobLists.
1539 if (is_globlist($a)) {
1540 $a=globlist_to_pagespec($a);
1542 if (is_globlist($b)) {
1543 $b=globlist_to_pagespec($b);
1546 return "($a) or ($b)";
1549 sub pagespec_translate ($) { #{{{
1552 # Support for old-style GlobLists.
1553 if (is_globlist($spec)) {
1554 $spec=globlist_to_pagespec($spec);
1557 # Convert spec to perl code.
1560 \s* # ignore whitespace
1561 ( # 1: match a single word
1568 \w+\([^\)]*\) # command(params)
1570 [^\s()]+ # any other text
1572 \s* # ignore whitespace
1575 if (lc $word eq 'and') {
1578 elsif (lc $word eq 'or') {
1581 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1584 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1585 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1586 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1593 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1597 if (! length $code) {
1602 return eval 'sub { my $page=shift; '.$code.' }';
1605 sub pagespec_match ($$;@) { #{{{
1610 # Backwards compatability with old calling convention.
1612 unshift @params, 'location';
1615 my $sub=pagespec_translate($spec);
1616 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1617 return $sub->($page, @params);
1620 sub pagespec_valid ($) { #{{{
1623 my $sub=pagespec_translate($spec);
1627 sub glob2re ($) { #{{{
1628 my $re=quotemeta(shift);
1634 package IkiWiki::FailReason;
1637 '""' => sub { ${$_[0]} },
1639 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1646 return bless \$value, $class;
1649 package IkiWiki::SuccessReason;
1652 '""' => sub { ${$_[0]} },
1654 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1661 return bless \$value, $class;
1664 package IkiWiki::PageSpec;
1666 sub match_glob ($$;@) { #{{{
1671 my $from=exists $params{location} ? $params{location} : '';
1674 if ($glob =~ m!^\./!) {
1675 $from=~s#/?[^/]+$##;
1677 $glob="$from/$glob" if length $from;
1680 my $regexp=IkiWiki::glob2re($glob);
1681 if ($page=~/^$regexp$/i) {
1682 if (! IkiWiki::isinternal($page) || $params{internal}) {
1683 return IkiWiki::SuccessReason->new("$glob matches $page");
1686 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1690 return IkiWiki::FailReason->new("$glob does not match $page");
1694 sub match_internal ($$;@) { #{{{
1695 return match_glob($_[0], $_[1], @_, internal => 1)
1698 sub match_link ($$;@) { #{{{
1703 my $from=exists $params{location} ? $params{location} : '';
1706 if ($link =~ m!^\.! && defined $from) {
1707 $from=~s#/?[^/]+$##;
1709 $link="$from/$link" if length $from;
1712 my $links = $IkiWiki::links{$page};
1713 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1714 my $bestlink = IkiWiki::bestlink($from, $link);
1715 foreach my $p (@{$links}) {
1716 if (length $bestlink) {
1717 return IkiWiki::SuccessReason->new("$page links to $link")
1718 if $bestlink eq IkiWiki::bestlink($page, $p);
1721 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1722 if match_glob($p, $link, %params);
1725 return IkiWiki::FailReason->new("$page does not link to $link");
1728 sub match_backlink ($$;@) { #{{{
1729 return match_link($_[1], $_[0], @_);
1732 sub match_created_before ($$;@) { #{{{
1736 if (exists $IkiWiki::pagectime{$testpage}) {
1737 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1738 return IkiWiki::SuccessReason->new("$page created before $testpage");
1741 return IkiWiki::FailReason->new("$page not created before $testpage");
1745 return IkiWiki::FailReason->new("$testpage has no ctime");
1749 sub match_created_after ($$;@) { #{{{
1753 if (exists $IkiWiki::pagectime{$testpage}) {
1754 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1755 return IkiWiki::SuccessReason->new("$page created after $testpage");
1758 return IkiWiki::FailReason->new("$page not created after $testpage");
1762 return IkiWiki::FailReason->new("$testpage has no ctime");
1766 sub match_creation_day ($$;@) { #{{{
1767 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1768 return IkiWiki::SuccessReason->new('creation_day matched');
1771 return IkiWiki::FailReason->new('creation_day did not match');
1775 sub match_creation_month ($$;@) { #{{{
1776 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1777 return IkiWiki::SuccessReason->new('creation_month matched');
1780 return IkiWiki::FailReason->new('creation_month did not match');
1784 sub match_creation_year ($$;@) { #{{{
1785 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1786 return IkiWiki::SuccessReason->new('creation_year matched');
1789 return IkiWiki::FailReason->new('creation_year did not match');