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
259 description => "force ikiwiki to use a particular umask",
260 safe => 0, # paranoia
266 example => "$ENV{HOME}/.ikiwiki/",
267 description => "extra library and plugin directory",
268 safe => 0, # directory
274 description => "environment variables",
275 safe => 0, # paranoia
282 description => "regexp of source files to ignore",
286 wiki_file_prune_regexps => {
288 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
289 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
290 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
293 description => "regexps of source files to ignore",
297 wiki_file_regexp => {
299 default => qr/(^[-[:alnum:]_.:\/+]+$)/,
300 description => "regexp of legal source files",
304 web_commit_regexp => {
306 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
307 description => "regexp to parse web commits from logs",
314 description => "run as a cgi",
318 cgi_disable_uploads => {
321 description => "whether CGI should accept file uploads",
328 description => "run as a post-commit hook",
335 description => "running in rebuild mode",
342 description => "running in refresh mode",
349 description => "running in getctime mode",
356 description => "running in w3mmode",
363 description => "setup file to read",
369 sub defaultconfig () { #{{{
372 foreach my $key (keys %s) {
373 push @ret, $key, $s{$key}->{default};
379 sub checkconfig () { #{{{
380 # locale stuff; avoid LC_ALL since it overrides everything
381 if (defined $ENV{LC_ALL}) {
382 $ENV{LANG} = $ENV{LC_ALL};
385 if (defined $config{locale}) {
386 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
387 $ENV{LANG}=$config{locale};
392 if (ref $config{ENV} eq 'HASH') {
393 foreach my $val (keys %{$config{ENV}}) {
394 $ENV{$val}=$config{ENV}{$val};
398 if ($config{w3mmode}) {
399 eval q{use Cwd q{abs_path}};
401 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
402 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
403 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
404 unless $config{cgiurl} =~ m!file:///!;
405 $config{url}="file://".$config{destdir};
408 if ($config{cgi} && ! length $config{url}) {
409 error(gettext("Must specify url to wiki with --url when using --cgi"));
412 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
413 unless exists $config{wikistatedir};
416 eval qq{use IkiWiki::Rcs::$config{rcs}};
418 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
422 require IkiWiki::Rcs::Stub;
425 if (defined $config{umask}) {
426 umask(possibly_foolish_untaint($config{umask}));
429 run_hooks(checkconfig => sub { shift->() });
434 sub listplugins () { #{{{
437 foreach my $dir (@INC, $config{libdir}) {
438 next unless defined $dir;
439 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
440 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
444 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
445 next unless defined $dir;
446 foreach my $file (glob("$dir/plugins/*")) {
447 $ret{basename($file)}=1 if -x $file;
454 sub loadplugins () { #{{{
455 if (defined $config{libdir}) {
456 unshift @INC, possibly_foolish_untaint($config{libdir});
459 loadplugin($_) foreach @{$config{default_plugins}}, @{$config{add_plugins}};
461 run_hooks(getopt => sub { shift->() });
462 if (grep /^-/, @ARGV) {
463 print STDERR "Unknown option: $_\n"
464 foreach grep /^-/, @ARGV;
471 sub loadplugin ($) { #{{{
474 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
476 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
477 "$installdir/lib/ikiwiki") {
478 if (defined $dir && -x "$dir/plugins/$plugin") {
479 require IkiWiki::Plugin::external;
480 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
485 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
488 error("Failed to load plugin $mod: $@");
493 sub error ($;$) { #{{{
496 log_message('err' => $message) if $config{syslog};
497 if (defined $cleaner) {
504 return unless $config{verbose};
505 return log_message(debug => @_);
509 sub log_message ($$) { #{{{
512 if ($config{syslog}) {
515 Sys::Syslog::setlogsock('unix');
516 Sys::Syslog::openlog('ikiwiki', '', 'user');
520 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
523 elsif (! $config{cgi}) {
527 return print STDERR "@_\n";
531 sub possibly_foolish_untaint ($) { #{{{
533 my ($untainted)=$tainted=~/(.*)/s;
537 sub basename ($) { #{{{
544 sub dirname ($) { #{{{
551 sub pagetype ($) { #{{{
554 if ($page =~ /\.([^.]+)$/) {
555 return $1 if exists $hooks{htmlize}{$1};
560 sub isinternal ($) { #{{{
562 return exists $pagesources{$page} &&
563 $pagesources{$page} =~ /\._([^.]+)$/;
566 sub pagename ($) { #{{{
569 my $type=pagetype($file);
571 $page=~s/\Q.$type\E*$// if defined $type;
575 sub targetpage ($$) { #{{{
579 if (! $config{usedirs} || $page =~ /^index$/ ) {
580 return $page.".".$ext;
582 return $page."/index.".$ext;
586 sub htmlpage ($) { #{{{
589 return targetpage($page, $config{htmlext});
592 sub srcfile_stat { #{{{
596 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
597 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
598 return "$dir/$file", stat(_) if -e "$dir/$file";
600 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
604 sub srcfile ($;$) { #{{{
605 return (srcfile_stat(@_))[0];
608 sub add_underlay ($) { #{{{
612 unshift @{$config{underlaydirs}}, $dir;
615 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
621 sub readfile ($;$$) { #{{{
627 error("cannot read a symlink ($file)");
631 open (my $in, "<", $file) || error("failed to read $file: $!");
632 binmode($in) if ($binary);
633 return \*$in if $wantfd;
635 close $in || error("failed to read $file: $!");
639 sub prep_writefile ($$) { #{{{
644 while (length $test) {
645 if (-l "$destdir/$test") {
646 error("cannot write to a symlink ($test)");
648 $test=dirname($test);
651 my $dir=dirname("$destdir/$file");
654 foreach my $s (split(m!/+!, $dir)) {
657 mkdir($d) || error("failed to create directory $d: $!");
665 sub writefile ($$$;$$) { #{{{
666 my $file=shift; # can include subdirs
667 my $destdir=shift; # directory to put file in
672 prep_writefile($file, $destdir);
674 my $newfile="$destdir/$file.ikiwiki-new";
676 error("cannot write to a symlink ($newfile)");
679 my $cleanup = sub { unlink($newfile) };
680 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
681 binmode($out) if ($binary);
683 $writer->(\*$out, $cleanup);
686 print $out $content or error("failed writing to $newfile: $!", $cleanup);
688 close $out || error("failed saving $newfile: $!", $cleanup);
689 rename($newfile, "$destdir/$file") ||
690 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
696 sub will_render ($$;$) { #{{{
701 # Important security check.
702 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
703 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
704 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
707 if (! $clear || $cleared{$page}) {
708 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
711 foreach my $old (@{$renderedfiles{$page}}) {
712 delete $destsources{$old};
714 $renderedfiles{$page}=[$dest];
717 $destsources{$dest}=$page;
722 sub bestlink ($$) { #{{{
727 if ($link=~s/^\/+//) {
735 $l.="/" if length $l;
738 if (exists $links{$l}) {
741 elsif (exists $pagecase{lc $l}) {
742 return $pagecase{lc $l};
744 } while $cwd=~s!/?[^/]+$!!;
746 if (length $config{userdir}) {
747 my $l = "$config{userdir}/".lc($link);
748 if (exists $links{$l}) {
751 elsif (exists $pagecase{lc $l}) {
752 return $pagecase{lc $l};
756 #print STDERR "warning: page $page, broken link: $link\n";
760 sub isinlinableimage ($) { #{{{
763 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
766 sub pagetitle ($;$) { #{{{
771 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
774 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
780 sub titlepage ($) { #{{{
782 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
786 sub linkpage ($) { #{{{
788 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
792 sub cgiurl (@) { #{{{
795 return $config{cgiurl}."?".
796 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
799 sub baseurl (;$) { #{{{
802 return "$config{url}/" if ! defined $page;
804 $page=htmlpage($page);
806 $page=~s/[^\/]+\//..\//g;
810 sub abs2rel ($$) { #{{{
811 # Work around very innefficient behavior in File::Spec if abs2rel
812 # is passed two relative paths. It's much faster if paths are
813 # absolute! (Debian bug #376658; fixed in debian unstable now)
818 my $ret=File::Spec->abs2rel($path, $base);
819 $ret=~s/^// if defined $ret;
823 sub displaytime ($;$) { #{{{
826 if (! defined $format) {
827 $format=$config{timeformat};
830 # strftime doesn't know about encodings, so make sure
831 # its output is properly treated as utf8
832 return decode_utf8(POSIX::strftime($format, localtime($time)));
835 sub beautify_urlpath ($) { #{{{
838 if ($config{usedirs}) {
839 $url =~ s!/index.$config{htmlext}$!/!;
842 # Ensure url is not an empty link, and
843 # if it's relative, make that explicit to avoid colon confusion.
851 sub urlto ($$;$) { #{{{
857 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
860 if (! $destsources{$to}) {
865 return $config{url}.beautify_urlpath("/".$to);
868 my $link = abs2rel($to, dirname(htmlpage($from)));
870 return beautify_urlpath($link);
873 sub htmllink ($$$;@) { #{{{
874 my $lpage=shift; # the page doing the linking
875 my $page=shift; # the page that will contain the link (different for inline)
882 if (! $opts{forcesubpage}) {
883 $bestlink=bestlink($lpage, $link);
886 $bestlink="$lpage/".lc($link);
890 if (defined $opts{linktext}) {
891 $linktext=$opts{linktext};
894 $linktext=pagetitle(basename($link));
897 return "<span class=\"selflink\">$linktext</span>"
898 if length $bestlink && $page eq $bestlink &&
899 ! defined $opts{anchor};
901 if (! $destsources{$bestlink}) {
902 $bestlink=htmlpage($bestlink);
904 if (! $destsources{$bestlink}) {
905 return $linktext unless length $config{cgiurl};
906 return "<span class=\"createlink\"><a href=\"".
912 "\" rel=\"nofollow\">?</a>$linktext</span>"
916 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
917 $bestlink=beautify_urlpath($bestlink);
919 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
920 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
923 if (defined $opts{anchor}) {
924 $bestlink.="#".$opts{anchor};
928 if (defined $opts{rel}) {
929 push @attrs, ' rel="'.$opts{rel}.'"';
931 if (defined $opts{class}) {
932 push @attrs, ' class="'.$opts{class}.'"';
935 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
938 sub userlink ($) { #{{{
941 my $oiduser=eval { openiduser($user) };
942 if (defined $oiduser) {
943 return "<a href=\"$user\">$oiduser</a>";
946 eval q{use CGI 'escapeHTML'};
949 return htmllink("", "", escapeHTML(
950 length $config{userdir} ? $config{userdir}."/".$user : $user
951 ), noimageinline => 1);
955 sub htmlize ($$$$) { #{{{
961 my $oneline = $content !~ /\n/;
963 if (exists $hooks{htmlize}{$type}) {
964 $content=$hooks{htmlize}{$type}{call}->(
970 error("htmlization of $type not supported");
973 run_hooks(sanitize => sub {
976 destpage => $destpage,
982 # hack to get rid of enclosing junk added by markdown
983 # and other htmlizers
985 $content=~s/<\/p>$//i;
992 sub linkify ($$$) { #{{{
997 run_hooks(linkify => sub {
1000 destpage => $destpage,
1001 content => $content,
1009 our $preprocess_preview=0;
1010 sub preprocess ($$$;$$) { #{{{
1011 my $page=shift; # the page the data comes from
1012 my $destpage=shift; # the page the data will appear in (different for inline)
1017 # Using local because it needs to be set within any nested calls
1019 local $preprocess_preview=$preview if defined $preview;
1026 if (length $escape) {
1027 return "[[$prefix$command $params]]";
1029 elsif (exists $hooks{preprocess}{$command}) {
1030 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1031 # Note: preserve order of params, some plugins may
1032 # consider it significant.
1034 while ($params =~ m{
1035 (?:([-\w]+)=)? # 1: named parameter key?
1037 """(.*?)""" # 2: triple-quoted value
1039 "([^"]+)" # 3: single-quoted value
1041 (\S+) # 4: unquoted value
1043 (?:\s+|$) # delimiter to next param
1053 elsif (defined $3) {
1056 elsif (defined $4) {
1061 push @params, $key, $val;
1064 push @params, $val, '';
1067 if ($preprocessing{$page}++ > 3) {
1068 # Avoid loops of preprocessed pages preprocessing
1069 # other pages that preprocess them, etc.
1070 #translators: The first parameter is a
1071 #translators: preprocessor directive name,
1072 #translators: the second a page name, the
1073 #translators: third a number.
1074 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
1075 $command, $page, $preprocessing{$page}).
1081 $hooks{preprocess}{$command}{call}->(
1084 destpage => $destpage,
1085 preview => $preprocess_preview,
1090 $ret="[[!$command <span class=\"error\">".
1091 gettext("Error").": $@"."</span>]]";
1095 # use void context during scan pass
1097 $hooks{preprocess}{$command}{call}->(
1100 destpage => $destpage,
1101 preview => $preprocess_preview,
1106 $preprocessing{$page}--;
1110 return "[[$prefix$command $params]]";
1115 if ($config{prefix_directives}) {
1118 \[\[(!) # directive open; 2: prefix
1119 ([-\w]+) # 3: command
1120 ( # 4: the parameters..
1121 \s+ # Must have space if parameters present
1123 (?:[-\w]+=)? # named parameter key?
1125 """.*?""" # triple-quoted value
1127 "[^"]+" # single-quoted value
1129 [^\s\]]+ # unquoted value
1131 \s* # whitespace or end
1134 *)? # 0 or more parameters
1135 \]\] # directive closed
1141 \[\[(!?) # directive open; 2: optional prefix
1142 ([-\w]+) # 3: command
1144 ( # 4: the parameters..
1146 (?:[-\w]+=)? # named parameter key?
1148 """.*?""" # triple-quoted value
1150 "[^"]+" # single-quoted value
1152 [^\s\]]+ # unquoted value
1154 \s* # whitespace or end
1157 *) # 0 or more parameters
1158 \]\] # directive closed
1162 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1166 sub filter ($$$) { #{{{
1171 run_hooks(filter => sub {
1172 $content=shift->(page => $page, destpage => $destpage,
1173 content => $content);
1179 sub indexlink () { #{{{
1180 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1185 sub lockwiki (;$) { #{{{
1186 my $wait=@_ ? shift : 1;
1187 # Take an exclusive lock on the wiki to prevent multiple concurrent
1188 # run issues. The lock will be dropped on program exit.
1189 if (! -d $config{wikistatedir}) {
1190 mkdir($config{wikistatedir});
1192 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1193 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1194 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1196 debug("wiki seems to be locked, waiting for lock");
1197 my $wait=600; # arbitrary, but don't hang forever to
1198 # prevent process pileup
1200 return if flock($wikilock, 2 | 4);
1203 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1212 sub unlockwiki () { #{{{
1213 return close($wikilock) if $wikilock;
1219 sub commit_hook_enabled () { #{{{
1220 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1221 error("cannot write to $config{wikistatedir}/commitlock: $!");
1222 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1223 close($commitlock) || error("failed closing commitlock: $!");
1226 close($commitlock) || error("failed closing commitlock: $!");
1230 sub disable_commit_hook () { #{{{
1231 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1232 error("cannot write to $config{wikistatedir}/commitlock: $!");
1233 if (! flock($commitlock, 2)) { # LOCK_EX
1234 error("failed to get commit lock");
1239 sub enable_commit_hook () { #{{{
1240 return close($commitlock) if $commitlock;
1244 sub loadindex () { #{{{
1245 %oldrenderedfiles=%pagectime=();
1246 if (! $config{rebuild}) {
1247 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1248 %destsources=%renderedfiles=%pagecase=%pagestate=();
1251 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1252 if (-e "$config{wikistatedir}/index") {
1253 system("ikiwiki-transition", "indexdb", $config{srcdir});
1254 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1260 my $ret=Storable::fd_retrieve($in);
1261 if (! defined $ret) {
1265 foreach my $src (keys %index) {
1266 my %d=%{$index{$src}};
1267 my $page=pagename($src);
1268 $pagectime{$page}=$d{ctime};
1269 if (! $config{rebuild}) {
1270 $pagesources{$page}=$src;
1271 $pagemtime{$page}=$d{mtime};
1272 $renderedfiles{$page}=$d{dest};
1273 if (exists $d{links} && ref $d{links}) {
1274 $links{$page}=$d{links};
1275 $oldlinks{$page}=[@{$d{links}}];
1277 if (exists $d{depends}) {
1278 $depends{$page}=$d{depends};
1280 if (exists $d{state}) {
1281 $pagestate{$page}=$d{state};
1284 $oldrenderedfiles{$page}=[@{$d{dest}}];
1286 foreach my $page (keys %pagesources) {
1287 $pagecase{lc $page}=$page;
1289 foreach my $page (keys %renderedfiles) {
1290 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1295 sub saveindex () { #{{{
1296 run_hooks(savestate => sub { shift->() });
1299 foreach my $type (keys %hooks) {
1300 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1302 my @hookids=keys %hookids;
1304 if (! -d $config{wikistatedir}) {
1305 mkdir($config{wikistatedir});
1307 my $newfile="$config{wikistatedir}/indexdb.new";
1308 my $cleanup = sub { unlink($newfile) };
1309 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1311 foreach my $page (keys %pagemtime) {
1312 next unless $pagemtime{$page};
1313 my $src=$pagesources{$page};
1316 ctime => $pagectime{$page},
1317 mtime => $pagemtime{$page},
1318 dest => $renderedfiles{$page},
1319 links => $links{$page},
1322 if (exists $depends{$page}) {
1323 $index{$src}{depends} = $depends{$page};
1326 if (exists $pagestate{$page}) {
1327 foreach my $id (@hookids) {
1328 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1329 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1334 my $ret=Storable::nstore_fd(\%index, $out);
1335 return if ! defined $ret || ! $ret;
1336 close $out || error("failed saving to $newfile: $!", $cleanup);
1337 rename($newfile, "$config{wikistatedir}/indexdb") ||
1338 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1343 sub template_file ($) { #{{{
1346 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1347 return "$dir/$template" if -e "$dir/$template";
1352 sub template_params (@) { #{{{
1353 my $filename=template_file(shift);
1355 if (! defined $filename) {
1356 return if wantarray;
1362 my $text_ref = shift;
1363 ${$text_ref} = decode_utf8(${$text_ref});
1365 filename => $filename,
1366 loop_context_vars => 1,
1367 die_on_bad_params => 0,
1370 return wantarray ? @ret : {@ret};
1373 sub template ($;@) { #{{{
1374 require HTML::Template;
1375 return HTML::Template->new(template_params(@_));
1378 sub misctemplate ($$;@) { #{{{
1382 my $template=template("misc.tmpl");
1385 indexlink => indexlink(),
1386 wikiname => $config{wikiname},
1387 pagebody => $pagebody,
1388 baseurl => baseurl(),
1391 run_hooks(pagetemplate => sub {
1392 shift->(page => "", destpage => "", template => $template);
1394 return $template->output;
1397 sub hook (@) { # {{{
1400 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1401 error 'hook requires type, call, and id parameters';
1404 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1406 $hooks{$param{type}}{$param{id}}=\%param;
1410 sub run_hooks ($$) { # {{{
1411 # Calls the given sub for each hook of the given type,
1412 # passing it the hook function to call.
1416 if (exists $hooks{$type}) {
1418 foreach my $id (keys %{$hooks{$type}}) {
1419 if ($hooks{$type}{$id}{last}) {
1420 push @deferred, $id;
1423 $sub->($hooks{$type}{$id}{call});
1425 foreach my $id (@deferred) {
1426 $sub->($hooks{$type}{$id}{call});
1433 sub globlist_to_pagespec ($) { #{{{
1434 my @globlist=split(' ', shift);
1437 foreach my $glob (@globlist) {
1438 if ($glob=~/^!(.*)/) {
1446 my $spec=join(' or ', @spec);
1448 my $skip=join(' and ', @skip);
1450 $spec="$skip and ($spec)";
1459 sub is_globlist ($) { #{{{
1461 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1464 sub safequote ($) { #{{{
1470 sub add_depends ($$) { #{{{
1474 return unless pagespec_valid($pagespec);
1476 if (! exists $depends{$page}) {
1477 $depends{$page}=$pagespec;
1480 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1486 sub file_pruned ($$) { #{{{
1488 my $file=File::Spec->canonpath(shift);
1489 my $base=File::Spec->canonpath(shift);
1490 $file =~ s#^\Q$base\E/+##;
1492 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1493 return $file =~ m/$regexp/ && $file ne $base;
1497 # Only use gettext in the rare cases it's needed.
1498 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1499 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1500 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1501 if (! $gettext_obj) {
1502 $gettext_obj=eval q{
1503 use Locale::gettext q{textdomain};
1504 Locale::gettext->domain('ikiwiki')
1512 return $gettext_obj->get(shift);
1519 sub yesno ($) { #{{{
1522 return (defined $val && lc($val) eq gettext("yes"));
1525 sub pagespec_merge ($$) { #{{{
1529 return $a if $a eq $b;
1531 # Support for old-style GlobLists.
1532 if (is_globlist($a)) {
1533 $a=globlist_to_pagespec($a);
1535 if (is_globlist($b)) {
1536 $b=globlist_to_pagespec($b);
1539 return "($a) or ($b)";
1542 sub pagespec_translate ($) { #{{{
1545 # Support for old-style GlobLists.
1546 if (is_globlist($spec)) {
1547 $spec=globlist_to_pagespec($spec);
1550 # Convert spec to perl code.
1553 \s* # ignore whitespace
1554 ( # 1: match a single word
1561 \w+\([^\)]*\) # command(params)
1563 [^\s()]+ # any other text
1565 \s* # ignore whitespace
1568 if (lc $word eq 'and') {
1571 elsif (lc $word eq 'or') {
1574 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1577 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1578 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1579 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1586 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1590 if (! length $code) {
1595 return eval 'sub { my $page=shift; '.$code.' }';
1598 sub pagespec_match ($$;@) { #{{{
1603 # Backwards compatability with old calling convention.
1605 unshift @params, 'location';
1608 my $sub=pagespec_translate($spec);
1609 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1610 return $sub->($page, @params);
1613 sub pagespec_valid ($) { #{{{
1616 my $sub=pagespec_translate($spec);
1620 sub glob2re ($) { #{{{
1621 my $re=quotemeta(shift);
1627 package IkiWiki::FailReason;
1630 '""' => sub { ${$_[0]} },
1632 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1639 return bless \$value, $class;
1642 package IkiWiki::SuccessReason;
1645 '""' => sub { ${$_[0]} },
1647 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1654 return bless \$value, $class;
1657 package IkiWiki::PageSpec;
1659 sub match_glob ($$;@) { #{{{
1664 my $from=exists $params{location} ? $params{location} : '';
1667 if ($glob =~ m!^\./!) {
1668 $from=~s#/?[^/]+$##;
1670 $glob="$from/$glob" if length $from;
1673 my $regexp=IkiWiki::glob2re($glob);
1674 if ($page=~/^$regexp$/i) {
1675 if (! IkiWiki::isinternal($page) || $params{internal}) {
1676 return IkiWiki::SuccessReason->new("$glob matches $page");
1679 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1683 return IkiWiki::FailReason->new("$glob does not match $page");
1687 sub match_internal ($$;@) { #{{{
1688 return match_glob($_[0], $_[1], @_, internal => 1)
1691 sub match_link ($$;@) { #{{{
1696 my $from=exists $params{location} ? $params{location} : '';
1699 if ($link =~ m!^\.! && defined $from) {
1700 $from=~s#/?[^/]+$##;
1702 $link="$from/$link" if length $from;
1705 my $links = $IkiWiki::links{$page};
1706 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1707 my $bestlink = IkiWiki::bestlink($from, $link);
1708 foreach my $p (@{$links}) {
1709 if (length $bestlink) {
1710 return IkiWiki::SuccessReason->new("$page links to $link")
1711 if $bestlink eq IkiWiki::bestlink($page, $p);
1714 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1715 if match_glob($p, $link, %params);
1718 return IkiWiki::FailReason->new("$page does not link to $link");
1721 sub match_backlink ($$;@) { #{{{
1722 return match_link($_[1], $_[0], @_);
1725 sub match_created_before ($$;@) { #{{{
1729 if (exists $IkiWiki::pagectime{$testpage}) {
1730 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1731 return IkiWiki::SuccessReason->new("$page created before $testpage");
1734 return IkiWiki::FailReason->new("$page not created before $testpage");
1738 return IkiWiki::FailReason->new("$testpage has no ctime");
1742 sub match_created_after ($$;@) { #{{{
1746 if (exists $IkiWiki::pagectime{$testpage}) {
1747 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1748 return IkiWiki::SuccessReason->new("$page created after $testpage");
1751 return IkiWiki::FailReason->new("$page not created after $testpage");
1755 return IkiWiki::FailReason->new("$testpage has no ctime");
1759 sub match_creation_day ($$;@) { #{{{
1760 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1761 return IkiWiki::SuccessReason->new('creation_day matched');
1764 return IkiWiki::FailReason->new('creation_day did not match');
1768 sub match_creation_month ($$;@) { #{{{
1769 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1770 return IkiWiki::SuccessReason->new('creation_month matched');
1773 return IkiWiki::FailReason->new('creation_month did not match');
1777 sub match_creation_year ($$;@) { #{{{
1778 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1779 return IkiWiki::SuccessReason->new('creation_year matched');
1782 return IkiWiki::FailReason->new('creation_year did not match');