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",
290 description => "users who cannot use the wiki",
294 wiki_file_prune_regexps => {
296 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
297 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
298 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
301 description => "regexps of source files to ignore",
305 wiki_file_regexp => {
307 default => qr/(^[-[:alnum:]_.:\/+]+$)/,
308 description => "regexp of legal source files",
312 web_commit_regexp => {
314 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
315 description => "regexp to parse web commits from logs",
322 description => "run as a cgi",
326 cgi_disable_uploads => {
329 description => "whether CGI should accept file uploads",
336 description => "run as a post-commit hook",
343 description => "running in rebuild mode",
350 description => "running in refresh mode",
357 description => "running in getctime mode",
364 description => "running in w3mmode",
371 description => "setup file to read",
377 sub defaultconfig () { #{{{
380 foreach my $key (keys %s) {
381 push @ret, $key, $s{$key}->{default};
387 sub checkconfig () { #{{{
388 # locale stuff; avoid LC_ALL since it overrides everything
389 if (defined $ENV{LC_ALL}) {
390 $ENV{LANG} = $ENV{LC_ALL};
393 if (defined $config{locale}) {
394 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
395 $ENV{LANG}=$config{locale};
400 if (ref $config{ENV} eq 'HASH') {
401 foreach my $val (keys %{$config{ENV}}) {
402 $ENV{$val}=$config{ENV}{$val};
406 if ($config{w3mmode}) {
407 eval q{use Cwd q{abs_path}};
409 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
410 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
411 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
412 unless $config{cgiurl} =~ m!file:///!;
413 $config{url}="file://".$config{destdir};
416 if ($config{cgi} && ! length $config{url}) {
417 error(gettext("Must specify url to wiki with --url when using --cgi"));
420 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
421 unless exists $config{wikistatedir};
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 && length $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 && length $dir;
444 foreach my $file (glob("$dir/plugins/*")) {
445 $ret{basename($file)}=1 if -x $file;
452 sub loadplugins () { #{{{
453 if (defined $config{libdir} && length $config{libdir}) {
454 unshift @INC, possibly_foolish_untaint($config{libdir});
457 loadplugin($_) foreach @{$config{default_plugins}}, @{$config{add_plugins}};
460 if (exists $IkiWiki::hooks{rcs}) {
461 error(gettext("cannot use multiple rcs plugins"));
463 loadplugin($config{rcs});
465 if (! exists $IkiWiki::hooks{rcs}) {
469 run_hooks(getopt => sub { shift->() });
470 if (grep /^-/, @ARGV) {
471 print STDERR "Unknown option: $_\n"
472 foreach grep /^-/, @ARGV;
479 sub loadplugin ($) { #{{{
482 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
484 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
485 "$installdir/lib/ikiwiki") {
486 if (defined $dir && -x "$dir/plugins/$plugin") {
487 require IkiWiki::Plugin::external;
488 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
493 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
496 error("Failed to load plugin $mod: $@");
501 sub error ($;$) { #{{{
504 log_message('err' => $message) if $config{syslog};
505 if (defined $cleaner) {
512 return unless $config{verbose};
513 return log_message(debug => @_);
517 sub log_message ($$) { #{{{
520 if ($config{syslog}) {
523 Sys::Syslog::setlogsock('unix');
524 Sys::Syslog::openlog('ikiwiki', '', 'user');
528 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
531 elsif (! $config{cgi}) {
535 return print STDERR "@_\n";
539 sub possibly_foolish_untaint ($) { #{{{
541 my ($untainted)=$tainted=~/(.*)/s;
545 sub basename ($) { #{{{
552 sub dirname ($) { #{{{
559 sub pagetype ($) { #{{{
562 if ($page =~ /\.([^.]+)$/) {
563 return $1 if exists $hooks{htmlize}{$1};
568 sub isinternal ($) { #{{{
570 return exists $pagesources{$page} &&
571 $pagesources{$page} =~ /\._([^.]+)$/;
574 sub pagename ($) { #{{{
577 my $type=pagetype($file);
579 $page=~s/\Q.$type\E*$// if defined $type;
583 sub targetpage ($$) { #{{{
587 if (! $config{usedirs} || $page =~ /^index$/ ) {
588 return $page.".".$ext;
590 return $page."/index.".$ext;
594 sub htmlpage ($) { #{{{
597 return targetpage($page, $config{htmlext});
600 sub srcfile_stat { #{{{
604 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
605 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
606 return "$dir/$file", stat(_) if -e "$dir/$file";
608 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
612 sub srcfile ($;$) { #{{{
613 return (srcfile_stat(@_))[0];
616 sub add_underlay ($) { #{{{
620 unshift @{$config{underlaydirs}}, $dir;
623 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
629 sub readfile ($;$$) { #{{{
635 error("cannot read a symlink ($file)");
639 open (my $in, "<", $file) || error("failed to read $file: $!");
640 binmode($in) if ($binary);
641 return \*$in if $wantfd;
643 close $in || error("failed to read $file: $!");
647 sub prep_writefile ($$) { #{{{
652 while (length $test) {
653 if (-l "$destdir/$test") {
654 error("cannot write to a symlink ($test)");
656 $test=dirname($test);
659 my $dir=dirname("$destdir/$file");
662 foreach my $s (split(m!/+!, $dir)) {
665 mkdir($d) || error("failed to create directory $d: $!");
673 sub writefile ($$$;$$) { #{{{
674 my $file=shift; # can include subdirs
675 my $destdir=shift; # directory to put file in
680 prep_writefile($file, $destdir);
682 my $newfile="$destdir/$file.ikiwiki-new";
684 error("cannot write to a symlink ($newfile)");
687 my $cleanup = sub { unlink($newfile) };
688 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
689 binmode($out) if ($binary);
691 $writer->(\*$out, $cleanup);
694 print $out $content or error("failed writing to $newfile: $!", $cleanup);
696 close $out || error("failed saving $newfile: $!", $cleanup);
697 rename($newfile, "$destdir/$file") ||
698 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
704 sub will_render ($$;$) { #{{{
709 # Important security check.
710 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
711 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
712 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
715 if (! $clear || $cleared{$page}) {
716 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
719 foreach my $old (@{$renderedfiles{$page}}) {
720 delete $destsources{$old};
722 $renderedfiles{$page}=[$dest];
725 $destsources{$dest}=$page;
730 sub bestlink ($$) { #{{{
735 if ($link=~s/^\/+//) {
743 $l.="/" if length $l;
746 if (exists $links{$l}) {
749 elsif (exists $pagecase{lc $l}) {
750 return $pagecase{lc $l};
752 } while $cwd=~s!/?[^/]+$!!;
754 if (length $config{userdir}) {
755 my $l = "$config{userdir}/".lc($link);
756 if (exists $links{$l}) {
759 elsif (exists $pagecase{lc $l}) {
760 return $pagecase{lc $l};
764 #print STDERR "warning: page $page, broken link: $link\n";
768 sub isinlinableimage ($) { #{{{
771 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
774 sub pagetitle ($;$) { #{{{
779 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
782 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
788 sub titlepage ($) { #{{{
790 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
794 sub linkpage ($) { #{{{
796 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
800 sub cgiurl (@) { #{{{
803 return $config{cgiurl}."?".
804 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
807 sub baseurl (;$) { #{{{
810 return "$config{url}/" if ! defined $page;
812 $page=htmlpage($page);
814 $page=~s/[^\/]+\//..\//g;
818 sub abs2rel ($$) { #{{{
819 # Work around very innefficient behavior in File::Spec if abs2rel
820 # is passed two relative paths. It's much faster if paths are
821 # absolute! (Debian bug #376658; fixed in debian unstable now)
826 my $ret=File::Spec->abs2rel($path, $base);
827 $ret=~s/^// if defined $ret;
831 sub displaytime ($;$) { #{{{
834 if (! defined $format) {
835 $format=$config{timeformat};
838 # strftime doesn't know about encodings, so make sure
839 # its output is properly treated as utf8
840 return decode_utf8(POSIX::strftime($format, localtime($time)));
843 sub beautify_urlpath ($) { #{{{
846 if ($config{usedirs}) {
847 $url =~ s!/index.$config{htmlext}$!/!;
850 # Ensure url is not an empty link, and
851 # if it's relative, make that explicit to avoid colon confusion.
859 sub urlto ($$;$) { #{{{
865 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
868 if (! $destsources{$to}) {
873 return $config{url}.beautify_urlpath("/".$to);
876 my $link = abs2rel($to, dirname(htmlpage($from)));
878 return beautify_urlpath($link);
881 sub htmllink ($$$;@) { #{{{
882 my $lpage=shift; # the page doing the linking
883 my $page=shift; # the page that will contain the link (different for inline)
890 if (! $opts{forcesubpage}) {
891 $bestlink=bestlink($lpage, $link);
894 $bestlink="$lpage/".lc($link);
898 if (defined $opts{linktext}) {
899 $linktext=$opts{linktext};
902 $linktext=pagetitle(basename($link));
905 return "<span class=\"selflink\">$linktext</span>"
906 if length $bestlink && $page eq $bestlink &&
907 ! defined $opts{anchor};
909 if (! $destsources{$bestlink}) {
910 $bestlink=htmlpage($bestlink);
912 if (! $destsources{$bestlink}) {
913 return $linktext unless length $config{cgiurl};
914 return "<span class=\"createlink\"><a href=\"".
920 "\" rel=\"nofollow\">?</a>$linktext</span>"
924 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
925 $bestlink=beautify_urlpath($bestlink);
927 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
928 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
931 if (defined $opts{anchor}) {
932 $bestlink.="#".$opts{anchor};
936 if (defined $opts{rel}) {
937 push @attrs, ' rel="'.$opts{rel}.'"';
939 if (defined $opts{class}) {
940 push @attrs, ' class="'.$opts{class}.'"';
943 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
946 sub userlink ($) { #{{{
949 my $oiduser=eval { openiduser($user) };
950 if (defined $oiduser) {
951 return "<a href=\"$user\">$oiduser</a>";
954 eval q{use CGI 'escapeHTML'};
957 return htmllink("", "", escapeHTML(
958 length $config{userdir} ? $config{userdir}."/".$user : $user
959 ), noimageinline => 1);
963 sub htmlize ($$$$) { #{{{
969 my $oneline = $content !~ /\n/;
971 if (exists $hooks{htmlize}{$type}) {
972 $content=$hooks{htmlize}{$type}{call}->(
978 error("htmlization of $type not supported");
981 run_hooks(sanitize => sub {
984 destpage => $destpage,
990 # hack to get rid of enclosing junk added by markdown
991 # and other htmlizers
993 $content=~s/<\/p>$//i;
1000 sub linkify ($$$) { #{{{
1005 run_hooks(linkify => sub {
1008 destpage => $destpage,
1009 content => $content,
1017 our $preprocess_preview=0;
1018 sub preprocess ($$$;$$) { #{{{
1019 my $page=shift; # the page the data comes from
1020 my $destpage=shift; # the page the data will appear in (different for inline)
1025 # Using local because it needs to be set within any nested calls
1027 local $preprocess_preview=$preview if defined $preview;
1034 if (length $escape) {
1035 return "[[$prefix$command $params]]";
1037 elsif (exists $hooks{preprocess}{$command}) {
1038 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1039 # Note: preserve order of params, some plugins may
1040 # consider it significant.
1042 while ($params =~ m{
1043 (?:([-\w]+)=)? # 1: named parameter key?
1045 """(.*?)""" # 2: triple-quoted value
1047 "([^"]+)" # 3: single-quoted value
1049 (\S+) # 4: unquoted value
1051 (?:\s+|$) # delimiter to next param
1061 elsif (defined $3) {
1064 elsif (defined $4) {
1069 push @params, $key, $val;
1072 push @params, $val, '';
1075 if ($preprocessing{$page}++ > 3) {
1076 # Avoid loops of preprocessed pages preprocessing
1077 # other pages that preprocess them, etc.
1078 return "[[!$command <span class=\"error\">".
1079 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1080 $page, $preprocessing{$page}).
1086 $hooks{preprocess}{$command}{call}->(
1089 destpage => $destpage,
1090 preview => $preprocess_preview,
1095 $ret="[[!$command <span class=\"error\">".
1096 gettext("Error").": $@"."</span>]]";
1100 # use void context during scan pass
1102 $hooks{preprocess}{$command}{call}->(
1105 destpage => $destpage,
1106 preview => $preprocess_preview,
1111 $preprocessing{$page}--;
1115 return "[[$prefix$command $params]]";
1120 if ($config{prefix_directives}) {
1123 \[\[(!) # directive open; 2: prefix
1124 ([-\w]+) # 3: command
1125 ( # 4: the parameters..
1126 \s+ # Must have space if parameters present
1128 (?:[-\w]+=)? # named parameter key?
1130 """.*?""" # triple-quoted value
1132 "[^"]+" # single-quoted value
1134 [^\s\]]+ # unquoted value
1136 \s* # whitespace or end
1139 *)? # 0 or more parameters
1140 \]\] # directive closed
1146 \[\[(!?) # directive open; 2: optional prefix
1147 ([-\w]+) # 3: command
1149 ( # 4: the parameters..
1151 (?:[-\w]+=)? # named parameter key?
1153 """.*?""" # triple-quoted value
1155 "[^"]+" # single-quoted value
1157 [^\s\]]+ # unquoted value
1159 \s* # whitespace or end
1162 *) # 0 or more parameters
1163 \]\] # directive closed
1167 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1171 sub filter ($$$) { #{{{
1176 run_hooks(filter => sub {
1177 $content=shift->(page => $page, destpage => $destpage,
1178 content => $content);
1184 sub indexlink () { #{{{
1185 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1190 sub lockwiki (;$) { #{{{
1191 my $wait=@_ ? shift : 1;
1192 # Take an exclusive lock on the wiki to prevent multiple concurrent
1193 # run issues. The lock will be dropped on program exit.
1194 if (! -d $config{wikistatedir}) {
1195 mkdir($config{wikistatedir});
1197 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1198 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1199 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1201 debug("wiki seems to be locked, waiting for lock");
1202 my $wait=600; # arbitrary, but don't hang forever to
1203 # prevent process pileup
1205 return if flock($wikilock, 2 | 4);
1208 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1217 sub unlockwiki () { #{{{
1218 return close($wikilock) if $wikilock;
1224 sub commit_hook_enabled () { #{{{
1225 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1226 error("cannot write to $config{wikistatedir}/commitlock: $!");
1227 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1228 close($commitlock) || error("failed closing commitlock: $!");
1231 close($commitlock) || error("failed closing commitlock: $!");
1235 sub disable_commit_hook () { #{{{
1236 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1237 error("cannot write to $config{wikistatedir}/commitlock: $!");
1238 if (! flock($commitlock, 2)) { # LOCK_EX
1239 error("failed to get commit lock");
1244 sub enable_commit_hook () { #{{{
1245 return close($commitlock) if $commitlock;
1249 sub loadindex () { #{{{
1250 %oldrenderedfiles=%pagectime=();
1251 if (! $config{rebuild}) {
1252 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1253 %destsources=%renderedfiles=%pagecase=%pagestate=();
1256 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1257 if (-e "$config{wikistatedir}/index") {
1258 system("ikiwiki-transition", "indexdb", $config{srcdir});
1259 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1265 my $ret=Storable::fd_retrieve($in);
1266 if (! defined $ret) {
1270 foreach my $src (keys %index) {
1271 my %d=%{$index{$src}};
1272 my $page=pagename($src);
1273 $pagectime{$page}=$d{ctime};
1274 if (! $config{rebuild}) {
1275 $pagesources{$page}=$src;
1276 $pagemtime{$page}=$d{mtime};
1277 $renderedfiles{$page}=$d{dest};
1278 if (exists $d{links} && ref $d{links}) {
1279 $links{$page}=$d{links};
1280 $oldlinks{$page}=[@{$d{links}}];
1282 if (exists $d{depends}) {
1283 $depends{$page}=$d{depends};
1285 if (exists $d{state}) {
1286 $pagestate{$page}=$d{state};
1289 $oldrenderedfiles{$page}=[@{$d{dest}}];
1291 foreach my $page (keys %pagesources) {
1292 $pagecase{lc $page}=$page;
1294 foreach my $page (keys %renderedfiles) {
1295 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1300 sub saveindex () { #{{{
1301 run_hooks(savestate => sub { shift->() });
1304 foreach my $type (keys %hooks) {
1305 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1307 my @hookids=keys %hookids;
1309 if (! -d $config{wikistatedir}) {
1310 mkdir($config{wikistatedir});
1312 my $newfile="$config{wikistatedir}/indexdb.new";
1313 my $cleanup = sub { unlink($newfile) };
1314 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1316 foreach my $page (keys %pagemtime) {
1317 next unless $pagemtime{$page};
1318 my $src=$pagesources{$page};
1321 ctime => $pagectime{$page},
1322 mtime => $pagemtime{$page},
1323 dest => $renderedfiles{$page},
1324 links => $links{$page},
1327 if (exists $depends{$page}) {
1328 $index{$src}{depends} = $depends{$page};
1331 if (exists $pagestate{$page}) {
1332 foreach my $id (@hookids) {
1333 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1334 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1339 my $ret=Storable::nstore_fd(\%index, $out);
1340 return if ! defined $ret || ! $ret;
1341 close $out || error("failed saving to $newfile: $!", $cleanup);
1342 rename($newfile, "$config{wikistatedir}/indexdb") ||
1343 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1348 sub template_file ($) { #{{{
1351 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1352 return "$dir/$template" if -e "$dir/$template";
1357 sub template_params (@) { #{{{
1358 my $filename=template_file(shift);
1360 if (! defined $filename) {
1361 return if wantarray;
1367 my $text_ref = shift;
1368 ${$text_ref} = decode_utf8(${$text_ref});
1370 filename => $filename,
1371 loop_context_vars => 1,
1372 die_on_bad_params => 0,
1375 return wantarray ? @ret : {@ret};
1378 sub template ($;@) { #{{{
1379 require HTML::Template;
1380 return HTML::Template->new(template_params(@_));
1383 sub misctemplate ($$;@) { #{{{
1387 my $template=template("misc.tmpl");
1390 indexlink => indexlink(),
1391 wikiname => $config{wikiname},
1392 pagebody => $pagebody,
1393 baseurl => baseurl(),
1396 run_hooks(pagetemplate => sub {
1397 shift->(page => "", destpage => "", template => $template);
1399 return $template->output;
1402 sub hook (@) { # {{{
1405 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1406 error 'hook requires type, call, and id parameters';
1409 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1411 $hooks{$param{type}}{$param{id}}=\%param;
1415 sub run_hooks ($$) { # {{{
1416 # Calls the given sub for each hook of the given type,
1417 # passing it the hook function to call.
1421 if (exists $hooks{$type}) {
1423 foreach my $id (keys %{$hooks{$type}}) {
1424 if ($hooks{$type}{$id}{last}) {
1425 push @deferred, $id;
1428 $sub->($hooks{$type}{$id}{call});
1430 foreach my $id (@deferred) {
1431 $sub->($hooks{$type}{$id}{call});
1438 sub rcs_update () { #{{{
1439 $hooks{rcs}{rcs_update}{call}->(@_);
1442 sub rcs_prepedit ($) { #{{{
1443 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1446 sub rcs_commit ($$$;$$) { #{{{
1447 $hooks{rcs}{rcs_commit}{call}->(@_);
1450 sub rcs_commit_staged ($$$) { #{{{
1451 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1454 sub rcs_add ($) { #{{{
1455 $hooks{rcs}{rcs_add}{call}->(@_);
1458 sub rcs_remove ($) { #{{{
1459 $hooks{rcs}{rcs_remove}{call}->(@_);
1462 sub rcs_rename ($$) { #{{{
1463 $hooks{rcs}{rcs_rename}{call}->(@_);
1466 sub rcs_recentchanges ($) { #{{{
1467 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1470 sub rcs_diff ($) { #{{{
1471 $hooks{rcs}{rcs_diff}{call}->(@_);
1474 sub rcs_getctime ($) { #{{{
1475 $hooks{rcs}{rcs_getctime}{call}->(@_);
1478 sub globlist_to_pagespec ($) { #{{{
1479 my @globlist=split(' ', shift);
1482 foreach my $glob (@globlist) {
1483 if ($glob=~/^!(.*)/) {
1491 my $spec=join(' or ', @spec);
1493 my $skip=join(' and ', @skip);
1495 $spec="$skip and ($spec)";
1504 sub is_globlist ($) { #{{{
1506 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1509 sub safequote ($) { #{{{
1515 sub add_depends ($$) { #{{{
1519 return unless pagespec_valid($pagespec);
1521 if (! exists $depends{$page}) {
1522 $depends{$page}=$pagespec;
1525 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1531 sub file_pruned ($$) { #{{{
1533 my $file=File::Spec->canonpath(shift);
1534 my $base=File::Spec->canonpath(shift);
1535 $file =~ s#^\Q$base\E/+##;
1537 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1538 return $file =~ m/$regexp/ && $file ne $base;
1542 # Only use gettext in the rare cases it's needed.
1543 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1544 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1545 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1546 if (! $gettext_obj) {
1547 $gettext_obj=eval q{
1548 use Locale::gettext q{textdomain};
1549 Locale::gettext->domain('ikiwiki')
1557 return $gettext_obj->get(shift);
1564 sub yesno ($) { #{{{
1567 return (defined $val && lc($val) eq gettext("yes"));
1570 sub pagespec_merge ($$) { #{{{
1574 return $a if $a eq $b;
1576 # Support for old-style GlobLists.
1577 if (is_globlist($a)) {
1578 $a=globlist_to_pagespec($a);
1580 if (is_globlist($b)) {
1581 $b=globlist_to_pagespec($b);
1584 return "($a) or ($b)";
1587 sub pagespec_translate ($) { #{{{
1590 # Support for old-style GlobLists.
1591 if (is_globlist($spec)) {
1592 $spec=globlist_to_pagespec($spec);
1595 # Convert spec to perl code.
1598 \s* # ignore whitespace
1599 ( # 1: match a single word
1606 \w+\([^\)]*\) # command(params)
1608 [^\s()]+ # any other text
1610 \s* # ignore whitespace
1613 if (lc $word eq 'and') {
1616 elsif (lc $word eq 'or') {
1619 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1622 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1623 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1624 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1631 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1635 if (! length $code) {
1640 return eval 'sub { my $page=shift; '.$code.' }';
1643 sub pagespec_match ($$;@) { #{{{
1648 # Backwards compatability with old calling convention.
1650 unshift @params, 'location';
1653 my $sub=pagespec_translate($spec);
1654 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1655 return $sub->($page, @params);
1658 sub pagespec_valid ($) { #{{{
1661 my $sub=pagespec_translate($spec);
1665 sub glob2re ($) { #{{{
1666 my $re=quotemeta(shift);
1672 package IkiWiki::FailReason;
1675 '""' => sub { ${$_[0]} },
1677 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1684 return bless \$value, $class;
1687 package IkiWiki::SuccessReason;
1690 '""' => sub { ${$_[0]} },
1692 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1699 return bless \$value, $class;
1702 package IkiWiki::PageSpec;
1704 sub match_glob ($$;@) { #{{{
1709 my $from=exists $params{location} ? $params{location} : '';
1712 if ($glob =~ m!^\./!) {
1713 $from=~s#/?[^/]+$##;
1715 $glob="$from/$glob" if length $from;
1718 my $regexp=IkiWiki::glob2re($glob);
1719 if ($page=~/^$regexp$/i) {
1720 if (! IkiWiki::isinternal($page) || $params{internal}) {
1721 return IkiWiki::SuccessReason->new("$glob matches $page");
1724 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1728 return IkiWiki::FailReason->new("$glob does not match $page");
1732 sub match_internal ($$;@) { #{{{
1733 return match_glob($_[0], $_[1], @_, internal => 1)
1736 sub match_link ($$;@) { #{{{
1741 my $from=exists $params{location} ? $params{location} : '';
1744 if ($link =~ m!^\.! && defined $from) {
1745 $from=~s#/?[^/]+$##;
1747 $link="$from/$link" if length $from;
1750 my $links = $IkiWiki::links{$page};
1751 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1752 my $bestlink = IkiWiki::bestlink($from, $link);
1753 foreach my $p (@{$links}) {
1754 if (length $bestlink) {
1755 return IkiWiki::SuccessReason->new("$page links to $link")
1756 if $bestlink eq IkiWiki::bestlink($page, $p);
1759 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1760 if match_glob($p, $link, %params);
1763 return IkiWiki::FailReason->new("$page does not link to $link");
1766 sub match_backlink ($$;@) { #{{{
1767 return match_link($_[1], $_[0], @_);
1770 sub match_created_before ($$;@) { #{{{
1774 if (exists $IkiWiki::pagectime{$testpage}) {
1775 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1776 return IkiWiki::SuccessReason->new("$page created before $testpage");
1779 return IkiWiki::FailReason->new("$page not created before $testpage");
1783 return IkiWiki::FailReason->new("$testpage has no ctime");
1787 sub match_created_after ($$;@) { #{{{
1791 if (exists $IkiWiki::pagectime{$testpage}) {
1792 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1793 return IkiWiki::SuccessReason->new("$page created after $testpage");
1796 return IkiWiki::FailReason->new("$page not created after $testpage");
1800 return IkiWiki::FailReason->new("$testpage has no ctime");
1804 sub match_creation_day ($$;@) { #{{{
1805 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1806 return IkiWiki::SuccessReason->new('creation_day matched');
1809 return IkiWiki::FailReason->new('creation_day did not match');
1813 sub match_creation_month ($$;@) { #{{{
1814 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1815 return IkiWiki::SuccessReason->new('creation_month matched');
1818 return IkiWiki::FailReason->new('creation_month did not match');
1822 sub match_creation_year ($$;@) { #{{{
1823 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1824 return IkiWiki::SuccessReason->new('creation_year matched');
1827 return IkiWiki::FailReason->new('creation_year did not match');