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?",
123 gitorigin_branch => {
126 description => "the git origin to pull from",
127 safe => 0, # paranoia
130 gitmaster_branch => {
133 description => "the git master branch",
134 safe => 0, # paranoia
140 description => "definitions of wrappers to generate",
147 description => "wrapper filename",
154 description => "mode of wrapper file",
160 default => "$installdir/share/ikiwiki/templates",
161 description => "location of template files",
167 default => "$installdir/share/ikiwiki/basewiki",
168 description => "base wiki source location",
175 description => "additional underlays to use",
182 description => "display verbose messages when building?",
189 description => "log to syslog?",
196 description => "create output files named page/index.html?",
197 safe => 0, # changing requires manual transition
200 prefix_directives => {
203 description => "use '!'-prefixed preprocessor directives?",
204 safe => 0, # changing requires manual transition
210 description => "extension to use for new pages",
211 safe => 0, # not sanitized
217 description => "extension to use for html files",
218 safe => 0, # not sanitized
224 description => "strftime format string to display date",
231 example => "en_US.UTF-8",
232 description => "UTF-8 locale to use",
239 description => "only send cookies over SSL connections?",
247 description => "put user pages below specified page",
254 description => "how many backlinks to show before hiding excess (0 to show all)",
261 description => "attempt to hardlink source files? (optimisation for large files)",
262 safe => 0, # paranoia
270 description => "regexp of source files to ignore",
274 wiki_file_prune_regexps => {
276 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
277 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
278 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
281 description => "regexps of source files to ignore",
285 wiki_file_regexp => {
287 default => qr/(^[-[:alnum:]_.:\/+]+$)/,
288 description => "regexp of legal source files",
292 web_commit_regexp => {
294 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
295 description => "regexp to parse web commits from logs",
302 description => "run as a cgi",
306 cgi_disable_uploads => {
309 description => "whether CGI should accept file uploads",
316 description => "run as a post-commit hook",
323 description => "running in rebuild mode",
330 description => "running in refresh mode",
337 description => "running in getctime mode",
344 description => "running in w3mmode",
351 description => "setup file to read",
357 default => [qw{mdwn link inline htmlscrubber passwordauth
358 openid signinedit lockedit conditional
359 recentchanges parentlinks}],
360 description => "plugins to enable by default",
367 description => "plugins to add to the default configuration",
374 description => "plugins to disable",
381 example => "$ENV{HOME}/.ikiwiki/",
382 description => "extra library and plugin directory",
388 sub defaultconfig () { #{{{
391 foreach my $key (keys %s) {
392 push @ret, $key, $s{$key}->{default};
398 sub checkconfig () { #{{{
399 # locale stuff; avoid LC_ALL since it overrides everything
400 if (defined $ENV{LC_ALL}) {
401 $ENV{LANG} = $ENV{LC_ALL};
404 if (defined $config{locale}) {
405 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
406 $ENV{LANG}=$config{locale};
411 if (ref $config{ENV} eq 'HASH') {
412 foreach my $val (keys %{$config{ENV}}) {
413 $ENV{$val}=$config{ENV}{$val};
417 if ($config{w3mmode}) {
418 eval q{use Cwd q{abs_path}};
420 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
421 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
422 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
423 unless $config{cgiurl} =~ m!file:///!;
424 $config{url}="file://".$config{destdir};
427 if ($config{cgi} && ! length $config{url}) {
428 error(gettext("Must specify url to wiki with --url when using --cgi"));
431 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
432 unless exists $config{wikistatedir};
435 eval qq{use IkiWiki::Rcs::$config{rcs}};
437 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
441 require IkiWiki::Rcs::Stub;
444 if (exists $config{umask}) {
445 umask(possibly_foolish_untaint($config{umask}));
448 run_hooks(checkconfig => sub { shift->() });
453 sub loadplugins () { #{{{
454 if (defined $config{libdir}) {
455 unshift @INC, possibly_foolish_untaint($config{libdir});
458 loadplugin($_) foreach @{$config{default_plugins}}, @{$config{add_plugins}};
460 run_hooks(getopt => sub { shift->() });
461 if (grep /^-/, @ARGV) {
462 print STDERR "Unknown option: $_\n"
463 foreach grep /^-/, @ARGV;
470 sub loadplugin ($) { #{{{
473 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
475 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
476 "$installdir/lib/ikiwiki") {
477 if (defined $dir && -x "$dir/plugins/$plugin") {
478 require IkiWiki::Plugin::external;
479 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
484 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
487 error("Failed to load plugin $mod: $@");
492 sub error ($;$) { #{{{
495 log_message('err' => $message) if $config{syslog};
496 if (defined $cleaner) {
503 return unless $config{verbose};
504 return log_message(debug => @_);
508 sub log_message ($$) { #{{{
511 if ($config{syslog}) {
514 Sys::Syslog::setlogsock('unix');
515 Sys::Syslog::openlog('ikiwiki', '', 'user');
519 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
522 elsif (! $config{cgi}) {
526 return print STDERR "@_\n";
530 sub possibly_foolish_untaint ($) { #{{{
532 my ($untainted)=$tainted=~/(.*)/s;
536 sub basename ($) { #{{{
543 sub dirname ($) { #{{{
550 sub pagetype ($) { #{{{
553 if ($page =~ /\.([^.]+)$/) {
554 return $1 if exists $hooks{htmlize}{$1};
559 sub isinternal ($) { #{{{
561 return exists $pagesources{$page} &&
562 $pagesources{$page} =~ /\._([^.]+)$/;
565 sub pagename ($) { #{{{
568 my $type=pagetype($file);
570 $page=~s/\Q.$type\E*$// if defined $type;
574 sub targetpage ($$) { #{{{
578 if (! $config{usedirs} || $page =~ /^index$/ ) {
579 return $page.".".$ext;
581 return $page."/index.".$ext;
585 sub htmlpage ($) { #{{{
588 return targetpage($page, $config{htmlext});
591 sub srcfile_stat { #{{{
595 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
596 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
597 return "$dir/$file", stat(_) if -e "$dir/$file";
599 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
603 sub srcfile ($;$) { #{{{
604 return (srcfile_stat(@_))[0];
607 sub add_underlay ($) { #{{{
611 unshift @{$config{underlaydirs}}, $dir;
614 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
620 sub readfile ($;$$) { #{{{
626 error("cannot read a symlink ($file)");
630 open (my $in, "<", $file) || error("failed to read $file: $!");
631 binmode($in) if ($binary);
632 return \*$in if $wantfd;
634 close $in || error("failed to read $file: $!");
638 sub prep_writefile ($$) { #{{{
643 while (length $test) {
644 if (-l "$destdir/$test") {
645 error("cannot write to a symlink ($test)");
647 $test=dirname($test);
650 my $dir=dirname("$destdir/$file");
653 foreach my $s (split(m!/+!, $dir)) {
656 mkdir($d) || error("failed to create directory $d: $!");
664 sub writefile ($$$;$$) { #{{{
665 my $file=shift; # can include subdirs
666 my $destdir=shift; # directory to put file in
671 prep_writefile($file, $destdir);
673 my $newfile="$destdir/$file.ikiwiki-new";
675 error("cannot write to a symlink ($newfile)");
678 my $cleanup = sub { unlink($newfile) };
679 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
680 binmode($out) if ($binary);
682 $writer->(\*$out, $cleanup);
685 print $out $content or error("failed writing to $newfile: $!", $cleanup);
687 close $out || error("failed saving $newfile: $!", $cleanup);
688 rename($newfile, "$destdir/$file") ||
689 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
695 sub will_render ($$;$) { #{{{
700 # Important security check.
701 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
702 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
703 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
706 if (! $clear || $cleared{$page}) {
707 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
710 foreach my $old (@{$renderedfiles{$page}}) {
711 delete $destsources{$old};
713 $renderedfiles{$page}=[$dest];
716 $destsources{$dest}=$page;
721 sub bestlink ($$) { #{{{
726 if ($link=~s/^\/+//) {
734 $l.="/" if length $l;
737 if (exists $links{$l}) {
740 elsif (exists $pagecase{lc $l}) {
741 return $pagecase{lc $l};
743 } while $cwd=~s!/?[^/]+$!!;
745 if (length $config{userdir}) {
746 my $l = "$config{userdir}/".lc($link);
747 if (exists $links{$l}) {
750 elsif (exists $pagecase{lc $l}) {
751 return $pagecase{lc $l};
755 #print STDERR "warning: page $page, broken link: $link\n";
759 sub isinlinableimage ($) { #{{{
762 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
765 sub pagetitle ($;$) { #{{{
770 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
773 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
779 sub titlepage ($) { #{{{
781 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
785 sub linkpage ($) { #{{{
787 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
791 sub cgiurl (@) { #{{{
794 return $config{cgiurl}."?".
795 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
798 sub baseurl (;$) { #{{{
801 return "$config{url}/" if ! defined $page;
803 $page=htmlpage($page);
805 $page=~s/[^\/]+\//..\//g;
809 sub abs2rel ($$) { #{{{
810 # Work around very innefficient behavior in File::Spec if abs2rel
811 # is passed two relative paths. It's much faster if paths are
812 # absolute! (Debian bug #376658; fixed in debian unstable now)
817 my $ret=File::Spec->abs2rel($path, $base);
818 $ret=~s/^// if defined $ret;
822 sub displaytime ($;$) { #{{{
825 if (! defined $format) {
826 $format=$config{timeformat};
829 # strftime doesn't know about encodings, so make sure
830 # its output is properly treated as utf8
831 return decode_utf8(POSIX::strftime($format, localtime($time)));
834 sub beautify_urlpath ($) { #{{{
837 if ($config{usedirs}) {
838 $url =~ s!/index.$config{htmlext}$!/!;
841 # Ensure url is not an empty link, and
842 # if it's relative, make that explicit to avoid colon confusion.
850 sub urlto ($$;$) { #{{{
856 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
859 if (! $destsources{$to}) {
864 return $config{url}.beautify_urlpath("/".$to);
867 my $link = abs2rel($to, dirname(htmlpage($from)));
869 return beautify_urlpath($link);
872 sub htmllink ($$$;@) { #{{{
873 my $lpage=shift; # the page doing the linking
874 my $page=shift; # the page that will contain the link (different for inline)
881 if (! $opts{forcesubpage}) {
882 $bestlink=bestlink($lpage, $link);
885 $bestlink="$lpage/".lc($link);
889 if (defined $opts{linktext}) {
890 $linktext=$opts{linktext};
893 $linktext=pagetitle(basename($link));
896 return "<span class=\"selflink\">$linktext</span>"
897 if length $bestlink && $page eq $bestlink &&
898 ! defined $opts{anchor};
900 if (! $destsources{$bestlink}) {
901 $bestlink=htmlpage($bestlink);
903 if (! $destsources{$bestlink}) {
904 return $linktext unless length $config{cgiurl};
905 return "<span class=\"createlink\"><a href=\"".
911 "\" rel=\"nofollow\">?</a>$linktext</span>"
915 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
916 $bestlink=beautify_urlpath($bestlink);
918 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
919 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
922 if (defined $opts{anchor}) {
923 $bestlink.="#".$opts{anchor};
927 if (defined $opts{rel}) {
928 push @attrs, ' rel="'.$opts{rel}.'"';
930 if (defined $opts{class}) {
931 push @attrs, ' class="'.$opts{class}.'"';
934 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
937 sub userlink ($) { #{{{
940 my $oiduser=eval { openiduser($user) };
941 if (defined $oiduser) {
942 return "<a href=\"$user\">$oiduser</a>";
945 eval q{use CGI 'escapeHTML'};
948 return htmllink("", "", escapeHTML(
949 length $config{userdir} ? $config{userdir}."/".$user : $user
950 ), noimageinline => 1);
954 sub htmlize ($$$$) { #{{{
960 my $oneline = $content !~ /\n/;
962 if (exists $hooks{htmlize}{$type}) {
963 $content=$hooks{htmlize}{$type}{call}->(
969 error("htmlization of $type not supported");
972 run_hooks(sanitize => sub {
975 destpage => $destpage,
981 # hack to get rid of enclosing junk added by markdown
982 # and other htmlizers
984 $content=~s/<\/p>$//i;
991 sub linkify ($$$) { #{{{
996 run_hooks(linkify => sub {
999 destpage => $destpage,
1000 content => $content,
1008 our $preprocess_preview=0;
1009 sub preprocess ($$$;$$) { #{{{
1010 my $page=shift; # the page the data comes from
1011 my $destpage=shift; # the page the data will appear in (different for inline)
1016 # Using local because it needs to be set within any nested calls
1018 local $preprocess_preview=$preview if defined $preview;
1025 if (length $escape) {
1026 return "[[$prefix$command $params]]";
1028 elsif (exists $hooks{preprocess}{$command}) {
1029 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1030 # Note: preserve order of params, some plugins may
1031 # consider it significant.
1033 while ($params =~ m{
1034 (?:([-\w]+)=)? # 1: named parameter key?
1036 """(.*?)""" # 2: triple-quoted value
1038 "([^"]+)" # 3: single-quoted value
1040 (\S+) # 4: unquoted value
1042 (?:\s+|$) # delimiter to next param
1052 elsif (defined $3) {
1055 elsif (defined $4) {
1060 push @params, $key, $val;
1063 push @params, $val, '';
1066 if ($preprocessing{$page}++ > 3) {
1067 # Avoid loops of preprocessed pages preprocessing
1068 # other pages that preprocess them, etc.
1069 #translators: The first parameter is a
1070 #translators: preprocessor directive name,
1071 #translators: the second a page name, the
1072 #translators: third a number.
1073 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
1074 $command, $page, $preprocessing{$page}).
1080 $hooks{preprocess}{$command}{call}->(
1083 destpage => $destpage,
1084 preview => $preprocess_preview,
1089 $ret="[[!$command <span class=\"error\">".
1090 gettext("Error").": $@"."</span>]]";
1094 # use void context during scan pass
1096 $hooks{preprocess}{$command}{call}->(
1099 destpage => $destpage,
1100 preview => $preprocess_preview,
1105 $preprocessing{$page}--;
1109 return "[[$prefix$command $params]]";
1114 if ($config{prefix_directives}) {
1117 \[\[(!) # directive open; 2: prefix
1118 ([-\w]+) # 3: command
1119 ( # 4: the parameters..
1120 \s+ # Must have space if parameters present
1122 (?:[-\w]+=)? # named parameter key?
1124 """.*?""" # triple-quoted value
1126 "[^"]+" # single-quoted value
1128 [^\s\]]+ # unquoted value
1130 \s* # whitespace or end
1133 *)? # 0 or more parameters
1134 \]\] # directive closed
1140 \[\[(!?) # directive open; 2: optional prefix
1141 ([-\w]+) # 3: command
1143 ( # 4: the parameters..
1145 (?:[-\w]+=)? # named parameter key?
1147 """.*?""" # triple-quoted value
1149 "[^"]+" # single-quoted value
1151 [^\s\]]+ # unquoted value
1153 \s* # whitespace or end
1156 *) # 0 or more parameters
1157 \]\] # directive closed
1161 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1165 sub filter ($$$) { #{{{
1170 run_hooks(filter => sub {
1171 $content=shift->(page => $page, destpage => $destpage,
1172 content => $content);
1178 sub indexlink () { #{{{
1179 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1184 sub lockwiki (;$) { #{{{
1185 my $wait=@_ ? shift : 1;
1186 # Take an exclusive lock on the wiki to prevent multiple concurrent
1187 # run issues. The lock will be dropped on program exit.
1188 if (! -d $config{wikistatedir}) {
1189 mkdir($config{wikistatedir});
1191 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1192 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1193 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1195 debug("wiki seems to be locked, waiting for lock");
1196 my $wait=600; # arbitrary, but don't hang forever to
1197 # prevent process pileup
1199 return if flock($wikilock, 2 | 4);
1202 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1211 sub unlockwiki () { #{{{
1212 return close($wikilock) if $wikilock;
1218 sub commit_hook_enabled () { #{{{
1219 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1220 error("cannot write to $config{wikistatedir}/commitlock: $!");
1221 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1222 close($commitlock) || error("failed closing commitlock: $!");
1225 close($commitlock) || error("failed closing commitlock: $!");
1229 sub disable_commit_hook () { #{{{
1230 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1231 error("cannot write to $config{wikistatedir}/commitlock: $!");
1232 if (! flock($commitlock, 2)) { # LOCK_EX
1233 error("failed to get commit lock");
1238 sub enable_commit_hook () { #{{{
1239 return close($commitlock) if $commitlock;
1243 sub loadindex () { #{{{
1244 %oldrenderedfiles=%pagectime=();
1245 if (! $config{rebuild}) {
1246 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1247 %destsources=%renderedfiles=%pagecase=%pagestate=();
1250 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1251 if (-e "$config{wikistatedir}/index") {
1252 system("ikiwiki-transition", "indexdb", $config{srcdir});
1253 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1259 my $ret=Storable::fd_retrieve($in);
1260 if (! defined $ret) {
1264 foreach my $src (keys %index) {
1265 my %d=%{$index{$src}};
1266 my $page=pagename($src);
1267 $pagectime{$page}=$d{ctime};
1268 if (! $config{rebuild}) {
1269 $pagesources{$page}=$src;
1270 $pagemtime{$page}=$d{mtime};
1271 $renderedfiles{$page}=$d{dest};
1272 if (exists $d{links} && ref $d{links}) {
1273 $links{$page}=$d{links};
1274 $oldlinks{$page}=[@{$d{links}}];
1276 if (exists $d{depends}) {
1277 $depends{$page}=$d{depends};
1279 if (exists $d{state}) {
1280 $pagestate{$page}=$d{state};
1283 $oldrenderedfiles{$page}=[@{$d{dest}}];
1285 foreach my $page (keys %pagesources) {
1286 $pagecase{lc $page}=$page;
1288 foreach my $page (keys %renderedfiles) {
1289 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1294 sub saveindex () { #{{{
1295 run_hooks(savestate => sub { shift->() });
1298 foreach my $type (keys %hooks) {
1299 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1301 my @hookids=keys %hookids;
1303 if (! -d $config{wikistatedir}) {
1304 mkdir($config{wikistatedir});
1306 my $newfile="$config{wikistatedir}/indexdb.new";
1307 my $cleanup = sub { unlink($newfile) };
1308 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1310 foreach my $page (keys %pagemtime) {
1311 next unless $pagemtime{$page};
1312 my $src=$pagesources{$page};
1315 ctime => $pagectime{$page},
1316 mtime => $pagemtime{$page},
1317 dest => $renderedfiles{$page},
1318 links => $links{$page},
1321 if (exists $depends{$page}) {
1322 $index{$src}{depends} = $depends{$page};
1325 if (exists $pagestate{$page}) {
1326 foreach my $id (@hookids) {
1327 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1328 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1333 my $ret=Storable::nstore_fd(\%index, $out);
1334 return if ! defined $ret || ! $ret;
1335 close $out || error("failed saving to $newfile: $!", $cleanup);
1336 rename($newfile, "$config{wikistatedir}/indexdb") ||
1337 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1342 sub template_file ($) { #{{{
1345 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1346 return "$dir/$template" if -e "$dir/$template";
1351 sub template_params (@) { #{{{
1352 my $filename=template_file(shift);
1354 if (! defined $filename) {
1355 return if wantarray;
1361 my $text_ref = shift;
1362 ${$text_ref} = decode_utf8(${$text_ref});
1364 filename => $filename,
1365 loop_context_vars => 1,
1366 die_on_bad_params => 0,
1369 return wantarray ? @ret : {@ret};
1372 sub template ($;@) { #{{{
1373 require HTML::Template;
1374 return HTML::Template->new(template_params(@_));
1377 sub misctemplate ($$;@) { #{{{
1381 my $template=template("misc.tmpl");
1384 indexlink => indexlink(),
1385 wikiname => $config{wikiname},
1386 pagebody => $pagebody,
1387 baseurl => baseurl(),
1390 run_hooks(pagetemplate => sub {
1391 shift->(page => "", destpage => "", template => $template);
1393 return $template->output;
1396 sub hook (@) { # {{{
1399 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1400 error 'hook requires type, call, and id parameters';
1403 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1405 $hooks{$param{type}}{$param{id}}=\%param;
1409 sub run_hooks ($$) { # {{{
1410 # Calls the given sub for each hook of the given type,
1411 # passing it the hook function to call.
1415 if (exists $hooks{$type}) {
1417 foreach my $id (keys %{$hooks{$type}}) {
1418 if ($hooks{$type}{$id}{last}) {
1419 push @deferred, $id;
1422 $sub->($hooks{$type}{$id}{call});
1424 foreach my $id (@deferred) {
1425 $sub->($hooks{$type}{$id}{call});
1432 sub globlist_to_pagespec ($) { #{{{
1433 my @globlist=split(' ', shift);
1436 foreach my $glob (@globlist) {
1437 if ($glob=~/^!(.*)/) {
1445 my $spec=join(' or ', @spec);
1447 my $skip=join(' and ', @skip);
1449 $spec="$skip and ($spec)";
1458 sub is_globlist ($) { #{{{
1460 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1463 sub safequote ($) { #{{{
1469 sub add_depends ($$) { #{{{
1473 return unless pagespec_valid($pagespec);
1475 if (! exists $depends{$page}) {
1476 $depends{$page}=$pagespec;
1479 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1485 sub file_pruned ($$) { #{{{
1487 my $file=File::Spec->canonpath(shift);
1488 my $base=File::Spec->canonpath(shift);
1489 $file =~ s#^\Q$base\E/+##;
1491 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1492 return $file =~ m/$regexp/ && $file ne $base;
1496 # Only use gettext in the rare cases it's needed.
1497 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1498 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1499 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1500 if (! $gettext_obj) {
1501 $gettext_obj=eval q{
1502 use Locale::gettext q{textdomain};
1503 Locale::gettext->domain('ikiwiki')
1511 return $gettext_obj->get(shift);
1518 sub yesno ($) { #{{{
1521 return (defined $val && lc($val) eq gettext("yes"));
1524 sub pagespec_merge ($$) { #{{{
1528 return $a if $a eq $b;
1530 # Support for old-style GlobLists.
1531 if (is_globlist($a)) {
1532 $a=globlist_to_pagespec($a);
1534 if (is_globlist($b)) {
1535 $b=globlist_to_pagespec($b);
1538 return "($a) or ($b)";
1541 sub pagespec_translate ($) { #{{{
1544 # Support for old-style GlobLists.
1545 if (is_globlist($spec)) {
1546 $spec=globlist_to_pagespec($spec);
1549 # Convert spec to perl code.
1552 \s* # ignore whitespace
1553 ( # 1: match a single word
1560 \w+\([^\)]*\) # command(params)
1562 [^\s()]+ # any other text
1564 \s* # ignore whitespace
1567 if (lc $word eq 'and') {
1570 elsif (lc $word eq 'or') {
1573 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1576 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1577 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1578 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1585 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1589 if (! length $code) {
1594 return eval 'sub { my $page=shift; '.$code.' }';
1597 sub pagespec_match ($$;@) { #{{{
1602 # Backwards compatability with old calling convention.
1604 unshift @params, 'location';
1607 my $sub=pagespec_translate($spec);
1608 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1609 return $sub->($page, @params);
1612 sub pagespec_valid ($) { #{{{
1615 my $sub=pagespec_translate($spec);
1619 sub glob2re ($) { #{{{
1620 my $re=quotemeta(shift);
1626 package IkiWiki::FailReason;
1629 '""' => sub { ${$_[0]} },
1631 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1638 return bless \$value, $class;
1641 package IkiWiki::SuccessReason;
1644 '""' => sub { ${$_[0]} },
1646 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1653 return bless \$value, $class;
1656 package IkiWiki::PageSpec;
1658 sub match_glob ($$;@) { #{{{
1663 my $from=exists $params{location} ? $params{location} : '';
1666 if ($glob =~ m!^\./!) {
1667 $from=~s#/?[^/]+$##;
1669 $glob="$from/$glob" if length $from;
1672 my $regexp=IkiWiki::glob2re($glob);
1673 if ($page=~/^$regexp$/i) {
1674 if (! IkiWiki::isinternal($page) || $params{internal}) {
1675 return IkiWiki::SuccessReason->new("$glob matches $page");
1678 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1682 return IkiWiki::FailReason->new("$glob does not match $page");
1686 sub match_internal ($$;@) { #{{{
1687 return match_glob($_[0], $_[1], @_, internal => 1)
1690 sub match_link ($$;@) { #{{{
1695 my $from=exists $params{location} ? $params{location} : '';
1698 if ($link =~ m!^\.! && defined $from) {
1699 $from=~s#/?[^/]+$##;
1701 $link="$from/$link" if length $from;
1704 my $links = $IkiWiki::links{$page};
1705 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1706 my $bestlink = IkiWiki::bestlink($from, $link);
1707 foreach my $p (@{$links}) {
1708 if (length $bestlink) {
1709 return IkiWiki::SuccessReason->new("$page links to $link")
1710 if $bestlink eq IkiWiki::bestlink($page, $p);
1713 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1714 if match_glob($p, $link, %params);
1717 return IkiWiki::FailReason->new("$page does not link to $link");
1720 sub match_backlink ($$;@) { #{{{
1721 return match_link($_[1], $_[0], @_);
1724 sub match_created_before ($$;@) { #{{{
1728 if (exists $IkiWiki::pagectime{$testpage}) {
1729 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1730 return IkiWiki::SuccessReason->new("$page created before $testpage");
1733 return IkiWiki::FailReason->new("$page not created before $testpage");
1737 return IkiWiki::FailReason->new("$testpage has no ctime");
1741 sub match_created_after ($$;@) { #{{{
1745 if (exists $IkiWiki::pagectime{$testpage}) {
1746 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1747 return IkiWiki::SuccessReason->new("$page created after $testpage");
1750 return IkiWiki::FailReason->new("$page not created after $testpage");
1754 return IkiWiki::FailReason->new("$testpage has no ctime");
1758 sub match_creation_day ($$;@) { #{{{
1759 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1760 return IkiWiki::SuccessReason->new('creation_day matched');
1763 return IkiWiki::FailReason->new('creation_day did not match');
1767 sub match_creation_month ($$;@) { #{{{
1768 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1769 return IkiWiki::SuccessReason->new('creation_month matched');
1772 return IkiWiki::FailReason->new('creation_month did not match');
1776 sub match_creation_year ($$;@) { #{{{
1777 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1778 return IkiWiki::SuccessReason->new('creation_year matched');
1781 return IkiWiki::FailReason->new('creation_year did not match');