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 editpage}],
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",
317 description => "specifies the characters that are allowed in source filenames",
318 default => "-[:alnum:]+/.:_",
322 wiki_file_regexp => {
324 description => "regexp of legal source files",
328 web_commit_regexp => {
330 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
331 description => "regexp to parse web commits from logs",
338 description => "run as a cgi",
342 cgi_disable_uploads => {
345 description => "whether CGI should accept file uploads",
352 description => "run as a post-commit hook",
359 description => "running in rebuild mode",
366 description => "running in setup mode",
373 description => "running in refresh mode",
380 description => "running in getctime mode",
387 description => "running in w3mmode",
394 description => "path to setup file",
400 sub defaultconfig () { #{{{
403 foreach my $key (keys %s) {
404 push @ret, $key, $s{$key}->{default};
410 sub checkconfig () { #{{{
411 # locale stuff; avoid LC_ALL since it overrides everything
412 if (defined $ENV{LC_ALL}) {
413 $ENV{LANG} = $ENV{LC_ALL};
416 if (defined $config{locale}) {
417 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
418 $ENV{LANG}=$config{locale};
423 if (! defined $config{wiki_file_regexp}) {
424 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
427 if (ref $config{ENV} eq 'HASH') {
428 foreach my $val (keys %{$config{ENV}}) {
429 $ENV{$val}=$config{ENV}{$val};
433 if ($config{w3mmode}) {
434 eval q{use Cwd q{abs_path}};
436 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
437 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
438 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
439 unless $config{cgiurl} =~ m!file:///!;
440 $config{url}="file://".$config{destdir};
443 if ($config{cgi} && ! length $config{url}) {
444 error(gettext("Must specify url to wiki with --url when using --cgi"));
447 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
448 unless exists $config{wikistatedir};
450 if (defined $config{umask}) {
451 umask(possibly_foolish_untaint($config{umask}));
454 run_hooks(checkconfig => sub { shift->() });
459 sub listplugins () { #{{{
462 foreach my $dir (@INC, $config{libdir}) {
463 next unless defined $dir && length $dir;
464 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
465 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
469 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
470 next unless defined $dir && length $dir;
471 foreach my $file (glob("$dir/plugins/*")) {
472 $ret{basename($file)}=1 if -x $file;
479 sub loadplugins () { #{{{
480 if (defined $config{libdir} && length $config{libdir}) {
481 unshift @INC, possibly_foolish_untaint($config{libdir});
484 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
489 if (exists $IkiWiki::hooks{rcs}) {
490 error(gettext("cannot use multiple rcs plugins"));
492 loadplugin($config{rcs});
494 if (! exists $IkiWiki::hooks{rcs}) {
498 run_hooks(getopt => sub { shift->() });
499 if (grep /^-/, @ARGV) {
500 print STDERR "Unknown option: $_\n"
501 foreach grep /^-/, @ARGV;
508 sub loadplugin ($) { #{{{
511 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
513 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
514 "$installdir/lib/ikiwiki") {
515 if (defined $dir && -x "$dir/plugins/$plugin") {
516 require IkiWiki::Plugin::external;
517 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
518 $loaded_plugins{$plugin}=1;
523 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
526 error("Failed to load plugin $mod: $@");
528 $loaded_plugins{$plugin}=1;
532 sub error ($;$) { #{{{
535 log_message('err' => $message) if $config{syslog};
536 if (defined $cleaner) {
543 return unless $config{verbose};
544 return log_message(debug => @_);
548 sub log_message ($$) { #{{{
551 if ($config{syslog}) {
554 Sys::Syslog::setlogsock('unix');
555 Sys::Syslog::openlog('ikiwiki', '', 'user');
559 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
562 elsif (! $config{cgi}) {
566 return print STDERR "@_\n";
570 sub possibly_foolish_untaint ($) { #{{{
572 my ($untainted)=$tainted=~/(.*)/s;
576 sub basename ($) { #{{{
583 sub dirname ($) { #{{{
590 sub pagetype ($) { #{{{
593 if ($page =~ /\.([^.]+)$/) {
594 return $1 if exists $hooks{htmlize}{$1};
599 sub isinternal ($) { #{{{
601 return exists $pagesources{$page} &&
602 $pagesources{$page} =~ /\._([^.]+)$/;
605 sub pagename ($) { #{{{
608 my $type=pagetype($file);
610 $page=~s/\Q.$type\E*$// if defined $type;
614 sub targetpage ($$) { #{{{
618 if (! $config{usedirs} || $page =~ /^index$/ ) {
619 return $page.".".$ext;
621 return $page."/index.".$ext;
625 sub htmlpage ($) { #{{{
628 return targetpage($page, $config{htmlext});
631 sub srcfile_stat { #{{{
635 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
636 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
637 return "$dir/$file", stat(_) if -e "$dir/$file";
639 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
643 sub srcfile ($;$) { #{{{
644 return (srcfile_stat(@_))[0];
647 sub add_underlay ($) { #{{{
651 unshift @{$config{underlaydirs}}, $dir;
654 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
660 sub readfile ($;$$) { #{{{
666 error("cannot read a symlink ($file)");
670 open (my $in, "<", $file) || error("failed to read $file: $!");
671 binmode($in) if ($binary);
672 return \*$in if $wantfd;
674 close $in || error("failed to read $file: $!");
678 sub prep_writefile ($$) { #{{{
683 while (length $test) {
684 if (-l "$destdir/$test") {
685 error("cannot write to a symlink ($test)");
687 $test=dirname($test);
690 my $dir=dirname("$destdir/$file");
693 foreach my $s (split(m!/+!, $dir)) {
696 mkdir($d) || error("failed to create directory $d: $!");
704 sub writefile ($$$;$$) { #{{{
705 my $file=shift; # can include subdirs
706 my $destdir=shift; # directory to put file in
711 prep_writefile($file, $destdir);
713 my $newfile="$destdir/$file.ikiwiki-new";
715 error("cannot write to a symlink ($newfile)");
718 my $cleanup = sub { unlink($newfile) };
719 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
720 binmode($out) if ($binary);
722 $writer->(\*$out, $cleanup);
725 print $out $content or error("failed writing to $newfile: $!", $cleanup);
727 close $out || error("failed saving $newfile: $!", $cleanup);
728 rename($newfile, "$destdir/$file") ||
729 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
735 sub will_render ($$;$) { #{{{
740 # Important security check.
741 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
742 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
743 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
746 if (! $clear || $cleared{$page}) {
747 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
750 foreach my $old (@{$renderedfiles{$page}}) {
751 delete $destsources{$old};
753 $renderedfiles{$page}=[$dest];
756 $destsources{$dest}=$page;
761 sub bestlink ($$) { #{{{
766 if ($link=~s/^\/+//) {
774 $l.="/" if length $l;
777 if (exists $links{$l}) {
780 elsif (exists $pagecase{lc $l}) {
781 return $pagecase{lc $l};
783 } while $cwd=~s{/?[^/]+$}{};
785 if (length $config{userdir}) {
786 my $l = "$config{userdir}/".lc($link);
787 if (exists $links{$l}) {
790 elsif (exists $pagecase{lc $l}) {
791 return $pagecase{lc $l};
795 #print STDERR "warning: page $page, broken link: $link\n";
799 sub isinlinableimage ($) { #{{{
802 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
805 sub pagetitle ($;$) { #{{{
810 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
813 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
819 sub titlepage ($) { #{{{
821 # support use w/o %config set
822 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
823 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
827 sub linkpage ($) { #{{{
829 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
830 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
834 sub cgiurl (@) { #{{{
837 return $config{cgiurl}."?".
838 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
841 sub baseurl (;$) { #{{{
844 return "$config{url}/" if ! defined $page;
846 $page=htmlpage($page);
848 $page=~s/[^\/]+\//..\//g;
852 sub abs2rel ($$) { #{{{
853 # Work around very innefficient behavior in File::Spec if abs2rel
854 # is passed two relative paths. It's much faster if paths are
855 # absolute! (Debian bug #376658; fixed in debian unstable now)
860 my $ret=File::Spec->abs2rel($path, $base);
861 $ret=~s/^// if defined $ret;
865 sub displaytime ($;$) { #{{{
868 if (! defined $format) {
869 $format=$config{timeformat};
872 # strftime doesn't know about encodings, so make sure
873 # its output is properly treated as utf8
874 return decode_utf8(POSIX::strftime($format, localtime($time)));
877 sub beautify_urlpath ($) { #{{{
880 if ($config{usedirs}) {
881 $url =~ s!/index.$config{htmlext}$!/!;
884 # Ensure url is not an empty link, and
885 # if it's relative, make that explicit to avoid colon confusion.
893 sub urlto ($$;$) { #{{{
899 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
902 if (! $destsources{$to}) {
907 return $config{url}.beautify_urlpath("/".$to);
910 my $link = abs2rel($to, dirname(htmlpage($from)));
912 return beautify_urlpath($link);
915 sub htmllink ($$$;@) { #{{{
916 my $lpage=shift; # the page doing the linking
917 my $page=shift; # the page that will contain the link (different for inline)
924 if (! $opts{forcesubpage}) {
925 $bestlink=bestlink($lpage, $link);
928 $bestlink="$lpage/".lc($link);
932 if (defined $opts{linktext}) {
933 $linktext=$opts{linktext};
936 $linktext=pagetitle(basename($link));
939 return "<span class=\"selflink\">$linktext</span>"
940 if length $bestlink && $page eq $bestlink &&
941 ! defined $opts{anchor};
943 if (! $destsources{$bestlink}) {
944 $bestlink=htmlpage($bestlink);
946 if (! $destsources{$bestlink}) {
947 return $linktext unless length $config{cgiurl};
948 return "<span class=\"createlink\"><a href=\"".
954 "\" rel=\"nofollow\">?</a>$linktext</span>"
958 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
959 $bestlink=beautify_urlpath($bestlink);
961 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
962 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
965 if (defined $opts{anchor}) {
966 $bestlink.="#".$opts{anchor};
970 if (defined $opts{rel}) {
971 push @attrs, ' rel="'.$opts{rel}.'"';
973 if (defined $opts{class}) {
974 push @attrs, ' class="'.$opts{class}.'"';
977 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
980 sub userlink ($) { #{{{
983 my $oiduser=eval { openiduser($user) };
984 if (defined $oiduser) {
985 return "<a href=\"$user\">$oiduser</a>";
988 eval q{use CGI 'escapeHTML'};
991 return htmllink("", "", escapeHTML(
992 length $config{userdir} ? $config{userdir}."/".$user : $user
993 ), noimageinline => 1);
997 sub htmlize ($$$$) { #{{{
1003 my $oneline = $content !~ /\n/;
1005 if (exists $hooks{htmlize}{$type}) {
1006 $content=$hooks{htmlize}{$type}{call}->(
1008 content => $content,
1012 error("htmlization of $type not supported");
1015 run_hooks(sanitize => sub {
1018 destpage => $destpage,
1019 content => $content,
1024 # hack to get rid of enclosing junk added by markdown
1025 # and other htmlizers
1026 $content=~s/^<p>//i;
1027 $content=~s/<\/p>$//i;
1034 sub linkify ($$$) { #{{{
1039 run_hooks(linkify => sub {
1042 destpage => $destpage,
1043 content => $content,
1051 our $preprocess_preview=0;
1052 sub preprocess ($$$;$$) { #{{{
1053 my $page=shift; # the page the data comes from
1054 my $destpage=shift; # the page the data will appear in (different for inline)
1059 # Using local because it needs to be set within any nested calls
1061 local $preprocess_preview=$preview if defined $preview;
1068 $params="" if ! defined $params;
1070 if (length $escape) {
1071 return "[[$prefix$command $params]]";
1073 elsif (exists $hooks{preprocess}{$command}) {
1074 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1075 # Note: preserve order of params, some plugins may
1076 # consider it significant.
1078 while ($params =~ m{
1079 (?:([-\w]+)=)? # 1: named parameter key?
1081 """(.*?)""" # 2: triple-quoted value
1083 "([^"]+)" # 3: single-quoted value
1085 (\S+) # 4: unquoted value
1087 (?:\s+|$) # delimiter to next param
1097 elsif (defined $3) {
1100 elsif (defined $4) {
1105 push @params, $key, $val;
1108 push @params, $val, '';
1111 if ($preprocessing{$page}++ > 3) {
1112 # Avoid loops of preprocessed pages preprocessing
1113 # other pages that preprocess them, etc.
1114 return "[[!$command <span class=\"error\">".
1115 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1116 $page, $preprocessing{$page}).
1122 $hooks{preprocess}{$command}{call}->(
1125 destpage => $destpage,
1126 preview => $preprocess_preview,
1131 $ret="[[!$command <span class=\"error\">".
1132 gettext("Error").": $@"."</span>]]";
1136 # use void context during scan pass
1138 $hooks{preprocess}{$command}{call}->(
1141 destpage => $destpage,
1142 preview => $preprocess_preview,
1147 $preprocessing{$page}--;
1151 return "[[$prefix$command $params]]";
1156 if ($config{prefix_directives}) {
1159 \[\[(!) # directive open; 2: prefix
1160 ([-\w]+) # 3: command
1161 ( # 4: the parameters..
1162 \s+ # Must have space if parameters present
1164 (?:[-\w]+=)? # named parameter key?
1166 """.*?""" # triple-quoted value
1168 "[^"]+" # single-quoted value
1170 [^\s\]]+ # unquoted value
1172 \s* # whitespace or end
1175 *)? # 0 or more parameters
1176 \]\] # directive closed
1182 \[\[(!?) # directive open; 2: optional prefix
1183 ([-\w]+) # 3: command
1185 ( # 4: the parameters..
1187 (?:[-\w]+=)? # named parameter key?
1189 """.*?""" # triple-quoted value
1191 "[^"]+" # single-quoted value
1193 [^\s\]]+ # unquoted value
1195 \s* # whitespace or end
1198 *) # 0 or more parameters
1199 \]\] # directive closed
1203 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1207 sub filter ($$$) { #{{{
1212 run_hooks(filter => sub {
1213 $content=shift->(page => $page, destpage => $destpage,
1214 content => $content);
1220 sub indexlink () { #{{{
1221 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1226 sub lockwiki (;$) { #{{{
1227 my $wait=@_ ? shift : 1;
1228 # Take an exclusive lock on the wiki to prevent multiple concurrent
1229 # run issues. The lock will be dropped on program exit.
1230 if (! -d $config{wikistatedir}) {
1231 mkdir($config{wikistatedir});
1233 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1234 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1235 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1237 debug("wiki seems to be locked, waiting for lock");
1238 my $wait=600; # arbitrary, but don't hang forever to
1239 # prevent process pileup
1241 return if flock($wikilock, 2 | 4);
1244 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1253 sub unlockwiki () { #{{{
1254 return close($wikilock) if $wikilock;
1260 sub commit_hook_enabled () { #{{{
1261 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1262 error("cannot write to $config{wikistatedir}/commitlock: $!");
1263 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1264 close($commitlock) || error("failed closing commitlock: $!");
1267 close($commitlock) || error("failed closing commitlock: $!");
1271 sub disable_commit_hook () { #{{{
1272 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1273 error("cannot write to $config{wikistatedir}/commitlock: $!");
1274 if (! flock($commitlock, 2)) { # LOCK_EX
1275 error("failed to get commit lock");
1280 sub enable_commit_hook () { #{{{
1281 return close($commitlock) if $commitlock;
1285 sub loadindex () { #{{{
1286 %oldrenderedfiles=%pagectime=();
1287 if (! $config{rebuild}) {
1288 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1289 %destsources=%renderedfiles=%pagecase=%pagestate=();
1292 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1293 if (-e "$config{wikistatedir}/index") {
1294 system("ikiwiki-transition", "indexdb", $config{srcdir});
1295 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1301 my $ret=Storable::fd_retrieve($in);
1302 if (! defined $ret) {
1306 foreach my $src (keys %index) {
1307 my %d=%{$index{$src}};
1308 my $page=pagename($src);
1309 $pagectime{$page}=$d{ctime};
1310 if (! $config{rebuild}) {
1311 $pagesources{$page}=$src;
1312 $pagemtime{$page}=$d{mtime};
1313 $renderedfiles{$page}=$d{dest};
1314 if (exists $d{links} && ref $d{links}) {
1315 $links{$page}=$d{links};
1316 $oldlinks{$page}=[@{$d{links}}];
1318 if (exists $d{depends}) {
1319 $depends{$page}=$d{depends};
1321 if (exists $d{state}) {
1322 $pagestate{$page}=$d{state};
1325 $oldrenderedfiles{$page}=[@{$d{dest}}];
1327 foreach my $page (keys %pagesources) {
1328 $pagecase{lc $page}=$page;
1330 foreach my $page (keys %renderedfiles) {
1331 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1336 sub saveindex () { #{{{
1337 run_hooks(savestate => sub { shift->() });
1340 foreach my $type (keys %hooks) {
1341 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1343 my @hookids=keys %hookids;
1345 if (! -d $config{wikistatedir}) {
1346 mkdir($config{wikistatedir});
1348 my $newfile="$config{wikistatedir}/indexdb.new";
1349 my $cleanup = sub { unlink($newfile) };
1350 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1352 foreach my $page (keys %pagemtime) {
1353 next unless $pagemtime{$page};
1354 my $src=$pagesources{$page};
1357 ctime => $pagectime{$page},
1358 mtime => $pagemtime{$page},
1359 dest => $renderedfiles{$page},
1360 links => $links{$page},
1363 if (exists $depends{$page}) {
1364 $index{$src}{depends} = $depends{$page};
1367 if (exists $pagestate{$page}) {
1368 foreach my $id (@hookids) {
1369 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1370 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1375 my $ret=Storable::nstore_fd(\%index, $out);
1376 return if ! defined $ret || ! $ret;
1377 close $out || error("failed saving to $newfile: $!", $cleanup);
1378 rename($newfile, "$config{wikistatedir}/indexdb") ||
1379 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1384 sub template_file ($) { #{{{
1387 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1388 return "$dir/$template" if -e "$dir/$template";
1393 sub template_params (@) { #{{{
1394 my $filename=template_file(shift);
1396 if (! defined $filename) {
1397 return if wantarray;
1403 my $text_ref = shift;
1404 ${$text_ref} = decode_utf8(${$text_ref});
1406 filename => $filename,
1407 loop_context_vars => 1,
1408 die_on_bad_params => 0,
1411 return wantarray ? @ret : {@ret};
1414 sub template ($;@) { #{{{
1415 require HTML::Template;
1416 return HTML::Template->new(template_params(@_));
1419 sub misctemplate ($$;@) { #{{{
1423 my $template=template("misc.tmpl");
1426 indexlink => indexlink(),
1427 wikiname => $config{wikiname},
1428 pagebody => $pagebody,
1429 baseurl => baseurl(),
1432 run_hooks(pagetemplate => sub {
1433 shift->(page => "", destpage => "", template => $template);
1435 return $template->output;
1438 sub hook (@) { # {{{
1441 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1442 error 'hook requires type, call, and id parameters';
1445 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1447 $hooks{$param{type}}{$param{id}}=\%param;
1451 sub run_hooks ($$) { # {{{
1452 # Calls the given sub for each hook of the given type,
1453 # passing it the hook function to call.
1457 if (exists $hooks{$type}) {
1459 foreach my $id (keys %{$hooks{$type}}) {
1460 if ($hooks{$type}{$id}{last}) {
1461 push @deferred, $id;
1464 $sub->($hooks{$type}{$id}{call});
1466 foreach my $id (@deferred) {
1467 $sub->($hooks{$type}{$id}{call});
1474 sub rcs_update () { #{{{
1475 $hooks{rcs}{rcs_update}{call}->(@_);
1478 sub rcs_prepedit ($) { #{{{
1479 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1482 sub rcs_commit ($$$;$$) { #{{{
1483 $hooks{rcs}{rcs_commit}{call}->(@_);
1486 sub rcs_commit_staged ($$$) { #{{{
1487 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1490 sub rcs_add ($) { #{{{
1491 $hooks{rcs}{rcs_add}{call}->(@_);
1494 sub rcs_remove ($) { #{{{
1495 $hooks{rcs}{rcs_remove}{call}->(@_);
1498 sub rcs_rename ($$) { #{{{
1499 $hooks{rcs}{rcs_rename}{call}->(@_);
1502 sub rcs_recentchanges ($) { #{{{
1503 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1506 sub rcs_diff ($) { #{{{
1507 $hooks{rcs}{rcs_diff}{call}->(@_);
1510 sub rcs_getctime ($) { #{{{
1511 $hooks{rcs}{rcs_getctime}{call}->(@_);
1514 sub globlist_to_pagespec ($) { #{{{
1515 my @globlist=split(' ', shift);
1518 foreach my $glob (@globlist) {
1519 if ($glob=~/^!(.*)/) {
1527 my $spec=join(' or ', @spec);
1529 my $skip=join(' and ', @skip);
1531 $spec="$skip and ($spec)";
1540 sub is_globlist ($) { #{{{
1542 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1545 sub safequote ($) { #{{{
1551 sub add_depends ($$) { #{{{
1555 return unless pagespec_valid($pagespec);
1557 if (! exists $depends{$page}) {
1558 $depends{$page}=$pagespec;
1561 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1567 sub file_pruned ($$) { #{{{
1569 my $file=File::Spec->canonpath(shift);
1570 my $base=File::Spec->canonpath(shift);
1571 $file =~ s#^\Q$base\E/+##;
1573 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1574 return $file =~ m/$regexp/ && $file ne $base;
1578 # Only use gettext in the rare cases it's needed.
1579 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1580 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1581 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1582 if (! $gettext_obj) {
1583 $gettext_obj=eval q{
1584 use Locale::gettext q{textdomain};
1585 Locale::gettext->domain('ikiwiki')
1593 return $gettext_obj->get(shift);
1600 sub yesno ($) { #{{{
1603 return (defined $val && lc($val) eq gettext("yes"));
1606 sub pagespec_merge ($$) { #{{{
1610 return $a if $a eq $b;
1612 # Support for old-style GlobLists.
1613 if (is_globlist($a)) {
1614 $a=globlist_to_pagespec($a);
1616 if (is_globlist($b)) {
1617 $b=globlist_to_pagespec($b);
1620 return "($a) or ($b)";
1623 sub pagespec_translate ($) { #{{{
1626 # Support for old-style GlobLists.
1627 if (is_globlist($spec)) {
1628 $spec=globlist_to_pagespec($spec);
1631 # Convert spec to perl code.
1634 \s* # ignore whitespace
1635 ( # 1: match a single word
1642 \w+\([^\)]*\) # command(params)
1644 [^\s()]+ # any other text
1646 \s* # ignore whitespace
1649 if (lc $word eq 'and') {
1652 elsif (lc $word eq 'or') {
1655 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1658 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1659 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1660 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1667 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1671 if (! length $code) {
1676 return eval 'sub { my $page=shift; '.$code.' }';
1679 sub pagespec_match ($$;@) { #{{{
1684 # Backwards compatability with old calling convention.
1686 unshift @params, 'location';
1689 my $sub=pagespec_translate($spec);
1690 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1691 return $sub->($page, @params);
1694 sub pagespec_valid ($) { #{{{
1697 my $sub=pagespec_translate($spec);
1701 sub glob2re ($) { #{{{
1702 my $re=quotemeta(shift);
1708 package IkiWiki::FailReason;
1711 '""' => sub { ${$_[0]} },
1713 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1720 return bless \$value, $class;
1723 package IkiWiki::SuccessReason;
1726 '""' => sub { ${$_[0]} },
1728 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1735 return bless \$value, $class;
1738 package IkiWiki::PageSpec;
1740 sub match_glob ($$;@) { #{{{
1745 my $from=exists $params{location} ? $params{location} : '';
1748 if ($glob =~ m!^\./!) {
1749 $from=~s#/?[^/]+$##;
1751 $glob="$from/$glob" if length $from;
1754 my $regexp=IkiWiki::glob2re($glob);
1755 if ($page=~/^$regexp$/i) {
1756 if (! IkiWiki::isinternal($page) || $params{internal}) {
1757 return IkiWiki::SuccessReason->new("$glob matches $page");
1760 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1764 return IkiWiki::FailReason->new("$glob does not match $page");
1768 sub match_internal ($$;@) { #{{{
1769 return match_glob($_[0], $_[1], @_, internal => 1)
1772 sub match_link ($$;@) { #{{{
1777 my $from=exists $params{location} ? $params{location} : '';
1780 if ($link =~ m!^\.! && defined $from) {
1781 $from=~s#/?[^/]+$##;
1783 $link="$from/$link" if length $from;
1786 my $links = $IkiWiki::links{$page};
1787 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1788 my $bestlink = IkiWiki::bestlink($from, $link);
1789 foreach my $p (@{$links}) {
1790 if (length $bestlink) {
1791 return IkiWiki::SuccessReason->new("$page links to $link")
1792 if $bestlink eq IkiWiki::bestlink($page, $p);
1795 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1796 if match_glob($p, $link, %params);
1799 return IkiWiki::FailReason->new("$page does not link to $link");
1802 sub match_backlink ($$;@) { #{{{
1803 return match_link($_[1], $_[0], @_);
1806 sub match_created_before ($$;@) { #{{{
1810 if (exists $IkiWiki::pagectime{$testpage}) {
1811 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1812 return IkiWiki::SuccessReason->new("$page created before $testpage");
1815 return IkiWiki::FailReason->new("$page not created before $testpage");
1819 return IkiWiki::FailReason->new("$testpage has no ctime");
1823 sub match_created_after ($$;@) { #{{{
1827 if (exists $IkiWiki::pagectime{$testpage}) {
1828 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1829 return IkiWiki::SuccessReason->new("$page created after $testpage");
1832 return IkiWiki::FailReason->new("$page not created after $testpage");
1836 return IkiWiki::FailReason->new("$testpage has no ctime");
1840 sub match_creation_day ($$;@) { #{{{
1841 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1842 return IkiWiki::SuccessReason->new('creation_day matched');
1845 return IkiWiki::FailReason->new('creation_day did not match');
1849 sub match_creation_month ($$;@) { #{{{
1850 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1851 return IkiWiki::SuccessReason->new('creation_month matched');
1854 return IkiWiki::FailReason->new('creation_month did not match');
1858 sub match_creation_year ($$;@) { #{{{
1859 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1860 return IkiWiki::SuccessReason->new('creation_year matched');
1863 return IkiWiki::FailReason->new('creation_year did not match');