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",
398 allow_symlinks_before_srcdir => {
401 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
407 sub defaultconfig () { #{{{
410 foreach my $key (keys %s) {
411 push @ret, $key, $s{$key}->{default};
417 sub checkconfig () { #{{{
418 # locale stuff; avoid LC_ALL since it overrides everything
419 if (defined $ENV{LC_ALL}) {
420 $ENV{LANG} = $ENV{LC_ALL};
423 if (defined $config{locale}) {
424 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
425 $ENV{LANG}=$config{locale};
430 if (! defined $config{wiki_file_regexp}) {
431 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
434 if (ref $config{ENV} eq 'HASH') {
435 foreach my $val (keys %{$config{ENV}}) {
436 $ENV{$val}=$config{ENV}{$val};
440 if ($config{w3mmode}) {
441 eval q{use Cwd q{abs_path}};
443 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
444 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
445 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
446 unless $config{cgiurl} =~ m!file:///!;
447 $config{url}="file://".$config{destdir};
450 if ($config{cgi} && ! length $config{url}) {
451 error(gettext("Must specify url to wiki with --url when using --cgi"));
454 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
455 unless exists $config{wikistatedir};
457 if (defined $config{umask}) {
458 umask(possibly_foolish_untaint($config{umask}));
461 run_hooks(checkconfig => sub { shift->() });
466 sub listplugins () { #{{{
469 foreach my $dir (@INC, $config{libdir}) {
470 next unless defined $dir && length $dir;
471 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
472 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
476 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
477 next unless defined $dir && length $dir;
478 foreach my $file (glob("$dir/plugins/*")) {
479 $ret{basename($file)}=1 if -x $file;
486 sub loadplugins () { #{{{
487 if (defined $config{libdir} && length $config{libdir}) {
488 unshift @INC, possibly_foolish_untaint($config{libdir});
491 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
496 if (exists $IkiWiki::hooks{rcs}) {
497 error(gettext("cannot use multiple rcs plugins"));
499 loadplugin($config{rcs});
501 if (! exists $IkiWiki::hooks{rcs}) {
505 run_hooks(getopt => sub { shift->() });
506 if (grep /^-/, @ARGV) {
507 print STDERR "Unknown option: $_\n"
508 foreach grep /^-/, @ARGV;
515 sub loadplugin ($) { #{{{
518 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
520 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
521 "$installdir/lib/ikiwiki") {
522 if (defined $dir && -x "$dir/plugins/$plugin") {
523 require IkiWiki::Plugin::external;
524 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
525 $loaded_plugins{$plugin}=1;
530 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
533 error("Failed to load plugin $mod: $@");
535 $loaded_plugins{$plugin}=1;
539 sub error ($;$) { #{{{
542 log_message('err' => $message) if $config{syslog};
543 if (defined $cleaner) {
550 return unless $config{verbose};
551 return log_message(debug => @_);
555 sub log_message ($$) { #{{{
558 if ($config{syslog}) {
561 Sys::Syslog::setlogsock('unix');
562 Sys::Syslog::openlog('ikiwiki', '', 'user');
566 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
569 elsif (! $config{cgi}) {
573 return print STDERR "@_\n";
577 sub possibly_foolish_untaint ($) { #{{{
579 my ($untainted)=$tainted=~/(.*)/s;
583 sub basename ($) { #{{{
590 sub dirname ($) { #{{{
597 sub pagetype ($) { #{{{
600 if ($page =~ /\.([^.]+)$/) {
601 return $1 if exists $hooks{htmlize}{$1};
606 sub isinternal ($) { #{{{
608 return exists $pagesources{$page} &&
609 $pagesources{$page} =~ /\._([^.]+)$/;
612 sub pagename ($) { #{{{
615 my $type=pagetype($file);
617 $page=~s/\Q.$type\E*$// if defined $type;
621 sub targetpage ($$) { #{{{
625 if (! $config{usedirs} || $page =~ /^index$/ ) {
626 return $page.".".$ext;
628 return $page."/index.".$ext;
632 sub htmlpage ($) { #{{{
635 return targetpage($page, $config{htmlext});
638 sub srcfile_stat { #{{{
642 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
643 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
644 return "$dir/$file", stat(_) if -e "$dir/$file";
646 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
650 sub srcfile ($;$) { #{{{
651 return (srcfile_stat(@_))[0];
654 sub add_underlay ($) { #{{{
658 unshift @{$config{underlaydirs}}, $dir;
661 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
667 sub readfile ($;$$) { #{{{
673 error("cannot read a symlink ($file)");
677 open (my $in, "<", $file) || error("failed to read $file: $!");
678 binmode($in) if ($binary);
679 return \*$in if $wantfd;
681 close $in || error("failed to read $file: $!");
685 sub prep_writefile ($$) { #{{{
690 while (length $test) {
691 if (-l "$destdir/$test") {
692 error("cannot write to a symlink ($test)");
694 $test=dirname($test);
697 my $dir=dirname("$destdir/$file");
700 foreach my $s (split(m!/+!, $dir)) {
703 mkdir($d) || error("failed to create directory $d: $!");
711 sub writefile ($$$;$$) { #{{{
712 my $file=shift; # can include subdirs
713 my $destdir=shift; # directory to put file in
718 prep_writefile($file, $destdir);
720 my $newfile="$destdir/$file.ikiwiki-new";
722 error("cannot write to a symlink ($newfile)");
725 my $cleanup = sub { unlink($newfile) };
726 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
727 binmode($out) if ($binary);
729 $writer->(\*$out, $cleanup);
732 print $out $content or error("failed writing to $newfile: $!", $cleanup);
734 close $out || error("failed saving $newfile: $!", $cleanup);
735 rename($newfile, "$destdir/$file") ||
736 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
742 sub will_render ($$;$) { #{{{
747 # Important security check.
748 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
749 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
750 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
753 if (! $clear || $cleared{$page}) {
754 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
757 foreach my $old (@{$renderedfiles{$page}}) {
758 delete $destsources{$old};
760 $renderedfiles{$page}=[$dest];
763 $destsources{$dest}=$page;
768 sub bestlink ($$) { #{{{
773 if ($link=~s/^\/+//) {
781 $l.="/" if length $l;
784 if (exists $links{$l}) {
787 elsif (exists $pagecase{lc $l}) {
788 return $pagecase{lc $l};
790 } while $cwd=~s{/?[^/]+$}{};
792 if (length $config{userdir}) {
793 my $l = "$config{userdir}/".lc($link);
794 if (exists $links{$l}) {
797 elsif (exists $pagecase{lc $l}) {
798 return $pagecase{lc $l};
802 #print STDERR "warning: page $page, broken link: $link\n";
806 sub isinlinableimage ($) { #{{{
809 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
812 sub pagetitle ($;$) { #{{{
817 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
820 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
826 sub titlepage ($) { #{{{
828 # support use w/o %config set
829 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
830 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
834 sub linkpage ($) { #{{{
836 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
837 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
841 sub cgiurl (@) { #{{{
844 return $config{cgiurl}."?".
845 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
848 sub baseurl (;$) { #{{{
851 return "$config{url}/" if ! defined $page;
853 $page=htmlpage($page);
855 $page=~s/[^\/]+\//..\//g;
859 sub abs2rel ($$) { #{{{
860 # Work around very innefficient behavior in File::Spec if abs2rel
861 # is passed two relative paths. It's much faster if paths are
862 # absolute! (Debian bug #376658; fixed in debian unstable now)
867 my $ret=File::Spec->abs2rel($path, $base);
868 $ret=~s/^// if defined $ret;
872 sub displaytime ($;$) { #{{{
875 if (! defined $format) {
876 $format=$config{timeformat};
879 # strftime doesn't know about encodings, so make sure
880 # its output is properly treated as utf8
881 return decode_utf8(POSIX::strftime($format, localtime($time)));
884 sub beautify_urlpath ($) { #{{{
887 if ($config{usedirs}) {
888 $url =~ s!/index.$config{htmlext}$!/!;
891 # Ensure url is not an empty link, and
892 # if it's relative, make that explicit to avoid colon confusion.
900 sub urlto ($$;$) { #{{{
906 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
909 if (! $destsources{$to}) {
914 return $config{url}.beautify_urlpath("/".$to);
917 my $link = abs2rel($to, dirname(htmlpage($from)));
919 return beautify_urlpath($link);
922 sub htmllink ($$$;@) { #{{{
923 my $lpage=shift; # the page doing the linking
924 my $page=shift; # the page that will contain the link (different for inline)
931 if (! $opts{forcesubpage}) {
932 $bestlink=bestlink($lpage, $link);
935 $bestlink="$lpage/".lc($link);
939 if (defined $opts{linktext}) {
940 $linktext=$opts{linktext};
943 $linktext=pagetitle(basename($link));
946 return "<span class=\"selflink\">$linktext</span>"
947 if length $bestlink && $page eq $bestlink &&
948 ! defined $opts{anchor};
950 if (! $destsources{$bestlink}) {
951 $bestlink=htmlpage($bestlink);
953 if (! $destsources{$bestlink}) {
954 return $linktext unless length $config{cgiurl};
955 return "<span class=\"createlink\"><a href=\"".
961 "\" rel=\"nofollow\">?</a>$linktext</span>"
965 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
966 $bestlink=beautify_urlpath($bestlink);
968 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
969 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
972 if (defined $opts{anchor}) {
973 $bestlink.="#".$opts{anchor};
977 if (defined $opts{rel}) {
978 push @attrs, ' rel="'.$opts{rel}.'"';
980 if (defined $opts{class}) {
981 push @attrs, ' class="'.$opts{class}.'"';
984 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
987 sub userlink ($) { #{{{
990 my $oiduser=eval { openiduser($user) };
991 if (defined $oiduser) {
992 return "<a href=\"$user\">$oiduser</a>";
995 eval q{use CGI 'escapeHTML'};
998 return htmllink("", "", escapeHTML(
999 length $config{userdir} ? $config{userdir}."/".$user : $user
1000 ), noimageinline => 1);
1004 sub htmlize ($$$$) { #{{{
1010 my $oneline = $content !~ /\n/;
1012 if (exists $hooks{htmlize}{$type}) {
1013 $content=$hooks{htmlize}{$type}{call}->(
1015 content => $content,
1019 error("htmlization of $type not supported");
1022 run_hooks(sanitize => sub {
1025 destpage => $destpage,
1026 content => $content,
1031 # hack to get rid of enclosing junk added by markdown
1032 # and other htmlizers
1033 $content=~s/^<p>//i;
1034 $content=~s/<\/p>$//i;
1041 sub linkify ($$$) { #{{{
1046 run_hooks(linkify => sub {
1049 destpage => $destpage,
1050 content => $content,
1058 our $preprocess_preview=0;
1059 sub preprocess ($$$;$$) { #{{{
1060 my $page=shift; # the page the data comes from
1061 my $destpage=shift; # the page the data will appear in (different for inline)
1066 # Using local because it needs to be set within any nested calls
1068 local $preprocess_preview=$preview if defined $preview;
1075 $params="" if ! defined $params;
1077 if (length $escape) {
1078 return "[[$prefix$command $params]]";
1080 elsif (exists $hooks{preprocess}{$command}) {
1081 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1082 # Note: preserve order of params, some plugins may
1083 # consider it significant.
1085 while ($params =~ m{
1086 (?:([-\w]+)=)? # 1: named parameter key?
1088 """(.*?)""" # 2: triple-quoted value
1090 "([^"]+)" # 3: single-quoted value
1092 (\S+) # 4: unquoted value
1094 (?:\s+|$) # delimiter to next param
1104 elsif (defined $3) {
1107 elsif (defined $4) {
1112 push @params, $key, $val;
1115 push @params, $val, '';
1118 if ($preprocessing{$page}++ > 3) {
1119 # Avoid loops of preprocessed pages preprocessing
1120 # other pages that preprocess them, etc.
1121 return "[[!$command <span class=\"error\">".
1122 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1123 $page, $preprocessing{$page}).
1129 $hooks{preprocess}{$command}{call}->(
1132 destpage => $destpage,
1133 preview => $preprocess_preview,
1138 $ret="[[!$command <span class=\"error\">".
1139 gettext("Error").": $@"."</span>]]";
1143 # use void context during scan pass
1145 $hooks{preprocess}{$command}{call}->(
1148 destpage => $destpage,
1149 preview => $preprocess_preview,
1154 $preprocessing{$page}--;
1158 return "[[$prefix$command $params]]";
1163 if ($config{prefix_directives}) {
1166 \[\[(!) # directive open; 2: prefix
1167 ([-\w]+) # 3: command
1168 ( # 4: the parameters..
1169 \s+ # Must have space if parameters present
1171 (?:[-\w]+=)? # named parameter key?
1173 """.*?""" # triple-quoted value
1175 "[^"]+" # single-quoted value
1177 [^\s\]]+ # unquoted value
1179 \s* # whitespace or end
1182 *)? # 0 or more parameters
1183 \]\] # directive closed
1189 \[\[(!?) # directive open; 2: optional prefix
1190 ([-\w]+) # 3: command
1192 ( # 4: the parameters..
1194 (?:[-\w]+=)? # named parameter key?
1196 """.*?""" # triple-quoted value
1198 "[^"]+" # single-quoted value
1200 [^\s\]]+ # unquoted value
1202 \s* # whitespace or end
1205 *) # 0 or more parameters
1206 \]\] # directive closed
1210 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1214 sub filter ($$$) { #{{{
1219 run_hooks(filter => sub {
1220 $content=shift->(page => $page, destpage => $destpage,
1221 content => $content);
1227 sub indexlink () { #{{{
1228 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1233 sub lockwiki (;$) { #{{{
1234 my $wait=@_ ? shift : 1;
1235 # Take an exclusive lock on the wiki to prevent multiple concurrent
1236 # run issues. The lock will be dropped on program exit.
1237 if (! -d $config{wikistatedir}) {
1238 mkdir($config{wikistatedir});
1240 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1241 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1242 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1244 debug("wiki seems to be locked, waiting for lock");
1245 my $wait=600; # arbitrary, but don't hang forever to
1246 # prevent process pileup
1248 return if flock($wikilock, 2 | 4);
1251 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1260 sub unlockwiki () { #{{{
1261 return close($wikilock) if $wikilock;
1267 sub commit_hook_enabled () { #{{{
1268 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1269 error("cannot write to $config{wikistatedir}/commitlock: $!");
1270 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1271 close($commitlock) || error("failed closing commitlock: $!");
1274 close($commitlock) || error("failed closing commitlock: $!");
1278 sub disable_commit_hook () { #{{{
1279 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1280 error("cannot write to $config{wikistatedir}/commitlock: $!");
1281 if (! flock($commitlock, 2)) { # LOCK_EX
1282 error("failed to get commit lock");
1287 sub enable_commit_hook () { #{{{
1288 return close($commitlock) if $commitlock;
1292 sub loadindex () { #{{{
1293 %oldrenderedfiles=%pagectime=();
1294 if (! $config{rebuild}) {
1295 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1296 %destsources=%renderedfiles=%pagecase=%pagestate=();
1299 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1300 if (-e "$config{wikistatedir}/index") {
1301 system("ikiwiki-transition", "indexdb", $config{srcdir});
1302 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1308 my $ret=Storable::fd_retrieve($in);
1309 if (! defined $ret) {
1313 foreach my $src (keys %index) {
1314 my %d=%{$index{$src}};
1315 my $page=pagename($src);
1316 $pagectime{$page}=$d{ctime};
1317 if (! $config{rebuild}) {
1318 $pagesources{$page}=$src;
1319 $pagemtime{$page}=$d{mtime};
1320 $renderedfiles{$page}=$d{dest};
1321 if (exists $d{links} && ref $d{links}) {
1322 $links{$page}=$d{links};
1323 $oldlinks{$page}=[@{$d{links}}];
1325 if (exists $d{depends}) {
1326 $depends{$page}=$d{depends};
1328 if (exists $d{state}) {
1329 $pagestate{$page}=$d{state};
1332 $oldrenderedfiles{$page}=[@{$d{dest}}];
1334 foreach my $page (keys %pagesources) {
1335 $pagecase{lc $page}=$page;
1337 foreach my $page (keys %renderedfiles) {
1338 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1343 sub saveindex () { #{{{
1344 run_hooks(savestate => sub { shift->() });
1347 foreach my $type (keys %hooks) {
1348 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1350 my @hookids=keys %hookids;
1352 if (! -d $config{wikistatedir}) {
1353 mkdir($config{wikistatedir});
1355 my $newfile="$config{wikistatedir}/indexdb.new";
1356 my $cleanup = sub { unlink($newfile) };
1357 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1359 foreach my $page (keys %pagemtime) {
1360 next unless $pagemtime{$page};
1361 my $src=$pagesources{$page};
1364 ctime => $pagectime{$page},
1365 mtime => $pagemtime{$page},
1366 dest => $renderedfiles{$page},
1367 links => $links{$page},
1370 if (exists $depends{$page}) {
1371 $index{$src}{depends} = $depends{$page};
1374 if (exists $pagestate{$page}) {
1375 foreach my $id (@hookids) {
1376 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1377 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1382 my $ret=Storable::nstore_fd(\%index, $out);
1383 return if ! defined $ret || ! $ret;
1384 close $out || error("failed saving to $newfile: $!", $cleanup);
1385 rename($newfile, "$config{wikistatedir}/indexdb") ||
1386 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1391 sub template_file ($) { #{{{
1394 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1395 return "$dir/$template" if -e "$dir/$template";
1400 sub template_params (@) { #{{{
1401 my $filename=template_file(shift);
1403 if (! defined $filename) {
1404 return if wantarray;
1410 my $text_ref = shift;
1411 ${$text_ref} = decode_utf8(${$text_ref});
1413 filename => $filename,
1414 loop_context_vars => 1,
1415 die_on_bad_params => 0,
1418 return wantarray ? @ret : {@ret};
1421 sub template ($;@) { #{{{
1422 require HTML::Template;
1423 return HTML::Template->new(template_params(@_));
1426 sub misctemplate ($$;@) { #{{{
1430 my $template=template("misc.tmpl");
1433 indexlink => indexlink(),
1434 wikiname => $config{wikiname},
1435 pagebody => $pagebody,
1436 baseurl => baseurl(),
1439 run_hooks(pagetemplate => sub {
1440 shift->(page => "", destpage => "", template => $template);
1442 return $template->output;
1445 sub hook (@) { # {{{
1448 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1449 error 'hook requires type, call, and id parameters';
1452 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1454 $hooks{$param{type}}{$param{id}}=\%param;
1458 sub run_hooks ($$) { # {{{
1459 # Calls the given sub for each hook of the given type,
1460 # passing it the hook function to call.
1464 if (exists $hooks{$type}) {
1466 foreach my $id (keys %{$hooks{$type}}) {
1467 if ($hooks{$type}{$id}{last}) {
1468 push @deferred, $id;
1471 $sub->($hooks{$type}{$id}{call});
1473 foreach my $id (@deferred) {
1474 $sub->($hooks{$type}{$id}{call});
1481 sub rcs_update () { #{{{
1482 $hooks{rcs}{rcs_update}{call}->(@_);
1485 sub rcs_prepedit ($) { #{{{
1486 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1489 sub rcs_commit ($$$;$$) { #{{{
1490 $hooks{rcs}{rcs_commit}{call}->(@_);
1493 sub rcs_commit_staged ($$$) { #{{{
1494 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1497 sub rcs_add ($) { #{{{
1498 $hooks{rcs}{rcs_add}{call}->(@_);
1501 sub rcs_remove ($) { #{{{
1502 $hooks{rcs}{rcs_remove}{call}->(@_);
1505 sub rcs_rename ($$) { #{{{
1506 $hooks{rcs}{rcs_rename}{call}->(@_);
1509 sub rcs_recentchanges ($) { #{{{
1510 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1513 sub rcs_diff ($) { #{{{
1514 $hooks{rcs}{rcs_diff}{call}->(@_);
1517 sub rcs_getctime ($) { #{{{
1518 $hooks{rcs}{rcs_getctime}{call}->(@_);
1521 sub globlist_to_pagespec ($) { #{{{
1522 my @globlist=split(' ', shift);
1525 foreach my $glob (@globlist) {
1526 if ($glob=~/^!(.*)/) {
1534 my $spec=join(' or ', @spec);
1536 my $skip=join(' and ', @skip);
1538 $spec="$skip and ($spec)";
1547 sub is_globlist ($) { #{{{
1549 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1552 sub safequote ($) { #{{{
1558 sub add_depends ($$) { #{{{
1562 return unless pagespec_valid($pagespec);
1564 if (! exists $depends{$page}) {
1565 $depends{$page}=$pagespec;
1568 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1574 sub file_pruned ($$) { #{{{
1576 my $file=File::Spec->canonpath(shift);
1577 my $base=File::Spec->canonpath(shift);
1578 $file =~ s#^\Q$base\E/+##;
1580 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1581 return $file =~ m/$regexp/ && $file ne $base;
1585 # Only use gettext in the rare cases it's needed.
1586 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1587 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1588 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1589 if (! $gettext_obj) {
1590 $gettext_obj=eval q{
1591 use Locale::gettext q{textdomain};
1592 Locale::gettext->domain('ikiwiki')
1600 return $gettext_obj->get(shift);
1607 sub yesno ($) { #{{{
1610 return (defined $val && lc($val) eq gettext("yes"));
1613 sub pagespec_merge ($$) { #{{{
1617 return $a if $a eq $b;
1619 # Support for old-style GlobLists.
1620 if (is_globlist($a)) {
1621 $a=globlist_to_pagespec($a);
1623 if (is_globlist($b)) {
1624 $b=globlist_to_pagespec($b);
1627 return "($a) or ($b)";
1630 sub pagespec_translate ($) { #{{{
1633 # Support for old-style GlobLists.
1634 if (is_globlist($spec)) {
1635 $spec=globlist_to_pagespec($spec);
1638 # Convert spec to perl code.
1641 \s* # ignore whitespace
1642 ( # 1: match a single word
1649 \w+\([^\)]*\) # command(params)
1651 [^\s()]+ # any other text
1653 \s* # ignore whitespace
1656 if (lc $word eq 'and') {
1659 elsif (lc $word eq 'or') {
1662 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1665 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1666 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1667 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1674 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1678 if (! length $code) {
1683 return eval 'sub { my $page=shift; '.$code.' }';
1686 sub pagespec_match ($$;@) { #{{{
1691 # Backwards compatability with old calling convention.
1693 unshift @params, 'location';
1696 my $sub=pagespec_translate($spec);
1697 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1698 return $sub->($page, @params);
1701 sub pagespec_valid ($) { #{{{
1704 my $sub=pagespec_translate($spec);
1708 sub glob2re ($) { #{{{
1709 my $re=quotemeta(shift);
1715 package IkiWiki::FailReason;
1718 '""' => sub { ${$_[0]} },
1720 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1727 return bless \$value, $class;
1730 package IkiWiki::SuccessReason;
1733 '""' => sub { ${$_[0]} },
1735 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1742 return bless \$value, $class;
1745 package IkiWiki::PageSpec;
1747 sub match_glob ($$;@) { #{{{
1752 my $from=exists $params{location} ? $params{location} : '';
1755 if ($glob =~ m!^\./!) {
1756 $from=~s#/?[^/]+$##;
1758 $glob="$from/$glob" if length $from;
1761 my $regexp=IkiWiki::glob2re($glob);
1762 if ($page=~/^$regexp$/i) {
1763 if (! IkiWiki::isinternal($page) || $params{internal}) {
1764 return IkiWiki::SuccessReason->new("$glob matches $page");
1767 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1771 return IkiWiki::FailReason->new("$glob does not match $page");
1775 sub match_internal ($$;@) { #{{{
1776 return match_glob($_[0], $_[1], @_, internal => 1)
1779 sub match_link ($$;@) { #{{{
1784 my $from=exists $params{location} ? $params{location} : '';
1787 if ($link =~ m!^\.! && defined $from) {
1788 $from=~s#/?[^/]+$##;
1790 $link="$from/$link" if length $from;
1793 my $links = $IkiWiki::links{$page};
1794 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1795 my $bestlink = IkiWiki::bestlink($from, $link);
1796 foreach my $p (@{$links}) {
1797 if (length $bestlink) {
1798 return IkiWiki::SuccessReason->new("$page links to $link")
1799 if $bestlink eq IkiWiki::bestlink($page, $p);
1802 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1803 if match_glob($p, $link, %params);
1806 return IkiWiki::FailReason->new("$page does not link to $link");
1809 sub match_backlink ($$;@) { #{{{
1810 return match_link($_[1], $_[0], @_);
1813 sub match_created_before ($$;@) { #{{{
1817 if (exists $IkiWiki::pagectime{$testpage}) {
1818 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1819 return IkiWiki::SuccessReason->new("$page created before $testpage");
1822 return IkiWiki::FailReason->new("$page not created before $testpage");
1826 return IkiWiki::FailReason->new("$testpage has no ctime");
1830 sub match_created_after ($$;@) { #{{{
1834 if (exists $IkiWiki::pagectime{$testpage}) {
1835 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1836 return IkiWiki::SuccessReason->new("$page created after $testpage");
1839 return IkiWiki::FailReason->new("$page not created after $testpage");
1843 return IkiWiki::FailReason->new("$testpage has no ctime");
1847 sub match_creation_day ($$;@) { #{{{
1848 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1849 return IkiWiki::SuccessReason->new('creation_day matched');
1852 return IkiWiki::FailReason->new('creation_day did not match');
1856 sub match_creation_month ($$;@) { #{{{
1857 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1858 return IkiWiki::SuccessReason->new('creation_month matched');
1861 return IkiWiki::FailReason->new('creation_month did not match');
1865 sub match_creation_year ($$;@) { #{{{
1866 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1867 return IkiWiki::SuccessReason->new('creation_year matched');
1870 return IkiWiki::FailReason->new('creation_year did not match');