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};
416 if (defined $config{umask}) {
417 umask(possibly_foolish_untaint($config{umask}));
420 run_hooks(checkconfig => sub { shift->() });
425 sub listplugins () { #{{{
428 foreach my $dir (@INC, $config{libdir}) {
429 next unless defined $dir && length $dir;
430 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
431 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
435 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
436 next unless defined $dir && length $dir;
437 foreach my $file (glob("$dir/plugins/*")) {
438 $ret{basename($file)}=1 if -x $file;
445 sub loadplugins () { #{{{
446 if (defined $config{libdir} && length $config{libdir}) {
447 unshift @INC, possibly_foolish_untaint($config{libdir});
450 loadplugin($_) foreach @{$config{default_plugins}}, @{$config{add_plugins}};
453 if (exists $IkiWiki::hooks{rcs}) {
454 error(gettext("cannot use multiple rcs plugins"));
456 loadplugin($config{rcs});
458 if (! exists $IkiWiki::hooks{rcs}) {
462 run_hooks(getopt => sub { shift->() });
463 if (grep /^-/, @ARGV) {
464 print STDERR "Unknown option: $_\n"
465 foreach grep /^-/, @ARGV;
472 sub loadplugin ($) { #{{{
475 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
477 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
478 "$installdir/lib/ikiwiki") {
479 if (defined $dir && -x "$dir/plugins/$plugin") {
480 require IkiWiki::Plugin::external;
481 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
486 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
489 error("Failed to load plugin $mod: $@");
494 sub error ($;$) { #{{{
497 log_message('err' => $message) if $config{syslog};
498 if (defined $cleaner) {
505 return unless $config{verbose};
506 return log_message(debug => @_);
510 sub log_message ($$) { #{{{
513 if ($config{syslog}) {
516 Sys::Syslog::setlogsock('unix');
517 Sys::Syslog::openlog('ikiwiki', '', 'user');
521 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
524 elsif (! $config{cgi}) {
528 return print STDERR "@_\n";
532 sub possibly_foolish_untaint ($) { #{{{
534 my ($untainted)=$tainted=~/(.*)/s;
538 sub basename ($) { #{{{
545 sub dirname ($) { #{{{
552 sub pagetype ($) { #{{{
555 if ($page =~ /\.([^.]+)$/) {
556 return $1 if exists $hooks{htmlize}{$1};
561 sub isinternal ($) { #{{{
563 return exists $pagesources{$page} &&
564 $pagesources{$page} =~ /\._([^.]+)$/;
567 sub pagename ($) { #{{{
570 my $type=pagetype($file);
572 $page=~s/\Q.$type\E*$// if defined $type;
576 sub targetpage ($$) { #{{{
580 if (! $config{usedirs} || $page =~ /^index$/ ) {
581 return $page.".".$ext;
583 return $page."/index.".$ext;
587 sub htmlpage ($) { #{{{
590 return targetpage($page, $config{htmlext});
593 sub srcfile_stat { #{{{
597 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
598 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
599 return "$dir/$file", stat(_) if -e "$dir/$file";
601 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
605 sub srcfile ($;$) { #{{{
606 return (srcfile_stat(@_))[0];
609 sub add_underlay ($) { #{{{
613 unshift @{$config{underlaydirs}}, $dir;
616 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
622 sub readfile ($;$$) { #{{{
628 error("cannot read a symlink ($file)");
632 open (my $in, "<", $file) || error("failed to read $file: $!");
633 binmode($in) if ($binary);
634 return \*$in if $wantfd;
636 close $in || error("failed to read $file: $!");
640 sub prep_writefile ($$) { #{{{
645 while (length $test) {
646 if (-l "$destdir/$test") {
647 error("cannot write to a symlink ($test)");
649 $test=dirname($test);
652 my $dir=dirname("$destdir/$file");
655 foreach my $s (split(m!/+!, $dir)) {
658 mkdir($d) || error("failed to create directory $d: $!");
666 sub writefile ($$$;$$) { #{{{
667 my $file=shift; # can include subdirs
668 my $destdir=shift; # directory to put file in
673 prep_writefile($file, $destdir);
675 my $newfile="$destdir/$file.ikiwiki-new";
677 error("cannot write to a symlink ($newfile)");
680 my $cleanup = sub { unlink($newfile) };
681 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
682 binmode($out) if ($binary);
684 $writer->(\*$out, $cleanup);
687 print $out $content or error("failed writing to $newfile: $!", $cleanup);
689 close $out || error("failed saving $newfile: $!", $cleanup);
690 rename($newfile, "$destdir/$file") ||
691 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
697 sub will_render ($$;$) { #{{{
702 # Important security check.
703 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
704 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
705 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
708 if (! $clear || $cleared{$page}) {
709 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
712 foreach my $old (@{$renderedfiles{$page}}) {
713 delete $destsources{$old};
715 $renderedfiles{$page}=[$dest];
718 $destsources{$dest}=$page;
723 sub bestlink ($$) { #{{{
728 if ($link=~s/^\/+//) {
736 $l.="/" if length $l;
739 if (exists $links{$l}) {
742 elsif (exists $pagecase{lc $l}) {
743 return $pagecase{lc $l};
745 } while $cwd=~s!/?[^/]+$!!;
747 if (length $config{userdir}) {
748 my $l = "$config{userdir}/".lc($link);
749 if (exists $links{$l}) {
752 elsif (exists $pagecase{lc $l}) {
753 return $pagecase{lc $l};
757 #print STDERR "warning: page $page, broken link: $link\n";
761 sub isinlinableimage ($) { #{{{
764 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
767 sub pagetitle ($;$) { #{{{
772 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
775 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
781 sub titlepage ($) { #{{{
783 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
787 sub linkpage ($) { #{{{
789 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
793 sub cgiurl (@) { #{{{
796 return $config{cgiurl}."?".
797 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
800 sub baseurl (;$) { #{{{
803 return "$config{url}/" if ! defined $page;
805 $page=htmlpage($page);
807 $page=~s/[^\/]+\//..\//g;
811 sub abs2rel ($$) { #{{{
812 # Work around very innefficient behavior in File::Spec if abs2rel
813 # is passed two relative paths. It's much faster if paths are
814 # absolute! (Debian bug #376658; fixed in debian unstable now)
819 my $ret=File::Spec->abs2rel($path, $base);
820 $ret=~s/^// if defined $ret;
824 sub displaytime ($;$) { #{{{
827 if (! defined $format) {
828 $format=$config{timeformat};
831 # strftime doesn't know about encodings, so make sure
832 # its output is properly treated as utf8
833 return decode_utf8(POSIX::strftime($format, localtime($time)));
836 sub beautify_urlpath ($) { #{{{
839 if ($config{usedirs}) {
840 $url =~ s!/index.$config{htmlext}$!/!;
843 # Ensure url is not an empty link, and
844 # if it's relative, make that explicit to avoid colon confusion.
852 sub urlto ($$;$) { #{{{
858 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
861 if (! $destsources{$to}) {
866 return $config{url}.beautify_urlpath("/".$to);
869 my $link = abs2rel($to, dirname(htmlpage($from)));
871 return beautify_urlpath($link);
874 sub htmllink ($$$;@) { #{{{
875 my $lpage=shift; # the page doing the linking
876 my $page=shift; # the page that will contain the link (different for inline)
883 if (! $opts{forcesubpage}) {
884 $bestlink=bestlink($lpage, $link);
887 $bestlink="$lpage/".lc($link);
891 if (defined $opts{linktext}) {
892 $linktext=$opts{linktext};
895 $linktext=pagetitle(basename($link));
898 return "<span class=\"selflink\">$linktext</span>"
899 if length $bestlink && $page eq $bestlink &&
900 ! defined $opts{anchor};
902 if (! $destsources{$bestlink}) {
903 $bestlink=htmlpage($bestlink);
905 if (! $destsources{$bestlink}) {
906 return $linktext unless length $config{cgiurl};
907 return "<span class=\"createlink\"><a href=\"".
913 "\" rel=\"nofollow\">?</a>$linktext</span>"
917 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
918 $bestlink=beautify_urlpath($bestlink);
920 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
921 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
924 if (defined $opts{anchor}) {
925 $bestlink.="#".$opts{anchor};
929 if (defined $opts{rel}) {
930 push @attrs, ' rel="'.$opts{rel}.'"';
932 if (defined $opts{class}) {
933 push @attrs, ' class="'.$opts{class}.'"';
936 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
939 sub userlink ($) { #{{{
942 my $oiduser=eval { openiduser($user) };
943 if (defined $oiduser) {
944 return "<a href=\"$user\">$oiduser</a>";
947 eval q{use CGI 'escapeHTML'};
950 return htmllink("", "", escapeHTML(
951 length $config{userdir} ? $config{userdir}."/".$user : $user
952 ), noimageinline => 1);
956 sub htmlize ($$$$) { #{{{
962 my $oneline = $content !~ /\n/;
964 if (exists $hooks{htmlize}{$type}) {
965 $content=$hooks{htmlize}{$type}{call}->(
971 error("htmlization of $type not supported");
974 run_hooks(sanitize => sub {
977 destpage => $destpage,
983 # hack to get rid of enclosing junk added by markdown
984 # and other htmlizers
986 $content=~s/<\/p>$//i;
993 sub linkify ($$$) { #{{{
998 run_hooks(linkify => sub {
1001 destpage => $destpage,
1002 content => $content,
1010 our $preprocess_preview=0;
1011 sub preprocess ($$$;$$) { #{{{
1012 my $page=shift; # the page the data comes from
1013 my $destpage=shift; # the page the data will appear in (different for inline)
1018 # Using local because it needs to be set within any nested calls
1020 local $preprocess_preview=$preview if defined $preview;
1027 if (length $escape) {
1028 return "[[$prefix$command $params]]";
1030 elsif (exists $hooks{preprocess}{$command}) {
1031 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1032 # Note: preserve order of params, some plugins may
1033 # consider it significant.
1035 while ($params =~ m{
1036 (?:([-\w]+)=)? # 1: named parameter key?
1038 """(.*?)""" # 2: triple-quoted value
1040 "([^"]+)" # 3: single-quoted value
1042 (\S+) # 4: unquoted value
1044 (?:\s+|$) # delimiter to next param
1054 elsif (defined $3) {
1057 elsif (defined $4) {
1062 push @params, $key, $val;
1065 push @params, $val, '';
1068 if ($preprocessing{$page}++ > 3) {
1069 # Avoid loops of preprocessed pages preprocessing
1070 # other pages that preprocess them, etc.
1071 return "[[!$command <span class=\"error\">".
1072 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1073 $page, $preprocessing{$page}).
1079 $hooks{preprocess}{$command}{call}->(
1082 destpage => $destpage,
1083 preview => $preprocess_preview,
1088 $ret="[[!$command <span class=\"error\">".
1089 gettext("Error").": $@"."</span>]]";
1093 # use void context during scan pass
1095 $hooks{preprocess}{$command}{call}->(
1098 destpage => $destpage,
1099 preview => $preprocess_preview,
1104 $preprocessing{$page}--;
1108 return "[[$prefix$command $params]]";
1113 if ($config{prefix_directives}) {
1116 \[\[(!) # directive open; 2: prefix
1117 ([-\w]+) # 3: command
1118 ( # 4: the parameters..
1119 \s+ # Must have space if parameters present
1121 (?:[-\w]+=)? # named parameter key?
1123 """.*?""" # triple-quoted value
1125 "[^"]+" # single-quoted value
1127 [^\s\]]+ # unquoted value
1129 \s* # whitespace or end
1132 *)? # 0 or more parameters
1133 \]\] # directive closed
1139 \[\[(!?) # directive open; 2: optional prefix
1140 ([-\w]+) # 3: command
1142 ( # 4: the parameters..
1144 (?:[-\w]+=)? # named parameter key?
1146 """.*?""" # triple-quoted value
1148 "[^"]+" # single-quoted value
1150 [^\s\]]+ # unquoted value
1152 \s* # whitespace or end
1155 *) # 0 or more parameters
1156 \]\] # directive closed
1160 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1164 sub filter ($$$) { #{{{
1169 run_hooks(filter => sub {
1170 $content=shift->(page => $page, destpage => $destpage,
1171 content => $content);
1177 sub indexlink () { #{{{
1178 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1183 sub lockwiki (;$) { #{{{
1184 my $wait=@_ ? shift : 1;
1185 # Take an exclusive lock on the wiki to prevent multiple concurrent
1186 # run issues. The lock will be dropped on program exit.
1187 if (! -d $config{wikistatedir}) {
1188 mkdir($config{wikistatedir});
1190 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1191 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1192 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1194 debug("wiki seems to be locked, waiting for lock");
1195 my $wait=600; # arbitrary, but don't hang forever to
1196 # prevent process pileup
1198 return if flock($wikilock, 2 | 4);
1201 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1210 sub unlockwiki () { #{{{
1211 return close($wikilock) if $wikilock;
1217 sub commit_hook_enabled () { #{{{
1218 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1219 error("cannot write to $config{wikistatedir}/commitlock: $!");
1220 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1221 close($commitlock) || error("failed closing commitlock: $!");
1224 close($commitlock) || error("failed closing commitlock: $!");
1228 sub disable_commit_hook () { #{{{
1229 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1230 error("cannot write to $config{wikistatedir}/commitlock: $!");
1231 if (! flock($commitlock, 2)) { # LOCK_EX
1232 error("failed to get commit lock");
1237 sub enable_commit_hook () { #{{{
1238 return close($commitlock) if $commitlock;
1242 sub loadindex () { #{{{
1243 %oldrenderedfiles=%pagectime=();
1244 if (! $config{rebuild}) {
1245 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1246 %destsources=%renderedfiles=%pagecase=%pagestate=();
1249 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1250 if (-e "$config{wikistatedir}/index") {
1251 system("ikiwiki-transition", "indexdb", $config{srcdir});
1252 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1258 my $ret=Storable::fd_retrieve($in);
1259 if (! defined $ret) {
1263 foreach my $src (keys %index) {
1264 my %d=%{$index{$src}};
1265 my $page=pagename($src);
1266 $pagectime{$page}=$d{ctime};
1267 if (! $config{rebuild}) {
1268 $pagesources{$page}=$src;
1269 $pagemtime{$page}=$d{mtime};
1270 $renderedfiles{$page}=$d{dest};
1271 if (exists $d{links} && ref $d{links}) {
1272 $links{$page}=$d{links};
1273 $oldlinks{$page}=[@{$d{links}}];
1275 if (exists $d{depends}) {
1276 $depends{$page}=$d{depends};
1278 if (exists $d{state}) {
1279 $pagestate{$page}=$d{state};
1282 $oldrenderedfiles{$page}=[@{$d{dest}}];
1284 foreach my $page (keys %pagesources) {
1285 $pagecase{lc $page}=$page;
1287 foreach my $page (keys %renderedfiles) {
1288 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1293 sub saveindex () { #{{{
1294 run_hooks(savestate => sub { shift->() });
1297 foreach my $type (keys %hooks) {
1298 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1300 my @hookids=keys %hookids;
1302 if (! -d $config{wikistatedir}) {
1303 mkdir($config{wikistatedir});
1305 my $newfile="$config{wikistatedir}/indexdb.new";
1306 my $cleanup = sub { unlink($newfile) };
1307 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1309 foreach my $page (keys %pagemtime) {
1310 next unless $pagemtime{$page};
1311 my $src=$pagesources{$page};
1314 ctime => $pagectime{$page},
1315 mtime => $pagemtime{$page},
1316 dest => $renderedfiles{$page},
1317 links => $links{$page},
1320 if (exists $depends{$page}) {
1321 $index{$src}{depends} = $depends{$page};
1324 if (exists $pagestate{$page}) {
1325 foreach my $id (@hookids) {
1326 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1327 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1332 my $ret=Storable::nstore_fd(\%index, $out);
1333 return if ! defined $ret || ! $ret;
1334 close $out || error("failed saving to $newfile: $!", $cleanup);
1335 rename($newfile, "$config{wikistatedir}/indexdb") ||
1336 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1341 sub template_file ($) { #{{{
1344 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1345 return "$dir/$template" if -e "$dir/$template";
1350 sub template_params (@) { #{{{
1351 my $filename=template_file(shift);
1353 if (! defined $filename) {
1354 return if wantarray;
1360 my $text_ref = shift;
1361 ${$text_ref} = decode_utf8(${$text_ref});
1363 filename => $filename,
1364 loop_context_vars => 1,
1365 die_on_bad_params => 0,
1368 return wantarray ? @ret : {@ret};
1371 sub template ($;@) { #{{{
1372 require HTML::Template;
1373 return HTML::Template->new(template_params(@_));
1376 sub misctemplate ($$;@) { #{{{
1380 my $template=template("misc.tmpl");
1383 indexlink => indexlink(),
1384 wikiname => $config{wikiname},
1385 pagebody => $pagebody,
1386 baseurl => baseurl(),
1389 run_hooks(pagetemplate => sub {
1390 shift->(page => "", destpage => "", template => $template);
1392 return $template->output;
1395 sub hook (@) { # {{{
1398 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1399 error 'hook requires type, call, and id parameters';
1402 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1404 $hooks{$param{type}}{$param{id}}=\%param;
1408 sub run_hooks ($$) { # {{{
1409 # Calls the given sub for each hook of the given type,
1410 # passing it the hook function to call.
1414 if (exists $hooks{$type}) {
1416 foreach my $id (keys %{$hooks{$type}}) {
1417 if ($hooks{$type}{$id}{last}) {
1418 push @deferred, $id;
1421 $sub->($hooks{$type}{$id}{call});
1423 foreach my $id (@deferred) {
1424 $sub->($hooks{$type}{$id}{call});
1431 sub rcs_update () { #{{{
1432 $hooks{rcs}{rcs_update}{call}->(@_);
1435 sub rcs_prepedit ($) { #{{{
1436 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1439 sub rcs_commit ($$$;$$) { #{{{
1440 $hooks{rcs}{rcs_commit}{call}->(@_);
1443 sub rcs_commit_staged ($$$) { #{{{
1444 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1447 sub rcs_add ($) { #{{{
1448 $hooks{rcs}{rcs_add}{call}->(@_);
1451 sub rcs_remove ($) { #{{{
1452 $hooks{rcs}{rcs_remove}{call}->(@_);
1455 sub rcs_rename ($$) { #{{{
1456 $hooks{rcs}{rcs_rename}{call}->(@_);
1459 sub rcs_recentchanges ($) { #{{{
1460 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1463 sub rcs_diff ($) { #{{{
1464 $hooks{rcs}{rcs_diff}{call}->(@_);
1467 sub rcs_getctime ($) { #{{{
1468 $hooks{rcs}{rcs_getctime}{call}->(@_);
1471 sub globlist_to_pagespec ($) { #{{{
1472 my @globlist=split(' ', shift);
1475 foreach my $glob (@globlist) {
1476 if ($glob=~/^!(.*)/) {
1484 my $spec=join(' or ', @spec);
1486 my $skip=join(' and ', @skip);
1488 $spec="$skip and ($spec)";
1497 sub is_globlist ($) { #{{{
1499 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1502 sub safequote ($) { #{{{
1508 sub add_depends ($$) { #{{{
1512 return unless pagespec_valid($pagespec);
1514 if (! exists $depends{$page}) {
1515 $depends{$page}=$pagespec;
1518 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1524 sub file_pruned ($$) { #{{{
1526 my $file=File::Spec->canonpath(shift);
1527 my $base=File::Spec->canonpath(shift);
1528 $file =~ s#^\Q$base\E/+##;
1530 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1531 return $file =~ m/$regexp/ && $file ne $base;
1535 # Only use gettext in the rare cases it's needed.
1536 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1537 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1538 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1539 if (! $gettext_obj) {
1540 $gettext_obj=eval q{
1541 use Locale::gettext q{textdomain};
1542 Locale::gettext->domain('ikiwiki')
1550 return $gettext_obj->get(shift);
1557 sub yesno ($) { #{{{
1560 return (defined $val && lc($val) eq gettext("yes"));
1563 sub pagespec_merge ($$) { #{{{
1567 return $a if $a eq $b;
1569 # Support for old-style GlobLists.
1570 if (is_globlist($a)) {
1571 $a=globlist_to_pagespec($a);
1573 if (is_globlist($b)) {
1574 $b=globlist_to_pagespec($b);
1577 return "($a) or ($b)";
1580 sub pagespec_translate ($) { #{{{
1583 # Support for old-style GlobLists.
1584 if (is_globlist($spec)) {
1585 $spec=globlist_to_pagespec($spec);
1588 # Convert spec to perl code.
1591 \s* # ignore whitespace
1592 ( # 1: match a single word
1599 \w+\([^\)]*\) # command(params)
1601 [^\s()]+ # any other text
1603 \s* # ignore whitespace
1606 if (lc $word eq 'and') {
1609 elsif (lc $word eq 'or') {
1612 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1615 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1616 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1617 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1624 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1628 if (! length $code) {
1633 return eval 'sub { my $page=shift; '.$code.' }';
1636 sub pagespec_match ($$;@) { #{{{
1641 # Backwards compatability with old calling convention.
1643 unshift @params, 'location';
1646 my $sub=pagespec_translate($spec);
1647 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1648 return $sub->($page, @params);
1651 sub pagespec_valid ($) { #{{{
1654 my $sub=pagespec_translate($spec);
1658 sub glob2re ($) { #{{{
1659 my $re=quotemeta(shift);
1665 package IkiWiki::FailReason;
1668 '""' => sub { ${$_[0]} },
1670 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1677 return bless \$value, $class;
1680 package IkiWiki::SuccessReason;
1683 '""' => sub { ${$_[0]} },
1685 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1692 return bless \$value, $class;
1695 package IkiWiki::PageSpec;
1697 sub match_glob ($$;@) { #{{{
1702 my $from=exists $params{location} ? $params{location} : '';
1705 if ($glob =~ m!^\./!) {
1706 $from=~s#/?[^/]+$##;
1708 $glob="$from/$glob" if length $from;
1711 my $regexp=IkiWiki::glob2re($glob);
1712 if ($page=~/^$regexp$/i) {
1713 if (! IkiWiki::isinternal($page) || $params{internal}) {
1714 return IkiWiki::SuccessReason->new("$glob matches $page");
1717 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1721 return IkiWiki::FailReason->new("$glob does not match $page");
1725 sub match_internal ($$;@) { #{{{
1726 return match_glob($_[0], $_[1], @_, internal => 1)
1729 sub match_link ($$;@) { #{{{
1734 my $from=exists $params{location} ? $params{location} : '';
1737 if ($link =~ m!^\.! && defined $from) {
1738 $from=~s#/?[^/]+$##;
1740 $link="$from/$link" if length $from;
1743 my $links = $IkiWiki::links{$page};
1744 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1745 my $bestlink = IkiWiki::bestlink($from, $link);
1746 foreach my $p (@{$links}) {
1747 if (length $bestlink) {
1748 return IkiWiki::SuccessReason->new("$page links to $link")
1749 if $bestlink eq IkiWiki::bestlink($page, $p);
1752 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1753 if match_glob($p, $link, %params);
1756 return IkiWiki::FailReason->new("$page does not link to $link");
1759 sub match_backlink ($$;@) { #{{{
1760 return match_link($_[1], $_[0], @_);
1763 sub match_created_before ($$;@) { #{{{
1767 if (exists $IkiWiki::pagectime{$testpage}) {
1768 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1769 return IkiWiki::SuccessReason->new("$page created before $testpage");
1772 return IkiWiki::FailReason->new("$page not created before $testpage");
1776 return IkiWiki::FailReason->new("$testpage has no ctime");
1780 sub match_created_after ($$;@) { #{{{
1784 if (exists $IkiWiki::pagectime{$testpage}) {
1785 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1786 return IkiWiki::SuccessReason->new("$page created after $testpage");
1789 return IkiWiki::FailReason->new("$page not created after $testpage");
1793 return IkiWiki::FailReason->new("$testpage has no ctime");
1797 sub match_creation_day ($$;@) { #{{{
1798 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1799 return IkiWiki::SuccessReason->new('creation_day matched');
1802 return IkiWiki::FailReason->new('creation_day did not match');
1806 sub match_creation_month ($$;@) { #{{{
1807 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1808 return IkiWiki::SuccessReason->new('creation_month matched');
1811 return IkiWiki::FailReason->new('creation_month did not match');
1815 sub match_creation_year ($$;@) { #{{{
1816 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1817 return IkiWiki::SuccessReason->new('creation_year matched');
1820 return IkiWiki::FailReason->new('creation_year did not match');