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 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
479 if (exists $IkiWiki::hooks{rcs}) {
480 error(gettext("cannot use multiple rcs plugins"));
482 loadplugin($config{rcs});
484 if (! exists $IkiWiki::hooks{rcs}) {
488 run_hooks(getopt => sub { shift->() });
489 if (grep /^-/, @ARGV) {
490 print STDERR "Unknown option: $_\n"
491 foreach grep /^-/, @ARGV;
498 sub loadplugin ($) { #{{{
501 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
503 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
504 "$installdir/lib/ikiwiki") {
505 if (defined $dir && -x "$dir/plugins/$plugin") {
506 require IkiWiki::Plugin::external;
507 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
508 $loaded_plugins{$plugin}=1;
513 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
516 error("Failed to load plugin $mod: $@");
518 $loaded_plugins{$plugin}=1;
522 sub error ($;$) { #{{{
525 log_message('err' => $message) if $config{syslog};
526 if (defined $cleaner) {
533 return unless $config{verbose};
534 return log_message(debug => @_);
538 sub log_message ($$) { #{{{
541 if ($config{syslog}) {
544 Sys::Syslog::setlogsock('unix');
545 Sys::Syslog::openlog('ikiwiki', '', 'user');
549 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
552 elsif (! $config{cgi}) {
556 return print STDERR "@_\n";
560 sub possibly_foolish_untaint ($) { #{{{
562 my ($untainted)=$tainted=~/(.*)/s;
566 sub basename ($) { #{{{
573 sub dirname ($) { #{{{
580 sub pagetype ($) { #{{{
583 if ($page =~ /\.([^.]+)$/) {
584 return $1 if exists $hooks{htmlize}{$1};
589 sub isinternal ($) { #{{{
591 return exists $pagesources{$page} &&
592 $pagesources{$page} =~ /\._([^.]+)$/;
595 sub pagename ($) { #{{{
598 my $type=pagetype($file);
600 $page=~s/\Q.$type\E*$// if defined $type;
604 sub targetpage ($$) { #{{{
608 if (! $config{usedirs} || $page =~ /^index$/ ) {
609 return $page.".".$ext;
611 return $page."/index.".$ext;
615 sub htmlpage ($) { #{{{
618 return targetpage($page, $config{htmlext});
621 sub srcfile_stat { #{{{
625 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
626 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
627 return "$dir/$file", stat(_) if -e "$dir/$file";
629 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
633 sub srcfile ($;$) { #{{{
634 return (srcfile_stat(@_))[0];
637 sub add_underlay ($) { #{{{
641 unshift @{$config{underlaydirs}}, $dir;
644 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
650 sub readfile ($;$$) { #{{{
656 error("cannot read a symlink ($file)");
660 open (my $in, "<", $file) || error("failed to read $file: $!");
661 binmode($in) if ($binary);
662 return \*$in if $wantfd;
664 close $in || error("failed to read $file: $!");
668 sub prep_writefile ($$) { #{{{
673 while (length $test) {
674 if (-l "$destdir/$test") {
675 error("cannot write to a symlink ($test)");
677 $test=dirname($test);
680 my $dir=dirname("$destdir/$file");
683 foreach my $s (split(m!/+!, $dir)) {
686 mkdir($d) || error("failed to create directory $d: $!");
694 sub writefile ($$$;$$) { #{{{
695 my $file=shift; # can include subdirs
696 my $destdir=shift; # directory to put file in
701 prep_writefile($file, $destdir);
703 my $newfile="$destdir/$file.ikiwiki-new";
705 error("cannot write to a symlink ($newfile)");
708 my $cleanup = sub { unlink($newfile) };
709 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
710 binmode($out) if ($binary);
712 $writer->(\*$out, $cleanup);
715 print $out $content or error("failed writing to $newfile: $!", $cleanup);
717 close $out || error("failed saving $newfile: $!", $cleanup);
718 rename($newfile, "$destdir/$file") ||
719 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
725 sub will_render ($$;$) { #{{{
730 # Important security check.
731 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
732 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
733 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
736 if (! $clear || $cleared{$page}) {
737 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
740 foreach my $old (@{$renderedfiles{$page}}) {
741 delete $destsources{$old};
743 $renderedfiles{$page}=[$dest];
746 $destsources{$dest}=$page;
751 sub bestlink ($$) { #{{{
756 if ($link=~s/^\/+//) {
764 $l.="/" if length $l;
767 if (exists $links{$l}) {
770 elsif (exists $pagecase{lc $l}) {
771 return $pagecase{lc $l};
773 } while $cwd=~s!/?[^/]+$!!;
775 if (length $config{userdir}) {
776 my $l = "$config{userdir}/".lc($link);
777 if (exists $links{$l}) {
780 elsif (exists $pagecase{lc $l}) {
781 return $pagecase{lc $l};
785 #print STDERR "warning: page $page, broken link: $link\n";
789 sub isinlinableimage ($) { #{{{
792 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
795 sub pagetitle ($;$) { #{{{
800 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
803 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
809 sub titlepage ($) { #{{{
811 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
815 sub linkpage ($) { #{{{
817 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
821 sub cgiurl (@) { #{{{
824 return $config{cgiurl}."?".
825 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
828 sub baseurl (;$) { #{{{
831 return "$config{url}/" if ! defined $page;
833 $page=htmlpage($page);
835 $page=~s/[^\/]+\//..\//g;
839 sub abs2rel ($$) { #{{{
840 # Work around very innefficient behavior in File::Spec if abs2rel
841 # is passed two relative paths. It's much faster if paths are
842 # absolute! (Debian bug #376658; fixed in debian unstable now)
847 my $ret=File::Spec->abs2rel($path, $base);
848 $ret=~s/^// if defined $ret;
852 sub displaytime ($;$) { #{{{
855 if (! defined $format) {
856 $format=$config{timeformat};
859 # strftime doesn't know about encodings, so make sure
860 # its output is properly treated as utf8
861 return decode_utf8(POSIX::strftime($format, localtime($time)));
864 sub beautify_urlpath ($) { #{{{
867 if ($config{usedirs}) {
868 $url =~ s!/index.$config{htmlext}$!/!;
871 # Ensure url is not an empty link, and
872 # if it's relative, make that explicit to avoid colon confusion.
880 sub urlto ($$;$) { #{{{
886 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
889 if (! $destsources{$to}) {
894 return $config{url}.beautify_urlpath("/".$to);
897 my $link = abs2rel($to, dirname(htmlpage($from)));
899 return beautify_urlpath($link);
902 sub htmllink ($$$;@) { #{{{
903 my $lpage=shift; # the page doing the linking
904 my $page=shift; # the page that will contain the link (different for inline)
911 if (! $opts{forcesubpage}) {
912 $bestlink=bestlink($lpage, $link);
915 $bestlink="$lpage/".lc($link);
919 if (defined $opts{linktext}) {
920 $linktext=$opts{linktext};
923 $linktext=pagetitle(basename($link));
926 return "<span class=\"selflink\">$linktext</span>"
927 if length $bestlink && $page eq $bestlink &&
928 ! defined $opts{anchor};
930 if (! $destsources{$bestlink}) {
931 $bestlink=htmlpage($bestlink);
933 if (! $destsources{$bestlink}) {
934 return $linktext unless length $config{cgiurl};
935 return "<span class=\"createlink\"><a href=\"".
941 "\" rel=\"nofollow\">?</a>$linktext</span>"
945 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
946 $bestlink=beautify_urlpath($bestlink);
948 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
949 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
952 if (defined $opts{anchor}) {
953 $bestlink.="#".$opts{anchor};
957 if (defined $opts{rel}) {
958 push @attrs, ' rel="'.$opts{rel}.'"';
960 if (defined $opts{class}) {
961 push @attrs, ' class="'.$opts{class}.'"';
964 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
967 sub userlink ($) { #{{{
970 my $oiduser=eval { openiduser($user) };
971 if (defined $oiduser) {
972 return "<a href=\"$user\">$oiduser</a>";
975 eval q{use CGI 'escapeHTML'};
978 return htmllink("", "", escapeHTML(
979 length $config{userdir} ? $config{userdir}."/".$user : $user
980 ), noimageinline => 1);
984 sub htmlize ($$$$) { #{{{
990 my $oneline = $content !~ /\n/;
992 if (exists $hooks{htmlize}{$type}) {
993 $content=$hooks{htmlize}{$type}{call}->(
999 error("htmlization of $type not supported");
1002 run_hooks(sanitize => sub {
1005 destpage => $destpage,
1006 content => $content,
1011 # hack to get rid of enclosing junk added by markdown
1012 # and other htmlizers
1013 $content=~s/^<p>//i;
1014 $content=~s/<\/p>$//i;
1021 sub linkify ($$$) { #{{{
1026 run_hooks(linkify => sub {
1029 destpage => $destpage,
1030 content => $content,
1038 our $preprocess_preview=0;
1039 sub preprocess ($$$;$$) { #{{{
1040 my $page=shift; # the page the data comes from
1041 my $destpage=shift; # the page the data will appear in (different for inline)
1046 # Using local because it needs to be set within any nested calls
1048 local $preprocess_preview=$preview if defined $preview;
1055 $params="" if ! defined $params;
1057 if (length $escape) {
1058 return "[[$prefix$command $params]]";
1060 elsif (exists $hooks{preprocess}{$command}) {
1061 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1062 # Note: preserve order of params, some plugins may
1063 # consider it significant.
1065 while ($params =~ m{
1066 (?:([-\w]+)=)? # 1: named parameter key?
1068 """(.*?)""" # 2: triple-quoted value
1070 "([^"]+)" # 3: single-quoted value
1072 (\S+) # 4: unquoted value
1074 (?:\s+|$) # delimiter to next param
1084 elsif (defined $3) {
1087 elsif (defined $4) {
1092 push @params, $key, $val;
1095 push @params, $val, '';
1098 if ($preprocessing{$page}++ > 3) {
1099 # Avoid loops of preprocessed pages preprocessing
1100 # other pages that preprocess them, etc.
1101 return "[[!$command <span class=\"error\">".
1102 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1103 $page, $preprocessing{$page}).
1109 $hooks{preprocess}{$command}{call}->(
1112 destpage => $destpage,
1113 preview => $preprocess_preview,
1118 $ret="[[!$command <span class=\"error\">".
1119 gettext("Error").": $@"."</span>]]";
1123 # use void context during scan pass
1125 $hooks{preprocess}{$command}{call}->(
1128 destpage => $destpage,
1129 preview => $preprocess_preview,
1134 $preprocessing{$page}--;
1138 return "[[$prefix$command $params]]";
1143 if ($config{prefix_directives}) {
1146 \[\[(!) # directive open; 2: prefix
1147 ([-\w]+) # 3: command
1148 ( # 4: the parameters..
1149 \s+ # Must have space if parameters present
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
1169 \[\[(!?) # directive open; 2: optional prefix
1170 ([-\w]+) # 3: command
1172 ( # 4: the parameters..
1174 (?:[-\w]+=)? # named parameter key?
1176 """.*?""" # triple-quoted value
1178 "[^"]+" # single-quoted value
1180 [^\s\]]+ # unquoted value
1182 \s* # whitespace or end
1185 *) # 0 or more parameters
1186 \]\] # directive closed
1190 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1194 sub filter ($$$) { #{{{
1199 run_hooks(filter => sub {
1200 $content=shift->(page => $page, destpage => $destpage,
1201 content => $content);
1207 sub indexlink () { #{{{
1208 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1213 sub lockwiki (;$) { #{{{
1214 my $wait=@_ ? shift : 1;
1215 # Take an exclusive lock on the wiki to prevent multiple concurrent
1216 # run issues. The lock will be dropped on program exit.
1217 if (! -d $config{wikistatedir}) {
1218 mkdir($config{wikistatedir});
1220 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1221 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1222 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1224 debug("wiki seems to be locked, waiting for lock");
1225 my $wait=600; # arbitrary, but don't hang forever to
1226 # prevent process pileup
1228 return if flock($wikilock, 2 | 4);
1231 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1240 sub unlockwiki () { #{{{
1241 return close($wikilock) if $wikilock;
1247 sub commit_hook_enabled () { #{{{
1248 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1249 error("cannot write to $config{wikistatedir}/commitlock: $!");
1250 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1251 close($commitlock) || error("failed closing commitlock: $!");
1254 close($commitlock) || error("failed closing commitlock: $!");
1258 sub disable_commit_hook () { #{{{
1259 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1260 error("cannot write to $config{wikistatedir}/commitlock: $!");
1261 if (! flock($commitlock, 2)) { # LOCK_EX
1262 error("failed to get commit lock");
1267 sub enable_commit_hook () { #{{{
1268 return close($commitlock) if $commitlock;
1272 sub loadindex () { #{{{
1273 %oldrenderedfiles=%pagectime=();
1274 if (! $config{rebuild}) {
1275 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1276 %destsources=%renderedfiles=%pagecase=%pagestate=();
1279 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1280 if (-e "$config{wikistatedir}/index") {
1281 system("ikiwiki-transition", "indexdb", $config{srcdir});
1282 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1288 my $ret=Storable::fd_retrieve($in);
1289 if (! defined $ret) {
1293 foreach my $src (keys %index) {
1294 my %d=%{$index{$src}};
1295 my $page=pagename($src);
1296 $pagectime{$page}=$d{ctime};
1297 if (! $config{rebuild}) {
1298 $pagesources{$page}=$src;
1299 $pagemtime{$page}=$d{mtime};
1300 $renderedfiles{$page}=$d{dest};
1301 if (exists $d{links} && ref $d{links}) {
1302 $links{$page}=$d{links};
1303 $oldlinks{$page}=[@{$d{links}}];
1305 if (exists $d{depends}) {
1306 $depends{$page}=$d{depends};
1308 if (exists $d{state}) {
1309 $pagestate{$page}=$d{state};
1312 $oldrenderedfiles{$page}=[@{$d{dest}}];
1314 foreach my $page (keys %pagesources) {
1315 $pagecase{lc $page}=$page;
1317 foreach my $page (keys %renderedfiles) {
1318 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1323 sub saveindex () { #{{{
1324 run_hooks(savestate => sub { shift->() });
1327 foreach my $type (keys %hooks) {
1328 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1330 my @hookids=keys %hookids;
1332 if (! -d $config{wikistatedir}) {
1333 mkdir($config{wikistatedir});
1335 my $newfile="$config{wikistatedir}/indexdb.new";
1336 my $cleanup = sub { unlink($newfile) };
1337 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1339 foreach my $page (keys %pagemtime) {
1340 next unless $pagemtime{$page};
1341 my $src=$pagesources{$page};
1344 ctime => $pagectime{$page},
1345 mtime => $pagemtime{$page},
1346 dest => $renderedfiles{$page},
1347 links => $links{$page},
1350 if (exists $depends{$page}) {
1351 $index{$src}{depends} = $depends{$page};
1354 if (exists $pagestate{$page}) {
1355 foreach my $id (@hookids) {
1356 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1357 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1362 my $ret=Storable::nstore_fd(\%index, $out);
1363 return if ! defined $ret || ! $ret;
1364 close $out || error("failed saving to $newfile: $!", $cleanup);
1365 rename($newfile, "$config{wikistatedir}/indexdb") ||
1366 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1371 sub template_file ($) { #{{{
1374 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1375 return "$dir/$template" if -e "$dir/$template";
1380 sub template_params (@) { #{{{
1381 my $filename=template_file(shift);
1383 if (! defined $filename) {
1384 return if wantarray;
1390 my $text_ref = shift;
1391 ${$text_ref} = decode_utf8(${$text_ref});
1393 filename => $filename,
1394 loop_context_vars => 1,
1395 die_on_bad_params => 0,
1398 return wantarray ? @ret : {@ret};
1401 sub template ($;@) { #{{{
1402 require HTML::Template;
1403 return HTML::Template->new(template_params(@_));
1406 sub misctemplate ($$;@) { #{{{
1410 my $template=template("misc.tmpl");
1413 indexlink => indexlink(),
1414 wikiname => $config{wikiname},
1415 pagebody => $pagebody,
1416 baseurl => baseurl(),
1419 run_hooks(pagetemplate => sub {
1420 shift->(page => "", destpage => "", template => $template);
1422 return $template->output;
1425 sub hook (@) { # {{{
1428 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1429 error 'hook requires type, call, and id parameters';
1432 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1434 $hooks{$param{type}}{$param{id}}=\%param;
1438 sub run_hooks ($$) { # {{{
1439 # Calls the given sub for each hook of the given type,
1440 # passing it the hook function to call.
1444 if (exists $hooks{$type}) {
1446 foreach my $id (keys %{$hooks{$type}}) {
1447 if ($hooks{$type}{$id}{last}) {
1448 push @deferred, $id;
1451 $sub->($hooks{$type}{$id}{call});
1453 foreach my $id (@deferred) {
1454 $sub->($hooks{$type}{$id}{call});
1461 sub rcs_update () { #{{{
1462 $hooks{rcs}{rcs_update}{call}->(@_);
1465 sub rcs_prepedit ($) { #{{{
1466 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1469 sub rcs_commit ($$$;$$) { #{{{
1470 $hooks{rcs}{rcs_commit}{call}->(@_);
1473 sub rcs_commit_staged ($$$) { #{{{
1474 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1477 sub rcs_add ($) { #{{{
1478 $hooks{rcs}{rcs_add}{call}->(@_);
1481 sub rcs_remove ($) { #{{{
1482 $hooks{rcs}{rcs_remove}{call}->(@_);
1485 sub rcs_rename ($$) { #{{{
1486 $hooks{rcs}{rcs_rename}{call}->(@_);
1489 sub rcs_recentchanges ($) { #{{{
1490 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1493 sub rcs_diff ($) { #{{{
1494 $hooks{rcs}{rcs_diff}{call}->(@_);
1497 sub rcs_getctime ($) { #{{{
1498 $hooks{rcs}{rcs_getctime}{call}->(@_);
1501 sub globlist_to_pagespec ($) { #{{{
1502 my @globlist=split(' ', shift);
1505 foreach my $glob (@globlist) {
1506 if ($glob=~/^!(.*)/) {
1514 my $spec=join(' or ', @spec);
1516 my $skip=join(' and ', @skip);
1518 $spec="$skip and ($spec)";
1527 sub is_globlist ($) { #{{{
1529 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1532 sub safequote ($) { #{{{
1538 sub add_depends ($$) { #{{{
1542 return unless pagespec_valid($pagespec);
1544 if (! exists $depends{$page}) {
1545 $depends{$page}=$pagespec;
1548 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1554 sub file_pruned ($$) { #{{{
1556 my $file=File::Spec->canonpath(shift);
1557 my $base=File::Spec->canonpath(shift);
1558 $file =~ s#^\Q$base\E/+##;
1560 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1561 return $file =~ m/$regexp/ && $file ne $base;
1565 # Only use gettext in the rare cases it's needed.
1566 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1567 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1568 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1569 if (! $gettext_obj) {
1570 $gettext_obj=eval q{
1571 use Locale::gettext q{textdomain};
1572 Locale::gettext->domain('ikiwiki')
1580 return $gettext_obj->get(shift);
1587 sub yesno ($) { #{{{
1590 return (defined $val && lc($val) eq gettext("yes"));
1593 sub pagespec_merge ($$) { #{{{
1597 return $a if $a eq $b;
1599 # Support for old-style GlobLists.
1600 if (is_globlist($a)) {
1601 $a=globlist_to_pagespec($a);
1603 if (is_globlist($b)) {
1604 $b=globlist_to_pagespec($b);
1607 return "($a) or ($b)";
1610 sub pagespec_translate ($) { #{{{
1613 # Support for old-style GlobLists.
1614 if (is_globlist($spec)) {
1615 $spec=globlist_to_pagespec($spec);
1618 # Convert spec to perl code.
1621 \s* # ignore whitespace
1622 ( # 1: match a single word
1629 \w+\([^\)]*\) # command(params)
1631 [^\s()]+ # any other text
1633 \s* # ignore whitespace
1636 if (lc $word eq 'and') {
1639 elsif (lc $word eq 'or') {
1642 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1645 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1646 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1647 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1654 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1658 if (! length $code) {
1663 return eval 'sub { my $page=shift; '.$code.' }';
1666 sub pagespec_match ($$;@) { #{{{
1671 # Backwards compatability with old calling convention.
1673 unshift @params, 'location';
1676 my $sub=pagespec_translate($spec);
1677 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1678 return $sub->($page, @params);
1681 sub pagespec_valid ($) { #{{{
1684 my $sub=pagespec_translate($spec);
1688 sub glob2re ($) { #{{{
1689 my $re=quotemeta(shift);
1695 package IkiWiki::FailReason;
1698 '""' => sub { ${$_[0]} },
1700 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1707 return bless \$value, $class;
1710 package IkiWiki::SuccessReason;
1713 '""' => sub { ${$_[0]} },
1715 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1722 return bless \$value, $class;
1725 package IkiWiki::PageSpec;
1727 sub match_glob ($$;@) { #{{{
1732 my $from=exists $params{location} ? $params{location} : '';
1735 if ($glob =~ m!^\./!) {
1736 $from=~s#/?[^/]+$##;
1738 $glob="$from/$glob" if length $from;
1741 my $regexp=IkiWiki::glob2re($glob);
1742 if ($page=~/^$regexp$/i) {
1743 if (! IkiWiki::isinternal($page) || $params{internal}) {
1744 return IkiWiki::SuccessReason->new("$glob matches $page");
1747 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1751 return IkiWiki::FailReason->new("$glob does not match $page");
1755 sub match_internal ($$;@) { #{{{
1756 return match_glob($_[0], $_[1], @_, internal => 1)
1759 sub match_link ($$;@) { #{{{
1764 my $from=exists $params{location} ? $params{location} : '';
1767 if ($link =~ m!^\.! && defined $from) {
1768 $from=~s#/?[^/]+$##;
1770 $link="$from/$link" if length $from;
1773 my $links = $IkiWiki::links{$page};
1774 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1775 my $bestlink = IkiWiki::bestlink($from, $link);
1776 foreach my $p (@{$links}) {
1777 if (length $bestlink) {
1778 return IkiWiki::SuccessReason->new("$page links to $link")
1779 if $bestlink eq IkiWiki::bestlink($page, $p);
1782 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1783 if match_glob($p, $link, %params);
1786 return IkiWiki::FailReason->new("$page does not link to $link");
1789 sub match_backlink ($$;@) { #{{{
1790 return match_link($_[1], $_[0], @_);
1793 sub match_created_before ($$;@) { #{{{
1797 if (exists $IkiWiki::pagectime{$testpage}) {
1798 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1799 return IkiWiki::SuccessReason->new("$page created before $testpage");
1802 return IkiWiki::FailReason->new("$page not created before $testpage");
1806 return IkiWiki::FailReason->new("$testpage has no ctime");
1810 sub match_created_after ($$;@) { #{{{
1814 if (exists $IkiWiki::pagectime{$testpage}) {
1815 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1816 return IkiWiki::SuccessReason->new("$page created after $testpage");
1819 return IkiWiki::FailReason->new("$page not created after $testpage");
1823 return IkiWiki::FailReason->new("$testpage has no ctime");
1827 sub match_creation_day ($$;@) { #{{{
1828 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1829 return IkiWiki::SuccessReason->new('creation_day matched');
1832 return IkiWiki::FailReason->new('creation_day did not match');
1836 sub match_creation_month ($$;@) { #{{{
1837 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1838 return IkiWiki::SuccessReason->new('creation_month matched');
1841 return IkiWiki::FailReason->new('creation_month did not match');
1845 sub match_creation_year ($$;@) { #{{{
1846 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1847 return IkiWiki::SuccessReason->new('creation_year matched');
1850 return IkiWiki::FailReason->new('creation_year did not match');