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 setup mode",
367 description => "running in refresh mode",
374 description => "running in getctime mode",
381 description => "running in w3mmode",
388 description => "path to setup file",
394 sub defaultconfig () { #{{{
397 foreach my $key (keys %s) {
398 push @ret, $key, $s{$key}->{default};
404 sub checkconfig () { #{{{
405 # locale stuff; avoid LC_ALL since it overrides everything
406 if (defined $ENV{LC_ALL}) {
407 $ENV{LANG} = $ENV{LC_ALL};
410 if (defined $config{locale}) {
411 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
412 $ENV{LANG}=$config{locale};
417 if (ref $config{ENV} eq 'HASH') {
418 foreach my $val (keys %{$config{ENV}}) {
419 $ENV{$val}=$config{ENV}{$val};
423 if ($config{w3mmode}) {
424 eval q{use Cwd q{abs_path}};
426 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
427 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
428 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
429 unless $config{cgiurl} =~ m!file:///!;
430 $config{url}="file://".$config{destdir};
433 if ($config{cgi} && ! length $config{url}) {
434 error(gettext("Must specify url to wiki with --url when using --cgi"));
437 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
438 unless exists $config{wikistatedir};
440 if (defined $config{umask}) {
441 umask(possibly_foolish_untaint($config{umask}));
444 run_hooks(checkconfig => sub { shift->() });
449 sub listplugins () { #{{{
452 foreach my $dir (@INC, $config{libdir}) {
453 next unless defined $dir && length $dir;
454 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
455 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
459 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
460 next unless defined $dir && length $dir;
461 foreach my $file (glob("$dir/plugins/*")) {
462 $ret{basename($file)}=1 if -x $file;
469 sub loadplugins () { #{{{
470 if (defined $config{libdir} && length $config{libdir}) {
471 unshift @INC, possibly_foolish_untaint($config{libdir});
474 loadplugin($_) foreach @{$config{default_plugins}}, @{$config{add_plugins}};
477 if (exists $IkiWiki::hooks{rcs}) {
478 error(gettext("cannot use multiple rcs plugins"));
480 loadplugin($config{rcs});
482 if (! exists $IkiWiki::hooks{rcs}) {
486 run_hooks(getopt => sub { shift->() });
487 if (grep /^-/, @ARGV) {
488 print STDERR "Unknown option: $_\n"
489 foreach grep /^-/, @ARGV;
496 sub loadplugin ($) { #{{{
499 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
501 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
502 "$installdir/lib/ikiwiki") {
503 if (defined $dir && -x "$dir/plugins/$plugin") {
504 require IkiWiki::Plugin::external;
505 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
506 $loaded_plugins{$plugin}=1;
511 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
514 error("Failed to load plugin $mod: $@");
516 $loaded_plugins{$plugin}=1;
520 sub error ($;$) { #{{{
523 log_message('err' => $message) if $config{syslog};
524 if (defined $cleaner) {
531 return unless $config{verbose};
532 return log_message(debug => @_);
536 sub log_message ($$) { #{{{
539 if ($config{syslog}) {
542 Sys::Syslog::setlogsock('unix');
543 Sys::Syslog::openlog('ikiwiki', '', 'user');
547 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
550 elsif (! $config{cgi}) {
554 return print STDERR "@_\n";
558 sub possibly_foolish_untaint ($) { #{{{
560 my ($untainted)=$tainted=~/(.*)/s;
564 sub basename ($) { #{{{
571 sub dirname ($) { #{{{
578 sub pagetype ($) { #{{{
581 if ($page =~ /\.([^.]+)$/) {
582 return $1 if exists $hooks{htmlize}{$1};
587 sub isinternal ($) { #{{{
589 return exists $pagesources{$page} &&
590 $pagesources{$page} =~ /\._([^.]+)$/;
593 sub pagename ($) { #{{{
596 my $type=pagetype($file);
598 $page=~s/\Q.$type\E*$// if defined $type;
602 sub targetpage ($$) { #{{{
606 if (! $config{usedirs} || $page =~ /^index$/ ) {
607 return $page.".".$ext;
609 return $page."/index.".$ext;
613 sub htmlpage ($) { #{{{
616 return targetpage($page, $config{htmlext});
619 sub srcfile_stat { #{{{
623 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
624 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
625 return "$dir/$file", stat(_) if -e "$dir/$file";
627 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
631 sub srcfile ($;$) { #{{{
632 return (srcfile_stat(@_))[0];
635 sub add_underlay ($) { #{{{
639 unshift @{$config{underlaydirs}}, $dir;
642 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
648 sub readfile ($;$$) { #{{{
654 error("cannot read a symlink ($file)");
658 open (my $in, "<", $file) || error("failed to read $file: $!");
659 binmode($in) if ($binary);
660 return \*$in if $wantfd;
662 close $in || error("failed to read $file: $!");
666 sub prep_writefile ($$) { #{{{
671 while (length $test) {
672 if (-l "$destdir/$test") {
673 error("cannot write to a symlink ($test)");
675 $test=dirname($test);
678 my $dir=dirname("$destdir/$file");
681 foreach my $s (split(m!/+!, $dir)) {
684 mkdir($d) || error("failed to create directory $d: $!");
692 sub writefile ($$$;$$) { #{{{
693 my $file=shift; # can include subdirs
694 my $destdir=shift; # directory to put file in
699 prep_writefile($file, $destdir);
701 my $newfile="$destdir/$file.ikiwiki-new";
703 error("cannot write to a symlink ($newfile)");
706 my $cleanup = sub { unlink($newfile) };
707 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
708 binmode($out) if ($binary);
710 $writer->(\*$out, $cleanup);
713 print $out $content or error("failed writing to $newfile: $!", $cleanup);
715 close $out || error("failed saving $newfile: $!", $cleanup);
716 rename($newfile, "$destdir/$file") ||
717 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
723 sub will_render ($$;$) { #{{{
728 # Important security check.
729 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
730 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
731 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
734 if (! $clear || $cleared{$page}) {
735 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
738 foreach my $old (@{$renderedfiles{$page}}) {
739 delete $destsources{$old};
741 $renderedfiles{$page}=[$dest];
744 $destsources{$dest}=$page;
749 sub bestlink ($$) { #{{{
754 if ($link=~s/^\/+//) {
762 $l.="/" if length $l;
765 if (exists $links{$l}) {
768 elsif (exists $pagecase{lc $l}) {
769 return $pagecase{lc $l};
771 } while $cwd=~s!/?[^/]+$!!;
773 if (length $config{userdir}) {
774 my $l = "$config{userdir}/".lc($link);
775 if (exists $links{$l}) {
778 elsif (exists $pagecase{lc $l}) {
779 return $pagecase{lc $l};
783 #print STDERR "warning: page $page, broken link: $link\n";
787 sub isinlinableimage ($) { #{{{
790 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
793 sub pagetitle ($;$) { #{{{
798 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
801 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
807 sub titlepage ($) { #{{{
809 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
813 sub linkpage ($) { #{{{
815 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
819 sub cgiurl (@) { #{{{
822 return $config{cgiurl}."?".
823 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
826 sub baseurl (;$) { #{{{
829 return "$config{url}/" if ! defined $page;
831 $page=htmlpage($page);
833 $page=~s/[^\/]+\//..\//g;
837 sub abs2rel ($$) { #{{{
838 # Work around very innefficient behavior in File::Spec if abs2rel
839 # is passed two relative paths. It's much faster if paths are
840 # absolute! (Debian bug #376658; fixed in debian unstable now)
845 my $ret=File::Spec->abs2rel($path, $base);
846 $ret=~s/^// if defined $ret;
850 sub displaytime ($;$) { #{{{
853 if (! defined $format) {
854 $format=$config{timeformat};
857 # strftime doesn't know about encodings, so make sure
858 # its output is properly treated as utf8
859 return decode_utf8(POSIX::strftime($format, localtime($time)));
862 sub beautify_urlpath ($) { #{{{
865 if ($config{usedirs}) {
866 $url =~ s!/index.$config{htmlext}$!/!;
869 # Ensure url is not an empty link, and
870 # if it's relative, make that explicit to avoid colon confusion.
878 sub urlto ($$;$) { #{{{
884 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
887 if (! $destsources{$to}) {
892 return $config{url}.beautify_urlpath("/".$to);
895 my $link = abs2rel($to, dirname(htmlpage($from)));
897 return beautify_urlpath($link);
900 sub htmllink ($$$;@) { #{{{
901 my $lpage=shift; # the page doing the linking
902 my $page=shift; # the page that will contain the link (different for inline)
909 if (! $opts{forcesubpage}) {
910 $bestlink=bestlink($lpage, $link);
913 $bestlink="$lpage/".lc($link);
917 if (defined $opts{linktext}) {
918 $linktext=$opts{linktext};
921 $linktext=pagetitle(basename($link));
924 return "<span class=\"selflink\">$linktext</span>"
925 if length $bestlink && $page eq $bestlink &&
926 ! defined $opts{anchor};
928 if (! $destsources{$bestlink}) {
929 $bestlink=htmlpage($bestlink);
931 if (! $destsources{$bestlink}) {
932 return $linktext unless length $config{cgiurl};
933 return "<span class=\"createlink\"><a href=\"".
939 "\" rel=\"nofollow\">?</a>$linktext</span>"
943 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
944 $bestlink=beautify_urlpath($bestlink);
946 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
947 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
950 if (defined $opts{anchor}) {
951 $bestlink.="#".$opts{anchor};
955 if (defined $opts{rel}) {
956 push @attrs, ' rel="'.$opts{rel}.'"';
958 if (defined $opts{class}) {
959 push @attrs, ' class="'.$opts{class}.'"';
962 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
965 sub userlink ($) { #{{{
968 my $oiduser=eval { openiduser($user) };
969 if (defined $oiduser) {
970 return "<a href=\"$user\">$oiduser</a>";
973 eval q{use CGI 'escapeHTML'};
976 return htmllink("", "", escapeHTML(
977 length $config{userdir} ? $config{userdir}."/".$user : $user
978 ), noimageinline => 1);
982 sub htmlize ($$$$) { #{{{
988 my $oneline = $content !~ /\n/;
990 if (exists $hooks{htmlize}{$type}) {
991 $content=$hooks{htmlize}{$type}{call}->(
997 error("htmlization of $type not supported");
1000 run_hooks(sanitize => sub {
1003 destpage => $destpage,
1004 content => $content,
1009 # hack to get rid of enclosing junk added by markdown
1010 # and other htmlizers
1011 $content=~s/^<p>//i;
1012 $content=~s/<\/p>$//i;
1019 sub linkify ($$$) { #{{{
1024 run_hooks(linkify => sub {
1027 destpage => $destpage,
1028 content => $content,
1036 our $preprocess_preview=0;
1037 sub preprocess ($$$;$$) { #{{{
1038 my $page=shift; # the page the data comes from
1039 my $destpage=shift; # the page the data will appear in (different for inline)
1044 # Using local because it needs to be set within any nested calls
1046 local $preprocess_preview=$preview if defined $preview;
1053 $params="" if ! defined $params;
1055 if (length $escape) {
1056 return "[[$prefix$command $params]]";
1058 elsif (exists $hooks{preprocess}{$command}) {
1059 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1060 # Note: preserve order of params, some plugins may
1061 # consider it significant.
1063 while ($params =~ m{
1064 (?:([-\w]+)=)? # 1: named parameter key?
1066 """(.*?)""" # 2: triple-quoted value
1068 "([^"]+)" # 3: single-quoted value
1070 (\S+) # 4: unquoted value
1072 (?:\s+|$) # delimiter to next param
1082 elsif (defined $3) {
1085 elsif (defined $4) {
1090 push @params, $key, $val;
1093 push @params, $val, '';
1096 if ($preprocessing{$page}++ > 3) {
1097 # Avoid loops of preprocessed pages preprocessing
1098 # other pages that preprocess them, etc.
1099 return "[[!$command <span class=\"error\">".
1100 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1101 $page, $preprocessing{$page}).
1107 $hooks{preprocess}{$command}{call}->(
1110 destpage => $destpage,
1111 preview => $preprocess_preview,
1116 $ret="[[!$command <span class=\"error\">".
1117 gettext("Error").": $@"."</span>]]";
1121 # use void context during scan pass
1123 $hooks{preprocess}{$command}{call}->(
1126 destpage => $destpage,
1127 preview => $preprocess_preview,
1132 $preprocessing{$page}--;
1136 return "[[$prefix$command $params]]";
1141 if ($config{prefix_directives}) {
1144 \[\[(!) # directive open; 2: prefix
1145 ([-\w]+) # 3: command
1146 ( # 4: the parameters..
1147 \s+ # Must have space if parameters present
1149 (?:[-\w]+=)? # named parameter key?
1151 """.*?""" # triple-quoted value
1153 "[^"]+" # single-quoted value
1155 [^\s\]]+ # unquoted value
1157 \s* # whitespace or end
1160 *)? # 0 or more parameters
1161 \]\] # directive closed
1167 \[\[(!?) # directive open; 2: optional prefix
1168 ([-\w]+) # 3: command
1170 ( # 4: the parameters..
1172 (?:[-\w]+=)? # named parameter key?
1174 """.*?""" # triple-quoted value
1176 "[^"]+" # single-quoted value
1178 [^\s\]]+ # unquoted value
1180 \s* # whitespace or end
1183 *) # 0 or more parameters
1184 \]\] # directive closed
1188 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1192 sub filter ($$$) { #{{{
1197 run_hooks(filter => sub {
1198 $content=shift->(page => $page, destpage => $destpage,
1199 content => $content);
1205 sub indexlink () { #{{{
1206 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1211 sub lockwiki (;$) { #{{{
1212 my $wait=@_ ? shift : 1;
1213 # Take an exclusive lock on the wiki to prevent multiple concurrent
1214 # run issues. The lock will be dropped on program exit.
1215 if (! -d $config{wikistatedir}) {
1216 mkdir($config{wikistatedir});
1218 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1219 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1220 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1222 debug("wiki seems to be locked, waiting for lock");
1223 my $wait=600; # arbitrary, but don't hang forever to
1224 # prevent process pileup
1226 return if flock($wikilock, 2 | 4);
1229 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1238 sub unlockwiki () { #{{{
1239 return close($wikilock) if $wikilock;
1245 sub commit_hook_enabled () { #{{{
1246 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1247 error("cannot write to $config{wikistatedir}/commitlock: $!");
1248 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1249 close($commitlock) || error("failed closing commitlock: $!");
1252 close($commitlock) || error("failed closing commitlock: $!");
1256 sub disable_commit_hook () { #{{{
1257 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1258 error("cannot write to $config{wikistatedir}/commitlock: $!");
1259 if (! flock($commitlock, 2)) { # LOCK_EX
1260 error("failed to get commit lock");
1265 sub enable_commit_hook () { #{{{
1266 return close($commitlock) if $commitlock;
1270 sub loadindex () { #{{{
1271 %oldrenderedfiles=%pagectime=();
1272 if (! $config{rebuild}) {
1273 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1274 %destsources=%renderedfiles=%pagecase=%pagestate=();
1277 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1278 if (-e "$config{wikistatedir}/index") {
1279 system("ikiwiki-transition", "indexdb", $config{srcdir});
1280 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1286 my $ret=Storable::fd_retrieve($in);
1287 if (! defined $ret) {
1291 foreach my $src (keys %index) {
1292 my %d=%{$index{$src}};
1293 my $page=pagename($src);
1294 $pagectime{$page}=$d{ctime};
1295 if (! $config{rebuild}) {
1296 $pagesources{$page}=$src;
1297 $pagemtime{$page}=$d{mtime};
1298 $renderedfiles{$page}=$d{dest};
1299 if (exists $d{links} && ref $d{links}) {
1300 $links{$page}=$d{links};
1301 $oldlinks{$page}=[@{$d{links}}];
1303 if (exists $d{depends}) {
1304 $depends{$page}=$d{depends};
1306 if (exists $d{state}) {
1307 $pagestate{$page}=$d{state};
1310 $oldrenderedfiles{$page}=[@{$d{dest}}];
1312 foreach my $page (keys %pagesources) {
1313 $pagecase{lc $page}=$page;
1315 foreach my $page (keys %renderedfiles) {
1316 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1321 sub saveindex () { #{{{
1322 run_hooks(savestate => sub { shift->() });
1325 foreach my $type (keys %hooks) {
1326 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1328 my @hookids=keys %hookids;
1330 if (! -d $config{wikistatedir}) {
1331 mkdir($config{wikistatedir});
1333 my $newfile="$config{wikistatedir}/indexdb.new";
1334 my $cleanup = sub { unlink($newfile) };
1335 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1337 foreach my $page (keys %pagemtime) {
1338 next unless $pagemtime{$page};
1339 my $src=$pagesources{$page};
1342 ctime => $pagectime{$page},
1343 mtime => $pagemtime{$page},
1344 dest => $renderedfiles{$page},
1345 links => $links{$page},
1348 if (exists $depends{$page}) {
1349 $index{$src}{depends} = $depends{$page};
1352 if (exists $pagestate{$page}) {
1353 foreach my $id (@hookids) {
1354 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1355 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1360 my $ret=Storable::nstore_fd(\%index, $out);
1361 return if ! defined $ret || ! $ret;
1362 close $out || error("failed saving to $newfile: $!", $cleanup);
1363 rename($newfile, "$config{wikistatedir}/indexdb") ||
1364 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1369 sub template_file ($) { #{{{
1372 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1373 return "$dir/$template" if -e "$dir/$template";
1378 sub template_params (@) { #{{{
1379 my $filename=template_file(shift);
1381 if (! defined $filename) {
1382 return if wantarray;
1388 my $text_ref = shift;
1389 ${$text_ref} = decode_utf8(${$text_ref});
1391 filename => $filename,
1392 loop_context_vars => 1,
1393 die_on_bad_params => 0,
1396 return wantarray ? @ret : {@ret};
1399 sub template ($;@) { #{{{
1400 require HTML::Template;
1401 return HTML::Template->new(template_params(@_));
1404 sub misctemplate ($$;@) { #{{{
1408 my $template=template("misc.tmpl");
1411 indexlink => indexlink(),
1412 wikiname => $config{wikiname},
1413 pagebody => $pagebody,
1414 baseurl => baseurl(),
1417 run_hooks(pagetemplate => sub {
1418 shift->(page => "", destpage => "", template => $template);
1420 return $template->output;
1423 sub hook (@) { # {{{
1426 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1427 error 'hook requires type, call, and id parameters';
1430 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1432 $hooks{$param{type}}{$param{id}}=\%param;
1436 sub run_hooks ($$) { # {{{
1437 # Calls the given sub for each hook of the given type,
1438 # passing it the hook function to call.
1442 if (exists $hooks{$type}) {
1444 foreach my $id (keys %{$hooks{$type}}) {
1445 if ($hooks{$type}{$id}{last}) {
1446 push @deferred, $id;
1449 $sub->($hooks{$type}{$id}{call});
1451 foreach my $id (@deferred) {
1452 $sub->($hooks{$type}{$id}{call});
1459 sub rcs_update () { #{{{
1460 $hooks{rcs}{rcs_update}{call}->(@_);
1463 sub rcs_prepedit ($) { #{{{
1464 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1467 sub rcs_commit ($$$;$$) { #{{{
1468 $hooks{rcs}{rcs_commit}{call}->(@_);
1471 sub rcs_commit_staged ($$$) { #{{{
1472 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1475 sub rcs_add ($) { #{{{
1476 $hooks{rcs}{rcs_add}{call}->(@_);
1479 sub rcs_remove ($) { #{{{
1480 $hooks{rcs}{rcs_remove}{call}->(@_);
1483 sub rcs_rename ($$) { #{{{
1484 $hooks{rcs}{rcs_rename}{call}->(@_);
1487 sub rcs_recentchanges ($) { #{{{
1488 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1491 sub rcs_diff ($) { #{{{
1492 $hooks{rcs}{rcs_diff}{call}->(@_);
1495 sub rcs_getctime ($) { #{{{
1496 $hooks{rcs}{rcs_getctime}{call}->(@_);
1499 sub globlist_to_pagespec ($) { #{{{
1500 my @globlist=split(' ', shift);
1503 foreach my $glob (@globlist) {
1504 if ($glob=~/^!(.*)/) {
1512 my $spec=join(' or ', @spec);
1514 my $skip=join(' and ', @skip);
1516 $spec="$skip and ($spec)";
1525 sub is_globlist ($) { #{{{
1527 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1530 sub safequote ($) { #{{{
1536 sub add_depends ($$) { #{{{
1540 return unless pagespec_valid($pagespec);
1542 if (! exists $depends{$page}) {
1543 $depends{$page}=$pagespec;
1546 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1552 sub file_pruned ($$) { #{{{
1554 my $file=File::Spec->canonpath(shift);
1555 my $base=File::Spec->canonpath(shift);
1556 $file =~ s#^\Q$base\E/+##;
1558 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1559 return $file =~ m/$regexp/ && $file ne $base;
1563 # Only use gettext in the rare cases it's needed.
1564 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1565 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1566 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1567 if (! $gettext_obj) {
1568 $gettext_obj=eval q{
1569 use Locale::gettext q{textdomain};
1570 Locale::gettext->domain('ikiwiki')
1578 return $gettext_obj->get(shift);
1585 sub yesno ($) { #{{{
1588 return (defined $val && lc($val) eq gettext("yes"));
1591 sub pagespec_merge ($$) { #{{{
1595 return $a if $a eq $b;
1597 # Support for old-style GlobLists.
1598 if (is_globlist($a)) {
1599 $a=globlist_to_pagespec($a);
1601 if (is_globlist($b)) {
1602 $b=globlist_to_pagespec($b);
1605 return "($a) or ($b)";
1608 sub pagespec_translate ($) { #{{{
1611 # Support for old-style GlobLists.
1612 if (is_globlist($spec)) {
1613 $spec=globlist_to_pagespec($spec);
1616 # Convert spec to perl code.
1619 \s* # ignore whitespace
1620 ( # 1: match a single word
1627 \w+\([^\)]*\) # command(params)
1629 [^\s()]+ # any other text
1631 \s* # ignore whitespace
1634 if (lc $word eq 'and') {
1637 elsif (lc $word eq 'or') {
1640 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1643 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1644 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1645 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1652 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1656 if (! length $code) {
1661 return eval 'sub { my $page=shift; '.$code.' }';
1664 sub pagespec_match ($$;@) { #{{{
1669 # Backwards compatability with old calling convention.
1671 unshift @params, 'location';
1674 my $sub=pagespec_translate($spec);
1675 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1676 return $sub->($page, @params);
1679 sub pagespec_valid ($) { #{{{
1682 my $sub=pagespec_translate($spec);
1686 sub glob2re ($) { #{{{
1687 my $re=quotemeta(shift);
1693 package IkiWiki::FailReason;
1696 '""' => sub { ${$_[0]} },
1698 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1705 return bless \$value, $class;
1708 package IkiWiki::SuccessReason;
1711 '""' => sub { ${$_[0]} },
1713 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1720 return bless \$value, $class;
1723 package IkiWiki::PageSpec;
1725 sub match_glob ($$;@) { #{{{
1730 my $from=exists $params{location} ? $params{location} : '';
1733 if ($glob =~ m!^\./!) {
1734 $from=~s#/?[^/]+$##;
1736 $glob="$from/$glob" if length $from;
1739 my $regexp=IkiWiki::glob2re($glob);
1740 if ($page=~/^$regexp$/i) {
1741 if (! IkiWiki::isinternal($page) || $params{internal}) {
1742 return IkiWiki::SuccessReason->new("$glob matches $page");
1745 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1749 return IkiWiki::FailReason->new("$glob does not match $page");
1753 sub match_internal ($$;@) { #{{{
1754 return match_glob($_[0], $_[1], @_, internal => 1)
1757 sub match_link ($$;@) { #{{{
1762 my $from=exists $params{location} ? $params{location} : '';
1765 if ($link =~ m!^\.! && defined $from) {
1766 $from=~s#/?[^/]+$##;
1768 $link="$from/$link" if length $from;
1771 my $links = $IkiWiki::links{$page};
1772 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1773 my $bestlink = IkiWiki::bestlink($from, $link);
1774 foreach my $p (@{$links}) {
1775 if (length $bestlink) {
1776 return IkiWiki::SuccessReason->new("$page links to $link")
1777 if $bestlink eq IkiWiki::bestlink($page, $p);
1780 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1781 if match_glob($p, $link, %params);
1784 return IkiWiki::FailReason->new("$page does not link to $link");
1787 sub match_backlink ($$;@) { #{{{
1788 return match_link($_[1], $_[0], @_);
1791 sub match_created_before ($$;@) { #{{{
1795 if (exists $IkiWiki::pagectime{$testpage}) {
1796 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1797 return IkiWiki::SuccessReason->new("$page created before $testpage");
1800 return IkiWiki::FailReason->new("$page not created before $testpage");
1804 return IkiWiki::FailReason->new("$testpage has no ctime");
1808 sub match_created_after ($$;@) { #{{{
1812 if (exists $IkiWiki::pagectime{$testpage}) {
1813 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1814 return IkiWiki::SuccessReason->new("$page created after $testpage");
1817 return IkiWiki::FailReason->new("$page not created after $testpage");
1821 return IkiWiki::FailReason->new("$testpage has no ctime");
1825 sub match_creation_day ($$;@) { #{{{
1826 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1827 return IkiWiki::SuccessReason->new('creation_day matched');
1830 return IkiWiki::FailReason->new('creation_day did not match');
1834 sub match_creation_month ($$;@) { #{{{
1835 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1836 return IkiWiki::SuccessReason->new('creation_month matched');
1839 return IkiWiki::FailReason->new('creation_month did not match');
1843 sub match_creation_year ($$;@) { #{{{
1844 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1845 return IkiWiki::SuccessReason->new('creation_year matched');
1848 return IkiWiki::FailReason->new('creation_year did not match');