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 example => "http://example.com/wiki/ikiwiki.cgi",
86 description => "url to the ikiwiki.cgi",
93 example => "/var/www/wiki/ikiwiki.cgi",
94 description => "cgi executable to generate",
101 description => "mode for cgi_wrapper (can safely be made suid)",
108 description => "rcs backend to use",
109 safe => 0, # don't allow overriding
114 default => [qw{mdwn link inline htmlscrubber passwordauth
115 openid signinedit lockedit conditional
116 recentchanges parentlinks}],
117 description => "plugins to enable by default",
124 description => "plugins to add to the default configuration",
131 description => "plugins to disable",
137 default => "$installdir/share/ikiwiki/templates",
138 description => "location of template files",
144 default => "$installdir/share/ikiwiki/basewiki",
145 description => "base wiki source location",
152 description => "wrappers to generate",
159 description => "additional underlays to use",
166 description => "display verbose messages when building?",
173 description => "log to syslog?",
180 description => "create output files named page/index.html?",
181 safe => 0, # changing requires manual transition
184 prefix_directives => {
187 description => "use '!'-prefixed preprocessor directives?",
188 safe => 0, # changing requires manual transition
194 description => "enable Discussion pages?",
201 description => "extension to use for new pages",
202 safe => 0, # not sanitized
208 description => "extension to use for html files",
209 safe => 0, # not sanitized
215 description => "strftime format string to display date",
222 example => "en_US.UTF-8",
223 description => "UTF-8 locale to use",
230 description => "only send cookies over SSL connections?",
238 description => "put user pages below specified page",
245 description => "how many backlinks to show before hiding excess (0 to show all)",
252 description => "attempt to hardlink source files? (optimisation for large files)",
253 safe => 0, # paranoia
260 description => "force ikiwiki to use a particular umask",
261 safe => 0, # paranoia
267 example => "$ENV{HOME}/.ikiwiki/",
268 description => "extra library and plugin directory",
269 safe => 0, # directory
275 description => "environment variables",
276 safe => 0, # paranoia
283 description => "regexp of source files to ignore",
287 wiki_file_prune_regexps => {
289 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
290 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
291 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
294 description => "regexps of source files to ignore",
298 wiki_file_regexp => {
300 default => qr/(^[-[:alnum:]_.:\/+]+$)/,
301 description => "regexp of legal source files",
305 web_commit_regexp => {
307 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
308 description => "regexp to parse web commits from logs",
315 description => "run as a cgi",
319 cgi_disable_uploads => {
322 description => "whether CGI should accept file uploads",
329 description => "run as a post-commit hook",
336 description => "running in rebuild mode",
343 description => "running in refresh mode",
350 description => "running in getctime mode",
357 description => "running in w3mmode",
364 description => "setup file to read",
370 sub defaultconfig () { #{{{
373 foreach my $key (keys %s) {
374 push @ret, $key, $s{$key}->{default};
380 sub checkconfig () { #{{{
381 # locale stuff; avoid LC_ALL since it overrides everything
382 if (defined $ENV{LC_ALL}) {
383 $ENV{LANG} = $ENV{LC_ALL};
386 if (defined $config{locale}) {
387 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
388 $ENV{LANG}=$config{locale};
393 if (ref $config{ENV} eq 'HASH') {
394 foreach my $val (keys %{$config{ENV}}) {
395 $ENV{$val}=$config{ENV}{$val};
399 if ($config{w3mmode}) {
400 eval q{use Cwd q{abs_path}};
402 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
403 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
404 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
405 unless $config{cgiurl} =~ m!file:///!;
406 $config{url}="file://".$config{destdir};
409 if ($config{cgi} && ! length $config{url}) {
410 error(gettext("Must specify url to wiki with --url when using --cgi"));
413 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
414 unless exists $config{wikistatedir};
417 loadplugin($config{rcs});
423 if (defined $config{umask}) {
424 umask(possibly_foolish_untaint($config{umask}));
427 run_hooks(checkconfig => sub { shift->() });
432 sub listplugins () { #{{{
435 foreach my $dir (@INC, $config{libdir}) {
436 next unless defined $dir;
437 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
438 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
442 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
443 next unless defined $dir;
444 foreach my $file (glob("$dir/plugins/*")) {
445 $ret{basename($file)}=1 if -x $file;
452 sub loadplugins () { #{{{
453 if (defined $config{libdir}) {
454 unshift @INC, possibly_foolish_untaint($config{libdir});
457 loadplugin($_) foreach @{$config{default_plugins}}, @{$config{add_plugins}};
459 run_hooks(getopt => sub { shift->() });
460 if (grep /^-/, @ARGV) {
461 print STDERR "Unknown option: $_\n"
462 foreach grep /^-/, @ARGV;
469 sub loadplugin ($) { #{{{
472 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
474 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
475 "$installdir/lib/ikiwiki") {
476 if (defined $dir && -x "$dir/plugins/$plugin") {
477 require IkiWiki::Plugin::external;
478 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
483 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
486 error("Failed to load plugin $mod: $@");
491 sub error ($;$) { #{{{
494 log_message('err' => $message) if $config{syslog};
495 if (defined $cleaner) {
502 return unless $config{verbose};
503 return log_message(debug => @_);
507 sub log_message ($$) { #{{{
510 if ($config{syslog}) {
513 Sys::Syslog::setlogsock('unix');
514 Sys::Syslog::openlog('ikiwiki', '', 'user');
518 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
521 elsif (! $config{cgi}) {
525 return print STDERR "@_\n";
529 sub possibly_foolish_untaint ($) { #{{{
531 my ($untainted)=$tainted=~/(.*)/s;
535 sub basename ($) { #{{{
542 sub dirname ($) { #{{{
549 sub pagetype ($) { #{{{
552 if ($page =~ /\.([^.]+)$/) {
553 return $1 if exists $hooks{htmlize}{$1};
558 sub isinternal ($) { #{{{
560 return exists $pagesources{$page} &&
561 $pagesources{$page} =~ /\._([^.]+)$/;
564 sub pagename ($) { #{{{
567 my $type=pagetype($file);
569 $page=~s/\Q.$type\E*$// if defined $type;
573 sub targetpage ($$) { #{{{
577 if (! $config{usedirs} || $page =~ /^index$/ ) {
578 return $page.".".$ext;
580 return $page."/index.".$ext;
584 sub htmlpage ($) { #{{{
587 return targetpage($page, $config{htmlext});
590 sub srcfile_stat { #{{{
594 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
595 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
596 return "$dir/$file", stat(_) if -e "$dir/$file";
598 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
602 sub srcfile ($;$) { #{{{
603 return (srcfile_stat(@_))[0];
606 sub add_underlay ($) { #{{{
610 unshift @{$config{underlaydirs}}, $dir;
613 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
619 sub readfile ($;$$) { #{{{
625 error("cannot read a symlink ($file)");
629 open (my $in, "<", $file) || error("failed to read $file: $!");
630 binmode($in) if ($binary);
631 return \*$in if $wantfd;
633 close $in || error("failed to read $file: $!");
637 sub prep_writefile ($$) { #{{{
642 while (length $test) {
643 if (-l "$destdir/$test") {
644 error("cannot write to a symlink ($test)");
646 $test=dirname($test);
649 my $dir=dirname("$destdir/$file");
652 foreach my $s (split(m!/+!, $dir)) {
655 mkdir($d) || error("failed to create directory $d: $!");
663 sub writefile ($$$;$$) { #{{{
664 my $file=shift; # can include subdirs
665 my $destdir=shift; # directory to put file in
670 prep_writefile($file, $destdir);
672 my $newfile="$destdir/$file.ikiwiki-new";
674 error("cannot write to a symlink ($newfile)");
677 my $cleanup = sub { unlink($newfile) };
678 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
679 binmode($out) if ($binary);
681 $writer->(\*$out, $cleanup);
684 print $out $content or error("failed writing to $newfile: $!", $cleanup);
686 close $out || error("failed saving $newfile: $!", $cleanup);
687 rename($newfile, "$destdir/$file") ||
688 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
694 sub will_render ($$;$) { #{{{
699 # Important security check.
700 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
701 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
702 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
705 if (! $clear || $cleared{$page}) {
706 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
709 foreach my $old (@{$renderedfiles{$page}}) {
710 delete $destsources{$old};
712 $renderedfiles{$page}=[$dest];
715 $destsources{$dest}=$page;
720 sub bestlink ($$) { #{{{
725 if ($link=~s/^\/+//) {
733 $l.="/" if length $l;
736 if (exists $links{$l}) {
739 elsif (exists $pagecase{lc $l}) {
740 return $pagecase{lc $l};
742 } while $cwd=~s!/?[^/]+$!!;
744 if (length $config{userdir}) {
745 my $l = "$config{userdir}/".lc($link);
746 if (exists $links{$l}) {
749 elsif (exists $pagecase{lc $l}) {
750 return $pagecase{lc $l};
754 #print STDERR "warning: page $page, broken link: $link\n";
758 sub isinlinableimage ($) { #{{{
761 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
764 sub pagetitle ($;$) { #{{{
769 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
772 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
778 sub titlepage ($) { #{{{
780 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
784 sub linkpage ($) { #{{{
786 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
790 sub cgiurl (@) { #{{{
793 return $config{cgiurl}."?".
794 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
797 sub baseurl (;$) { #{{{
800 return "$config{url}/" if ! defined $page;
802 $page=htmlpage($page);
804 $page=~s/[^\/]+\//..\//g;
808 sub abs2rel ($$) { #{{{
809 # Work around very innefficient behavior in File::Spec if abs2rel
810 # is passed two relative paths. It's much faster if paths are
811 # absolute! (Debian bug #376658; fixed in debian unstable now)
816 my $ret=File::Spec->abs2rel($path, $base);
817 $ret=~s/^// if defined $ret;
821 sub displaytime ($;$) { #{{{
824 if (! defined $format) {
825 $format=$config{timeformat};
828 # strftime doesn't know about encodings, so make sure
829 # its output is properly treated as utf8
830 return decode_utf8(POSIX::strftime($format, localtime($time)));
833 sub beautify_urlpath ($) { #{{{
836 if ($config{usedirs}) {
837 $url =~ s!/index.$config{htmlext}$!/!;
840 # Ensure url is not an empty link, and
841 # if it's relative, make that explicit to avoid colon confusion.
849 sub urlto ($$;$) { #{{{
855 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
858 if (! $destsources{$to}) {
863 return $config{url}.beautify_urlpath("/".$to);
866 my $link = abs2rel($to, dirname(htmlpage($from)));
868 return beautify_urlpath($link);
871 sub htmllink ($$$;@) { #{{{
872 my $lpage=shift; # the page doing the linking
873 my $page=shift; # the page that will contain the link (different for inline)
880 if (! $opts{forcesubpage}) {
881 $bestlink=bestlink($lpage, $link);
884 $bestlink="$lpage/".lc($link);
888 if (defined $opts{linktext}) {
889 $linktext=$opts{linktext};
892 $linktext=pagetitle(basename($link));
895 return "<span class=\"selflink\">$linktext</span>"
896 if length $bestlink && $page eq $bestlink &&
897 ! defined $opts{anchor};
899 if (! $destsources{$bestlink}) {
900 $bestlink=htmlpage($bestlink);
902 if (! $destsources{$bestlink}) {
903 return $linktext unless length $config{cgiurl};
904 return "<span class=\"createlink\"><a href=\"".
910 "\" rel=\"nofollow\">?</a>$linktext</span>"
914 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
915 $bestlink=beautify_urlpath($bestlink);
917 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
918 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
921 if (defined $opts{anchor}) {
922 $bestlink.="#".$opts{anchor};
926 if (defined $opts{rel}) {
927 push @attrs, ' rel="'.$opts{rel}.'"';
929 if (defined $opts{class}) {
930 push @attrs, ' class="'.$opts{class}.'"';
933 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
936 sub userlink ($) { #{{{
939 my $oiduser=eval { openiduser($user) };
940 if (defined $oiduser) {
941 return "<a href=\"$user\">$oiduser</a>";
944 eval q{use CGI 'escapeHTML'};
947 return htmllink("", "", escapeHTML(
948 length $config{userdir} ? $config{userdir}."/".$user : $user
949 ), noimageinline => 1);
953 sub htmlize ($$$$) { #{{{
959 my $oneline = $content !~ /\n/;
961 if (exists $hooks{htmlize}{$type}) {
962 $content=$hooks{htmlize}{$type}{call}->(
968 error("htmlization of $type not supported");
971 run_hooks(sanitize => sub {
974 destpage => $destpage,
980 # hack to get rid of enclosing junk added by markdown
981 # and other htmlizers
983 $content=~s/<\/p>$//i;
990 sub linkify ($$$) { #{{{
995 run_hooks(linkify => sub {
998 destpage => $destpage,
1007 our $preprocess_preview=0;
1008 sub preprocess ($$$;$$) { #{{{
1009 my $page=shift; # the page the data comes from
1010 my $destpage=shift; # the page the data will appear in (different for inline)
1015 # Using local because it needs to be set within any nested calls
1017 local $preprocess_preview=$preview if defined $preview;
1024 if (length $escape) {
1025 return "[[$prefix$command $params]]";
1027 elsif (exists $hooks{preprocess}{$command}) {
1028 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1029 # Note: preserve order of params, some plugins may
1030 # consider it significant.
1032 while ($params =~ m{
1033 (?:([-\w]+)=)? # 1: named parameter key?
1035 """(.*?)""" # 2: triple-quoted value
1037 "([^"]+)" # 3: single-quoted value
1039 (\S+) # 4: unquoted value
1041 (?:\s+|$) # delimiter to next param
1051 elsif (defined $3) {
1054 elsif (defined $4) {
1059 push @params, $key, $val;
1062 push @params, $val, '';
1065 if ($preprocessing{$page}++ > 3) {
1066 # Avoid loops of preprocessed pages preprocessing
1067 # other pages that preprocess them, etc.
1068 return "[[!$command <span class=\"error\">".
1069 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1070 $page, $preprocessing{$page}).
1076 $hooks{preprocess}{$command}{call}->(
1079 destpage => $destpage,
1080 preview => $preprocess_preview,
1085 $ret="[[!$command <span class=\"error\">".
1086 gettext("Error").": $@"."</span>]]";
1090 # use void context during scan pass
1092 $hooks{preprocess}{$command}{call}->(
1095 destpage => $destpage,
1096 preview => $preprocess_preview,
1101 $preprocessing{$page}--;
1105 return "[[$prefix$command $params]]";
1110 if ($config{prefix_directives}) {
1113 \[\[(!) # directive open; 2: prefix
1114 ([-\w]+) # 3: command
1115 ( # 4: the parameters..
1116 \s+ # Must have space if parameters present
1118 (?:[-\w]+=)? # named parameter key?
1120 """.*?""" # triple-quoted value
1122 "[^"]+" # single-quoted value
1124 [^\s\]]+ # unquoted value
1126 \s* # whitespace or end
1129 *)? # 0 or more parameters
1130 \]\] # directive closed
1136 \[\[(!?) # directive open; 2: optional prefix
1137 ([-\w]+) # 3: command
1139 ( # 4: the parameters..
1141 (?:[-\w]+=)? # named parameter key?
1143 """.*?""" # triple-quoted value
1145 "[^"]+" # single-quoted value
1147 [^\s\]]+ # unquoted value
1149 \s* # whitespace or end
1152 *) # 0 or more parameters
1153 \]\] # directive closed
1157 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1161 sub filter ($$$) { #{{{
1166 run_hooks(filter => sub {
1167 $content=shift->(page => $page, destpage => $destpage,
1168 content => $content);
1174 sub indexlink () { #{{{
1175 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1180 sub lockwiki (;$) { #{{{
1181 my $wait=@_ ? shift : 1;
1182 # Take an exclusive lock on the wiki to prevent multiple concurrent
1183 # run issues. The lock will be dropped on program exit.
1184 if (! -d $config{wikistatedir}) {
1185 mkdir($config{wikistatedir});
1187 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1188 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1189 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1191 debug("wiki seems to be locked, waiting for lock");
1192 my $wait=600; # arbitrary, but don't hang forever to
1193 # prevent process pileup
1195 return if flock($wikilock, 2 | 4);
1198 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1207 sub unlockwiki () { #{{{
1208 return close($wikilock) if $wikilock;
1214 sub commit_hook_enabled () { #{{{
1215 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1216 error("cannot write to $config{wikistatedir}/commitlock: $!");
1217 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1218 close($commitlock) || error("failed closing commitlock: $!");
1221 close($commitlock) || error("failed closing commitlock: $!");
1225 sub disable_commit_hook () { #{{{
1226 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1227 error("cannot write to $config{wikistatedir}/commitlock: $!");
1228 if (! flock($commitlock, 2)) { # LOCK_EX
1229 error("failed to get commit lock");
1234 sub enable_commit_hook () { #{{{
1235 return close($commitlock) if $commitlock;
1239 sub loadindex () { #{{{
1240 %oldrenderedfiles=%pagectime=();
1241 if (! $config{rebuild}) {
1242 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1243 %destsources=%renderedfiles=%pagecase=%pagestate=();
1246 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1247 if (-e "$config{wikistatedir}/index") {
1248 system("ikiwiki-transition", "indexdb", $config{srcdir});
1249 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1255 my $ret=Storable::fd_retrieve($in);
1256 if (! defined $ret) {
1260 foreach my $src (keys %index) {
1261 my %d=%{$index{$src}};
1262 my $page=pagename($src);
1263 $pagectime{$page}=$d{ctime};
1264 if (! $config{rebuild}) {
1265 $pagesources{$page}=$src;
1266 $pagemtime{$page}=$d{mtime};
1267 $renderedfiles{$page}=$d{dest};
1268 if (exists $d{links} && ref $d{links}) {
1269 $links{$page}=$d{links};
1270 $oldlinks{$page}=[@{$d{links}}];
1272 if (exists $d{depends}) {
1273 $depends{$page}=$d{depends};
1275 if (exists $d{state}) {
1276 $pagestate{$page}=$d{state};
1279 $oldrenderedfiles{$page}=[@{$d{dest}}];
1281 foreach my $page (keys %pagesources) {
1282 $pagecase{lc $page}=$page;
1284 foreach my $page (keys %renderedfiles) {
1285 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1290 sub saveindex () { #{{{
1291 run_hooks(savestate => sub { shift->() });
1294 foreach my $type (keys %hooks) {
1295 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1297 my @hookids=keys %hookids;
1299 if (! -d $config{wikistatedir}) {
1300 mkdir($config{wikistatedir});
1302 my $newfile="$config{wikistatedir}/indexdb.new";
1303 my $cleanup = sub { unlink($newfile) };
1304 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1306 foreach my $page (keys %pagemtime) {
1307 next unless $pagemtime{$page};
1308 my $src=$pagesources{$page};
1311 ctime => $pagectime{$page},
1312 mtime => $pagemtime{$page},
1313 dest => $renderedfiles{$page},
1314 links => $links{$page},
1317 if (exists $depends{$page}) {
1318 $index{$src}{depends} = $depends{$page};
1321 if (exists $pagestate{$page}) {
1322 foreach my $id (@hookids) {
1323 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1324 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1329 my $ret=Storable::nstore_fd(\%index, $out);
1330 return if ! defined $ret || ! $ret;
1331 close $out || error("failed saving to $newfile: $!", $cleanup);
1332 rename($newfile, "$config{wikistatedir}/indexdb") ||
1333 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1338 sub template_file ($) { #{{{
1341 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1342 return "$dir/$template" if -e "$dir/$template";
1347 sub template_params (@) { #{{{
1348 my $filename=template_file(shift);
1350 if (! defined $filename) {
1351 return if wantarray;
1357 my $text_ref = shift;
1358 ${$text_ref} = decode_utf8(${$text_ref});
1360 filename => $filename,
1361 loop_context_vars => 1,
1362 die_on_bad_params => 0,
1365 return wantarray ? @ret : {@ret};
1368 sub template ($;@) { #{{{
1369 require HTML::Template;
1370 return HTML::Template->new(template_params(@_));
1373 sub misctemplate ($$;@) { #{{{
1377 my $template=template("misc.tmpl");
1380 indexlink => indexlink(),
1381 wikiname => $config{wikiname},
1382 pagebody => $pagebody,
1383 baseurl => baseurl(),
1386 run_hooks(pagetemplate => sub {
1387 shift->(page => "", destpage => "", template => $template);
1389 return $template->output;
1392 sub hook (@) { # {{{
1395 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1396 error 'hook requires type, call, and id parameters';
1399 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1401 $hooks{$param{type}}{$param{id}}=\%param;
1405 sub run_hooks ($$) { # {{{
1406 # Calls the given sub for each hook of the given type,
1407 # passing it the hook function to call.
1411 if (exists $hooks{$type}) {
1413 foreach my $id (keys %{$hooks{$type}}) {
1414 if ($hooks{$type}{$id}{last}) {
1415 push @deferred, $id;
1418 $sub->($hooks{$type}{$id}{call});
1420 foreach my $id (@deferred) {
1421 $sub->($hooks{$type}{$id}{call});
1428 sub rcs_update () { #{{{
1429 $hooks{rcs}{rcs_update}{call}->(@_);
1432 sub rcs_prepedit ($) { #{{{
1433 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1436 sub rcs_commit ($$$;$$) { #{{{
1437 $hooks{rcs}{rcs_commit}{call}->(@_);
1440 sub rcs_commit_staged ($$$) { #{{{
1441 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1444 sub rcs_add ($) { #{{{
1445 $hooks{rcs}{rcs_add}{call}->(@_);
1448 sub rcs_remove ($) { #{{{
1449 $hooks{rcs}{rcs_remove}{call}->(@_);
1452 sub rcs_rename ($$) { #{{{
1453 $hooks{rcs}{rcs_rename}{call}->(@_);
1456 sub rcs_recentchanges ($) { #{{{
1457 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1460 sub rcs_diff ($) { #{{{
1461 $hooks{rcs}{rcs_diff}{call}->(@_);
1464 sub rcs_getctime ($) { #{{{
1465 $hooks{rcs}{rcs_getctime}{call}->(@_);
1468 sub globlist_to_pagespec ($) { #{{{
1469 my @globlist=split(' ', shift);
1472 foreach my $glob (@globlist) {
1473 if ($glob=~/^!(.*)/) {
1481 my $spec=join(' or ', @spec);
1483 my $skip=join(' and ', @skip);
1485 $spec="$skip and ($spec)";
1494 sub is_globlist ($) { #{{{
1496 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1499 sub safequote ($) { #{{{
1505 sub add_depends ($$) { #{{{
1509 return unless pagespec_valid($pagespec);
1511 if (! exists $depends{$page}) {
1512 $depends{$page}=$pagespec;
1515 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1521 sub file_pruned ($$) { #{{{
1523 my $file=File::Spec->canonpath(shift);
1524 my $base=File::Spec->canonpath(shift);
1525 $file =~ s#^\Q$base\E/+##;
1527 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1528 return $file =~ m/$regexp/ && $file ne $base;
1532 # Only use gettext in the rare cases it's needed.
1533 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1534 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1535 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1536 if (! $gettext_obj) {
1537 $gettext_obj=eval q{
1538 use Locale::gettext q{textdomain};
1539 Locale::gettext->domain('ikiwiki')
1547 return $gettext_obj->get(shift);
1554 sub yesno ($) { #{{{
1557 return (defined $val && lc($val) eq gettext("yes"));
1560 sub pagespec_merge ($$) { #{{{
1564 return $a if $a eq $b;
1566 # Support for old-style GlobLists.
1567 if (is_globlist($a)) {
1568 $a=globlist_to_pagespec($a);
1570 if (is_globlist($b)) {
1571 $b=globlist_to_pagespec($b);
1574 return "($a) or ($b)";
1577 sub pagespec_translate ($) { #{{{
1580 # Support for old-style GlobLists.
1581 if (is_globlist($spec)) {
1582 $spec=globlist_to_pagespec($spec);
1585 # Convert spec to perl code.
1588 \s* # ignore whitespace
1589 ( # 1: match a single word
1596 \w+\([^\)]*\) # command(params)
1598 [^\s()]+ # any other text
1600 \s* # ignore whitespace
1603 if (lc $word eq 'and') {
1606 elsif (lc $word eq 'or') {
1609 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1612 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1613 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1614 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1621 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1625 if (! length $code) {
1630 return eval 'sub { my $page=shift; '.$code.' }';
1633 sub pagespec_match ($$;@) { #{{{
1638 # Backwards compatability with old calling convention.
1640 unshift @params, 'location';
1643 my $sub=pagespec_translate($spec);
1644 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1645 return $sub->($page, @params);
1648 sub pagespec_valid ($) { #{{{
1651 my $sub=pagespec_translate($spec);
1655 sub glob2re ($) { #{{{
1656 my $re=quotemeta(shift);
1662 package IkiWiki::FailReason;
1665 '""' => sub { ${$_[0]} },
1667 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1674 return bless \$value, $class;
1677 package IkiWiki::SuccessReason;
1680 '""' => sub { ${$_[0]} },
1682 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1689 return bless \$value, $class;
1692 package IkiWiki::PageSpec;
1694 sub match_glob ($$;@) { #{{{
1699 my $from=exists $params{location} ? $params{location} : '';
1702 if ($glob =~ m!^\./!) {
1703 $from=~s#/?[^/]+$##;
1705 $glob="$from/$glob" if length $from;
1708 my $regexp=IkiWiki::glob2re($glob);
1709 if ($page=~/^$regexp$/i) {
1710 if (! IkiWiki::isinternal($page) || $params{internal}) {
1711 return IkiWiki::SuccessReason->new("$glob matches $page");
1714 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1718 return IkiWiki::FailReason->new("$glob does not match $page");
1722 sub match_internal ($$;@) { #{{{
1723 return match_glob($_[0], $_[1], @_, internal => 1)
1726 sub match_link ($$;@) { #{{{
1731 my $from=exists $params{location} ? $params{location} : '';
1734 if ($link =~ m!^\.! && defined $from) {
1735 $from=~s#/?[^/]+$##;
1737 $link="$from/$link" if length $from;
1740 my $links = $IkiWiki::links{$page};
1741 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1742 my $bestlink = IkiWiki::bestlink($from, $link);
1743 foreach my $p (@{$links}) {
1744 if (length $bestlink) {
1745 return IkiWiki::SuccessReason->new("$page links to $link")
1746 if $bestlink eq IkiWiki::bestlink($page, $p);
1749 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1750 if match_glob($p, $link, %params);
1753 return IkiWiki::FailReason->new("$page does not link to $link");
1756 sub match_backlink ($$;@) { #{{{
1757 return match_link($_[1], $_[0], @_);
1760 sub match_created_before ($$;@) { #{{{
1764 if (exists $IkiWiki::pagectime{$testpage}) {
1765 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1766 return IkiWiki::SuccessReason->new("$page created before $testpage");
1769 return IkiWiki::FailReason->new("$page not created before $testpage");
1773 return IkiWiki::FailReason->new("$testpage has no ctime");
1777 sub match_created_after ($$;@) { #{{{
1781 if (exists $IkiWiki::pagectime{$testpage}) {
1782 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1783 return IkiWiki::SuccessReason->new("$page created after $testpage");
1786 return IkiWiki::FailReason->new("$page not created after $testpage");
1790 return IkiWiki::FailReason->new("$testpage has no ctime");
1794 sub match_creation_day ($$;@) { #{{{
1795 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1796 return IkiWiki::SuccessReason->new('creation_day matched');
1799 return IkiWiki::FailReason->new('creation_day did not match');
1803 sub match_creation_month ($$;@) { #{{{
1804 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1805 return IkiWiki::SuccessReason->new('creation_month matched');
1808 return IkiWiki::FailReason->new('creation_month did not match');
1812 sub match_creation_year ($$;@) { #{{{
1813 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1814 return IkiWiki::SuccessReason->new('creation_year matched');
1817 return IkiWiki::FailReason->new('creation_year did not match');