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
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
21 bestlink htmllink readfile writefile pagetype srcfile pagename
22 displaytime will_render gettext urlto targetpage
24 %config %links %pagestate %renderedfiles
25 %pagesources %destsources);
26 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
27 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
28 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
33 memoize("pagespec_translate");
34 memoize("file_pruned");
36 sub getsetup () { #{{{
40 description => "name of the wiki",
47 example => 'me@example.com',
48 description => "contact email for wiki",
55 description => "users who are wiki admins",
62 description => "users who are banned from the wiki",
69 example => "$ENV{HOME}/wiki",
70 description => "where the source of the wiki is located",
77 example => "/var/www/wiki",
78 description => "where to build the wiki",
85 example => "http://example.com/wiki",
86 description => "base url to the wiki",
93 example => "http://example.com/wiki/ikiwiki.cgi",
94 description => "url to the ikiwiki.cgi",
101 example => "/var/www/wiki/ikiwiki.cgi",
102 description => "cgi wrapper to generate",
109 description => "mode for cgi_wrapper (can safely be made suid)",
116 description => "rcs backend to use",
117 safe => 0, # don't allow overriding
122 default => [qw{mdwn link inline htmlscrubber passwordauth
123 openid signinedit lockedit conditional
124 recentchanges parentlinks}],
125 description => "plugins to enable by default",
132 description => "plugins to add to the default configuration",
139 description => "plugins to disable",
145 default => "$installdir/share/ikiwiki/templates",
146 description => "location of template files",
153 default => "$installdir/share/ikiwiki/basewiki",
154 description => "base wiki source location",
162 description => "wrappers to generate",
169 description => "additional underlays to use",
176 description => "display verbose messages when building?",
183 description => "log to syslog?",
190 description => "create output files named page/index.html?",
191 safe => 0, # changing requires manual transition
194 prefix_directives => {
197 description => "use '!'-prefixed preprocessor directives?",
198 safe => 0, # changing requires manual transition
204 description => "enable Discussion pages?",
211 description => "only send cookies over SSL connections?",
219 description => "extension to use for new pages",
220 safe => 0, # not sanitized
226 description => "extension to use for html files",
227 safe => 0, # not sanitized
233 description => "strftime format string to display date",
241 example => "en_US.UTF-8",
242 description => "UTF-8 locale to use",
251 description => "put user pages below specified page",
258 description => "how many backlinks to show before hiding excess (0 to show all)",
265 description => "attempt to hardlink source files? (optimisation for large files)",
267 safe => 0, # paranoia
274 description => "force ikiwiki to use a particular umask",
276 safe => 0, # paranoia
282 example => "$ENV{HOME}/.ikiwiki/",
283 description => "extra library and plugin directory",
285 safe => 0, # directory
291 description => "environment variables",
292 safe => 0, # paranoia
299 description => "regexp of source files to ignore",
304 wiki_file_prune_regexps => {
306 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
307 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
308 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
311 description => "regexps of source files to ignore",
315 wiki_file_regexp => {
317 default => qr/(^[-[:alnum:]_.:\/+]+$)/,
318 description => "regexp of legal source files",
322 web_commit_regexp => {
324 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
325 description => "regexp to parse web commits from logs",
332 description => "run as a cgi",
336 cgi_disable_uploads => {
339 description => "whether CGI should accept file uploads",
346 description => "run as a post-commit hook",
353 description => "running in rebuild mode",
360 description => "running in refresh mode",
367 description => "running in getctime mode",
374 description => "running in w3mmode",
381 description => "setup file to read",
387 sub defaultconfig () { #{{{
390 foreach my $key (keys %s) {
391 push @ret, $key, $s{$key}->{default};
397 sub checkconfig () { #{{{
398 # locale stuff; avoid LC_ALL since it overrides everything
399 if (defined $ENV{LC_ALL}) {
400 $ENV{LANG} = $ENV{LC_ALL};
403 if (defined $config{locale}) {
404 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
405 $ENV{LANG}=$config{locale};
410 if (ref $config{ENV} eq 'HASH') {
411 foreach my $val (keys %{$config{ENV}}) {
412 $ENV{$val}=$config{ENV}{$val};
416 if ($config{w3mmode}) {
417 eval q{use Cwd q{abs_path}};
419 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
420 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
421 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
422 unless $config{cgiurl} =~ m!file:///!;
423 $config{url}="file://".$config{destdir};
426 if ($config{cgi} && ! length $config{url}) {
427 error(gettext("Must specify url to wiki with --url when using --cgi"));
430 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
431 unless exists $config{wikistatedir};
433 if (defined $config{umask}) {
434 umask(possibly_foolish_untaint($config{umask}));
437 run_hooks(checkconfig => sub { shift->() });
442 sub listplugins () { #{{{
445 foreach my $dir (@INC, $config{libdir}) {
446 next unless defined $dir && length $dir;
447 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
448 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
452 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
453 next unless defined $dir && length $dir;
454 foreach my $file (glob("$dir/plugins/*")) {
455 $ret{basename($file)}=1 if -x $file;
462 sub loadplugins () { #{{{
463 if (defined $config{libdir} && length $config{libdir}) {
464 unshift @INC, possibly_foolish_untaint($config{libdir});
467 loadplugin($_) foreach @{$config{default_plugins}}, @{$config{add_plugins}};
470 if (exists $IkiWiki::hooks{rcs}) {
471 error(gettext("cannot use multiple rcs plugins"));
473 loadplugin($config{rcs});
475 if (! exists $IkiWiki::hooks{rcs}) {
479 run_hooks(getopt => sub { shift->() });
480 if (grep /^-/, @ARGV) {
481 print STDERR "Unknown option: $_\n"
482 foreach grep /^-/, @ARGV;
489 sub loadplugin ($) { #{{{
492 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
494 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
495 "$installdir/lib/ikiwiki") {
496 if (defined $dir && -x "$dir/plugins/$plugin") {
497 require IkiWiki::Plugin::external;
498 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
499 $loaded_plugins{$plugin}=1;
504 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
507 error("Failed to load plugin $mod: $@");
509 $loaded_plugins{$plugin}=1;
513 sub error ($;$) { #{{{
516 log_message('err' => $message) if $config{syslog};
517 if (defined $cleaner) {
524 return unless $config{verbose};
525 return log_message(debug => @_);
529 sub log_message ($$) { #{{{
532 if ($config{syslog}) {
535 Sys::Syslog::setlogsock('unix');
536 Sys::Syslog::openlog('ikiwiki', '', 'user');
540 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
543 elsif (! $config{cgi}) {
547 return print STDERR "@_\n";
551 sub possibly_foolish_untaint ($) { #{{{
553 my ($untainted)=$tainted=~/(.*)/s;
557 sub basename ($) { #{{{
564 sub dirname ($) { #{{{
571 sub pagetype ($) { #{{{
574 if ($page =~ /\.([^.]+)$/) {
575 return $1 if exists $hooks{htmlize}{$1};
580 sub isinternal ($) { #{{{
582 return exists $pagesources{$page} &&
583 $pagesources{$page} =~ /\._([^.]+)$/;
586 sub pagename ($) { #{{{
589 my $type=pagetype($file);
591 $page=~s/\Q.$type\E*$// if defined $type;
595 sub targetpage ($$) { #{{{
599 if (! $config{usedirs} || $page =~ /^index$/ ) {
600 return $page.".".$ext;
602 return $page."/index.".$ext;
606 sub htmlpage ($) { #{{{
609 return targetpage($page, $config{htmlext});
612 sub srcfile_stat { #{{{
616 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
617 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
618 return "$dir/$file", stat(_) if -e "$dir/$file";
620 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
624 sub srcfile ($;$) { #{{{
625 return (srcfile_stat(@_))[0];
628 sub add_underlay ($) { #{{{
632 unshift @{$config{underlaydirs}}, $dir;
635 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
641 sub readfile ($;$$) { #{{{
647 error("cannot read a symlink ($file)");
651 open (my $in, "<", $file) || error("failed to read $file: $!");
652 binmode($in) if ($binary);
653 return \*$in if $wantfd;
655 close $in || error("failed to read $file: $!");
659 sub prep_writefile ($$) { #{{{
664 while (length $test) {
665 if (-l "$destdir/$test") {
666 error("cannot write to a symlink ($test)");
668 $test=dirname($test);
671 my $dir=dirname("$destdir/$file");
674 foreach my $s (split(m!/+!, $dir)) {
677 mkdir($d) || error("failed to create directory $d: $!");
685 sub writefile ($$$;$$) { #{{{
686 my $file=shift; # can include subdirs
687 my $destdir=shift; # directory to put file in
692 prep_writefile($file, $destdir);
694 my $newfile="$destdir/$file.ikiwiki-new";
696 error("cannot write to a symlink ($newfile)");
699 my $cleanup = sub { unlink($newfile) };
700 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
701 binmode($out) if ($binary);
703 $writer->(\*$out, $cleanup);
706 print $out $content or error("failed writing to $newfile: $!", $cleanup);
708 close $out || error("failed saving $newfile: $!", $cleanup);
709 rename($newfile, "$destdir/$file") ||
710 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
716 sub will_render ($$;$) { #{{{
721 # Important security check.
722 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
723 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
724 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
727 if (! $clear || $cleared{$page}) {
728 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
731 foreach my $old (@{$renderedfiles{$page}}) {
732 delete $destsources{$old};
734 $renderedfiles{$page}=[$dest];
737 $destsources{$dest}=$page;
742 sub bestlink ($$) { #{{{
747 if ($link=~s/^\/+//) {
755 $l.="/" if length $l;
758 if (exists $links{$l}) {
761 elsif (exists $pagecase{lc $l}) {
762 return $pagecase{lc $l};
764 } while $cwd=~s!/?[^/]+$!!;
766 if (length $config{userdir}) {
767 my $l = "$config{userdir}/".lc($link);
768 if (exists $links{$l}) {
771 elsif (exists $pagecase{lc $l}) {
772 return $pagecase{lc $l};
776 #print STDERR "warning: page $page, broken link: $link\n";
780 sub isinlinableimage ($) { #{{{
783 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
786 sub pagetitle ($;$) { #{{{
791 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
794 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
800 sub titlepage ($) { #{{{
802 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
806 sub linkpage ($) { #{{{
808 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
812 sub cgiurl (@) { #{{{
815 return $config{cgiurl}."?".
816 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
819 sub baseurl (;$) { #{{{
822 return "$config{url}/" if ! defined $page;
824 $page=htmlpage($page);
826 $page=~s/[^\/]+\//..\//g;
830 sub abs2rel ($$) { #{{{
831 # Work around very innefficient behavior in File::Spec if abs2rel
832 # is passed two relative paths. It's much faster if paths are
833 # absolute! (Debian bug #376658; fixed in debian unstable now)
838 my $ret=File::Spec->abs2rel($path, $base);
839 $ret=~s/^// if defined $ret;
843 sub displaytime ($;$) { #{{{
846 if (! defined $format) {
847 $format=$config{timeformat};
850 # strftime doesn't know about encodings, so make sure
851 # its output is properly treated as utf8
852 return decode_utf8(POSIX::strftime($format, localtime($time)));
855 sub beautify_urlpath ($) { #{{{
858 if ($config{usedirs}) {
859 $url =~ s!/index.$config{htmlext}$!/!;
862 # Ensure url is not an empty link, and
863 # if it's relative, make that explicit to avoid colon confusion.
871 sub urlto ($$;$) { #{{{
877 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
880 if (! $destsources{$to}) {
885 return $config{url}.beautify_urlpath("/".$to);
888 my $link = abs2rel($to, dirname(htmlpage($from)));
890 return beautify_urlpath($link);
893 sub htmllink ($$$;@) { #{{{
894 my $lpage=shift; # the page doing the linking
895 my $page=shift; # the page that will contain the link (different for inline)
902 if (! $opts{forcesubpage}) {
903 $bestlink=bestlink($lpage, $link);
906 $bestlink="$lpage/".lc($link);
910 if (defined $opts{linktext}) {
911 $linktext=$opts{linktext};
914 $linktext=pagetitle(basename($link));
917 return "<span class=\"selflink\">$linktext</span>"
918 if length $bestlink && $page eq $bestlink &&
919 ! defined $opts{anchor};
921 if (! $destsources{$bestlink}) {
922 $bestlink=htmlpage($bestlink);
924 if (! $destsources{$bestlink}) {
925 return $linktext unless length $config{cgiurl};
926 return "<span class=\"createlink\"><a href=\"".
932 "\" rel=\"nofollow\">?</a>$linktext</span>"
936 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
937 $bestlink=beautify_urlpath($bestlink);
939 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
940 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
943 if (defined $opts{anchor}) {
944 $bestlink.="#".$opts{anchor};
948 if (defined $opts{rel}) {
949 push @attrs, ' rel="'.$opts{rel}.'"';
951 if (defined $opts{class}) {
952 push @attrs, ' class="'.$opts{class}.'"';
955 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
958 sub userlink ($) { #{{{
961 my $oiduser=eval { openiduser($user) };
962 if (defined $oiduser) {
963 return "<a href=\"$user\">$oiduser</a>";
966 eval q{use CGI 'escapeHTML'};
969 return htmllink("", "", escapeHTML(
970 length $config{userdir} ? $config{userdir}."/".$user : $user
971 ), noimageinline => 1);
975 sub htmlize ($$$$) { #{{{
981 my $oneline = $content !~ /\n/;
983 if (exists $hooks{htmlize}{$type}) {
984 $content=$hooks{htmlize}{$type}{call}->(
990 error("htmlization of $type not supported");
993 run_hooks(sanitize => sub {
996 destpage => $destpage,
1002 # hack to get rid of enclosing junk added by markdown
1003 # and other htmlizers
1004 $content=~s/^<p>//i;
1005 $content=~s/<\/p>$//i;
1012 sub linkify ($$$) { #{{{
1017 run_hooks(linkify => sub {
1020 destpage => $destpage,
1021 content => $content,
1029 our $preprocess_preview=0;
1030 sub preprocess ($$$;$$) { #{{{
1031 my $page=shift; # the page the data comes from
1032 my $destpage=shift; # the page the data will appear in (different for inline)
1037 # Using local because it needs to be set within any nested calls
1039 local $preprocess_preview=$preview if defined $preview;
1046 $params="" if ! defined $params;
1048 f (length $escape) {
1049 return "[[$prefix$command $params]]";
1051 elsif (exists $hooks{preprocess}{$command}) {
1052 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1053 # Note: preserve order of params, some plugins may
1054 # consider it significant.
1056 while ($params =~ m{
1057 (?:([-\w]+)=)? # 1: named parameter key?
1059 """(.*?)""" # 2: triple-quoted value
1061 "([^"]+)" # 3: single-quoted value
1063 (\S+) # 4: unquoted value
1065 (?:\s+|$) # delimiter to next param
1075 elsif (defined $3) {
1078 elsif (defined $4) {
1083 push @params, $key, $val;
1086 push @params, $val, '';
1089 if ($preprocessing{$page}++ > 3) {
1090 # Avoid loops of preprocessed pages preprocessing
1091 # other pages that preprocess them, etc.
1092 return "[[!$command <span class=\"error\">".
1093 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1094 $page, $preprocessing{$page}).
1100 $hooks{preprocess}{$command}{call}->(
1103 destpage => $destpage,
1104 preview => $preprocess_preview,
1109 $ret="[[!$command <span class=\"error\">".
1110 gettext("Error").": $@"."</span>]]";
1114 # use void context during scan pass
1116 $hooks{preprocess}{$command}{call}->(
1119 destpage => $destpage,
1120 preview => $preprocess_preview,
1125 $preprocessing{$page}--;
1129 return "[[$prefix$command $params]]";
1134 if ($config{prefix_directives}) {
1137 \[\[(!) # directive open; 2: prefix
1138 ([-\w]+) # 3: command
1139 ( # 4: the parameters..
1140 \s+ # Must have space if parameters present
1142 (?:[-\w]+=)? # named parameter key?
1144 """.*?""" # triple-quoted value
1146 "[^"]+" # single-quoted value
1148 [^\s\]]+ # unquoted value
1150 \s* # whitespace or end
1153 *)? # 0 or more parameters
1154 \]\] # directive closed
1160 \[\[(!?) # directive open; 2: optional prefix
1161 ([-\w]+) # 3: command
1163 ( # 4: the parameters..
1165 (?:[-\w]+=)? # named parameter key?
1167 """.*?""" # triple-quoted value
1169 "[^"]+" # single-quoted value
1171 [^\s\]]+ # unquoted value
1173 \s* # whitespace or end
1176 *) # 0 or more parameters
1177 \]\] # directive closed
1181 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1185 sub filter ($$$) { #{{{
1190 run_hooks(filter => sub {
1191 $content=shift->(page => $page, destpage => $destpage,
1192 content => $content);
1198 sub indexlink () { #{{{
1199 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1204 sub lockwiki (;$) { #{{{
1205 my $wait=@_ ? shift : 1;
1206 # Take an exclusive lock on the wiki to prevent multiple concurrent
1207 # run issues. The lock will be dropped on program exit.
1208 if (! -d $config{wikistatedir}) {
1209 mkdir($config{wikistatedir});
1211 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1212 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1213 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1215 debug("wiki seems to be locked, waiting for lock");
1216 my $wait=600; # arbitrary, but don't hang forever to
1217 # prevent process pileup
1219 return if flock($wikilock, 2 | 4);
1222 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1231 sub unlockwiki () { #{{{
1232 return close($wikilock) if $wikilock;
1238 sub commit_hook_enabled () { #{{{
1239 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1240 error("cannot write to $config{wikistatedir}/commitlock: $!");
1241 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1242 close($commitlock) || error("failed closing commitlock: $!");
1245 close($commitlock) || error("failed closing commitlock: $!");
1249 sub disable_commit_hook () { #{{{
1250 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1251 error("cannot write to $config{wikistatedir}/commitlock: $!");
1252 if (! flock($commitlock, 2)) { # LOCK_EX
1253 error("failed to get commit lock");
1258 sub enable_commit_hook () { #{{{
1259 return close($commitlock) if $commitlock;
1263 sub loadindex () { #{{{
1264 %oldrenderedfiles=%pagectime=();
1265 if (! $config{rebuild}) {
1266 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1267 %destsources=%renderedfiles=%pagecase=%pagestate=();
1270 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1271 if (-e "$config{wikistatedir}/index") {
1272 system("ikiwiki-transition", "indexdb", $config{srcdir});
1273 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1279 my $ret=Storable::fd_retrieve($in);
1280 if (! defined $ret) {
1284 foreach my $src (keys %index) {
1285 my %d=%{$index{$src}};
1286 my $page=pagename($src);
1287 $pagectime{$page}=$d{ctime};
1288 if (! $config{rebuild}) {
1289 $pagesources{$page}=$src;
1290 $pagemtime{$page}=$d{mtime};
1291 $renderedfiles{$page}=$d{dest};
1292 if (exists $d{links} && ref $d{links}) {
1293 $links{$page}=$d{links};
1294 $oldlinks{$page}=[@{$d{links}}];
1296 if (exists $d{depends}) {
1297 $depends{$page}=$d{depends};
1299 if (exists $d{state}) {
1300 $pagestate{$page}=$d{state};
1303 $oldrenderedfiles{$page}=[@{$d{dest}}];
1305 foreach my $page (keys %pagesources) {
1306 $pagecase{lc $page}=$page;
1308 foreach my $page (keys %renderedfiles) {
1309 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1314 sub saveindex () { #{{{
1315 run_hooks(savestate => sub { shift->() });
1318 foreach my $type (keys %hooks) {
1319 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1321 my @hookids=keys %hookids;
1323 if (! -d $config{wikistatedir}) {
1324 mkdir($config{wikistatedir});
1326 my $newfile="$config{wikistatedir}/indexdb.new";
1327 my $cleanup = sub { unlink($newfile) };
1328 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1330 foreach my $page (keys %pagemtime) {
1331 next unless $pagemtime{$page};
1332 my $src=$pagesources{$page};
1335 ctime => $pagectime{$page},
1336 mtime => $pagemtime{$page},
1337 dest => $renderedfiles{$page},
1338 links => $links{$page},
1341 if (exists $depends{$page}) {
1342 $index{$src}{depends} = $depends{$page};
1345 if (exists $pagestate{$page}) {
1346 foreach my $id (@hookids) {
1347 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1348 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1353 my $ret=Storable::nstore_fd(\%index, $out);
1354 return if ! defined $ret || ! $ret;
1355 close $out || error("failed saving to $newfile: $!", $cleanup);
1356 rename($newfile, "$config{wikistatedir}/indexdb") ||
1357 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1362 sub template_file ($) { #{{{
1365 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1366 return "$dir/$template" if -e "$dir/$template";
1371 sub template_params (@) { #{{{
1372 my $filename=template_file(shift);
1374 if (! defined $filename) {
1375 return if wantarray;
1381 my $text_ref = shift;
1382 ${$text_ref} = decode_utf8(${$text_ref});
1384 filename => $filename,
1385 loop_context_vars => 1,
1386 die_on_bad_params => 0,
1389 return wantarray ? @ret : {@ret};
1392 sub template ($;@) { #{{{
1393 require HTML::Template;
1394 return HTML::Template->new(template_params(@_));
1397 sub misctemplate ($$;@) { #{{{
1401 my $template=template("misc.tmpl");
1404 indexlink => indexlink(),
1405 wikiname => $config{wikiname},
1406 pagebody => $pagebody,
1407 baseurl => baseurl(),
1410 run_hooks(pagetemplate => sub {
1411 shift->(page => "", destpage => "", template => $template);
1413 return $template->output;
1416 sub hook (@) { # {{{
1419 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1420 error 'hook requires type, call, and id parameters';
1423 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1425 $hooks{$param{type}}{$param{id}}=\%param;
1429 sub run_hooks ($$) { # {{{
1430 # Calls the given sub for each hook of the given type,
1431 # passing it the hook function to call.
1435 if (exists $hooks{$type}) {
1437 foreach my $id (keys %{$hooks{$type}}) {
1438 if ($hooks{$type}{$id}{last}) {
1439 push @deferred, $id;
1442 $sub->($hooks{$type}{$id}{call});
1444 foreach my $id (@deferred) {
1445 $sub->($hooks{$type}{$id}{call});
1452 sub rcs_update () { #{{{
1453 $hooks{rcs}{rcs_update}{call}->(@_);
1456 sub rcs_prepedit ($) { #{{{
1457 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1460 sub rcs_commit ($$$;$$) { #{{{
1461 $hooks{rcs}{rcs_commit}{call}->(@_);
1464 sub rcs_commit_staged ($$$) { #{{{
1465 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1468 sub rcs_add ($) { #{{{
1469 $hooks{rcs}{rcs_add}{call}->(@_);
1472 sub rcs_remove ($) { #{{{
1473 $hooks{rcs}{rcs_remove}{call}->(@_);
1476 sub rcs_rename ($$) { #{{{
1477 $hooks{rcs}{rcs_rename}{call}->(@_);
1480 sub rcs_recentchanges ($) { #{{{
1481 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1484 sub rcs_diff ($) { #{{{
1485 $hooks{rcs}{rcs_diff}{call}->(@_);
1488 sub rcs_getctime ($) { #{{{
1489 $hooks{rcs}{rcs_getctime}{call}->(@_);
1492 sub globlist_to_pagespec ($) { #{{{
1493 my @globlist=split(' ', shift);
1496 foreach my $glob (@globlist) {
1497 if ($glob=~/^!(.*)/) {
1505 my $spec=join(' or ', @spec);
1507 my $skip=join(' and ', @skip);
1509 $spec="$skip and ($spec)";
1518 sub is_globlist ($) { #{{{
1520 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1523 sub safequote ($) { #{{{
1529 sub add_depends ($$) { #{{{
1533 return unless pagespec_valid($pagespec);
1535 if (! exists $depends{$page}) {
1536 $depends{$page}=$pagespec;
1539 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1545 sub file_pruned ($$) { #{{{
1547 my $file=File::Spec->canonpath(shift);
1548 my $base=File::Spec->canonpath(shift);
1549 $file =~ s#^\Q$base\E/+##;
1551 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1552 return $file =~ m/$regexp/ && $file ne $base;
1556 # Only use gettext in the rare cases it's needed.
1557 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1558 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1559 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1560 if (! $gettext_obj) {
1561 $gettext_obj=eval q{
1562 use Locale::gettext q{textdomain};
1563 Locale::gettext->domain('ikiwiki')
1571 return $gettext_obj->get(shift);
1578 sub yesno ($) { #{{{
1581 return (defined $val && lc($val) eq gettext("yes"));
1584 sub pagespec_merge ($$) { #{{{
1588 return $a if $a eq $b;
1590 # Support for old-style GlobLists.
1591 if (is_globlist($a)) {
1592 $a=globlist_to_pagespec($a);
1594 if (is_globlist($b)) {
1595 $b=globlist_to_pagespec($b);
1598 return "($a) or ($b)";
1601 sub pagespec_translate ($) { #{{{
1604 # Support for old-style GlobLists.
1605 if (is_globlist($spec)) {
1606 $spec=globlist_to_pagespec($spec);
1609 # Convert spec to perl code.
1612 \s* # ignore whitespace
1613 ( # 1: match a single word
1620 \w+\([^\)]*\) # command(params)
1622 [^\s()]+ # any other text
1624 \s* # ignore whitespace
1627 if (lc $word eq 'and') {
1630 elsif (lc $word eq 'or') {
1633 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1636 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1637 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1638 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1645 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1649 if (! length $code) {
1654 return eval 'sub { my $page=shift; '.$code.' }';
1657 sub pagespec_match ($$;@) { #{{{
1662 # Backwards compatability with old calling convention.
1664 unshift @params, 'location';
1667 my $sub=pagespec_translate($spec);
1668 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1669 return $sub->($page, @params);
1672 sub pagespec_valid ($) { #{{{
1675 my $sub=pagespec_translate($spec);
1679 sub glob2re ($) { #{{{
1680 my $re=quotemeta(shift);
1686 package IkiWiki::FailReason;
1689 '""' => sub { ${$_[0]} },
1691 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1698 return bless \$value, $class;
1701 package IkiWiki::SuccessReason;
1704 '""' => sub { ${$_[0]} },
1706 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1713 return bless \$value, $class;
1716 package IkiWiki::PageSpec;
1718 sub match_glob ($$;@) { #{{{
1723 my $from=exists $params{location} ? $params{location} : '';
1726 if ($glob =~ m!^\./!) {
1727 $from=~s#/?[^/]+$##;
1729 $glob="$from/$glob" if length $from;
1732 my $regexp=IkiWiki::glob2re($glob);
1733 if ($page=~/^$regexp$/i) {
1734 if (! IkiWiki::isinternal($page) || $params{internal}) {
1735 return IkiWiki::SuccessReason->new("$glob matches $page");
1738 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1742 return IkiWiki::FailReason->new("$glob does not match $page");
1746 sub match_internal ($$;@) { #{{{
1747 return match_glob($_[0], $_[1], @_, internal => 1)
1750 sub match_link ($$;@) { #{{{
1755 my $from=exists $params{location} ? $params{location} : '';
1758 if ($link =~ m!^\.! && defined $from) {
1759 $from=~s#/?[^/]+$##;
1761 $link="$from/$link" if length $from;
1764 my $links = $IkiWiki::links{$page};
1765 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1766 my $bestlink = IkiWiki::bestlink($from, $link);
1767 foreach my $p (@{$links}) {
1768 if (length $bestlink) {
1769 return IkiWiki::SuccessReason->new("$page links to $link")
1770 if $bestlink eq IkiWiki::bestlink($page, $p);
1773 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1774 if match_glob($p, $link, %params);
1777 return IkiWiki::FailReason->new("$page does not link to $link");
1780 sub match_backlink ($$;@) { #{{{
1781 return match_link($_[1], $_[0], @_);
1784 sub match_created_before ($$;@) { #{{{
1788 if (exists $IkiWiki::pagectime{$testpage}) {
1789 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1790 return IkiWiki::SuccessReason->new("$page created before $testpage");
1793 return IkiWiki::FailReason->new("$page not created before $testpage");
1797 return IkiWiki::FailReason->new("$testpage has no ctime");
1801 sub match_created_after ($$;@) { #{{{
1805 if (exists $IkiWiki::pagectime{$testpage}) {
1806 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1807 return IkiWiki::SuccessReason->new("$page created after $testpage");
1810 return IkiWiki::FailReason->new("$page not created after $testpage");
1814 return IkiWiki::FailReason->new("$testpage has no ctime");
1818 sub match_creation_day ($$;@) { #{{{
1819 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1820 return IkiWiki::SuccessReason->new('creation_day matched');
1823 return IkiWiki::FailReason->new('creation_day did not match');
1827 sub match_creation_month ($$;@) { #{{{
1828 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1829 return IkiWiki::SuccessReason->new('creation_month matched');
1832 return IkiWiki::FailReason->new('creation_month did not match');
1836 sub match_creation_year ($$;@) { #{{{
1837 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1838 return IkiWiki::SuccessReason->new('creation_year matched');
1841 return IkiWiki::FailReason->new('creation_year did not match');