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};
18 use Exporter q{import};
19 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
20 bestlink htmllink readfile writefile pagetype srcfile pagename
21 displaytime will_render gettext urlto targetpage
23 %config %links %pagestate %renderedfiles
24 %pagesources %destsources);
25 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
26 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
27 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
32 memoize("pagespec_translate");
33 memoize("file_pruned");
35 sub getsetup () { #{{{
39 description => "name of the wiki",
46 example => "$ENV{HOME}/wiki",
47 description => "where the source of the wiki is located",
54 example => "/var/www/wiki",
55 description => "where to build the wiki",
62 description => "user names of wiki admins",
69 example => 'me@example.com',
70 description => "contact email for wiki",
77 example => "http://example.com/wiki",
78 description => "base url to the wiki",
85 examples => "http://example.com/wiki/ikiwiki.cgi",
86 description => "url to the ikiwiki.cgi",
93 description => "rcs backend to use",
94 safe => 0, # don't allow overriding
99 default => [qw{mdwn link inline htmlscrubber passwordauth
100 openid signinedit lockedit conditional
101 recentchanges parentlinks}],
102 description => "plugins to enable by default",
109 description => "plugins to add to the default configuration",
116 description => "plugins to disable",
123 description => "definitions of wrappers to generate",
130 description => "wrapper filename",
137 description => "mode of wrapper file",
143 default => "$installdir/share/ikiwiki/templates",
144 description => "location of template files",
150 default => "$installdir/share/ikiwiki/basewiki",
151 description => "base wiki source location",
158 description => "additional underlays to use",
165 description => "display verbose messages when building?",
172 description => "log to syslog?",
179 description => "create output files named page/index.html?",
180 safe => 0, # changing requires manual transition
183 prefix_directives => {
186 description => "use '!'-prefixed preprocessor directives?",
187 safe => 0, # changing requires manual transition
193 description => "enable Discussion pages?",
200 description => "extension to use for new pages",
201 safe => 0, # not sanitized
207 description => "extension to use for html files",
208 safe => 0, # not sanitized
214 description => "strftime format string to display date",
221 example => "en_US.UTF-8",
222 description => "UTF-8 locale to use",
229 description => "only send cookies over SSL connections?",
237 description => "put user pages below specified page",
244 description => "how many backlinks to show before hiding excess (0 to show all)",
251 description => "attempt to hardlink source files? (optimisation for large files)",
252 safe => 0, # paranoia
260 description => "regexp of source files to ignore",
264 wiki_file_prune_regexps => {
266 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
267 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
268 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
271 description => "regexps of source files to ignore",
275 wiki_file_regexp => {
277 default => qr/(^[-[:alnum:]_.:\/+]+$)/,
278 description => "regexp of legal source files",
282 web_commit_regexp => {
284 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
285 description => "regexp to parse web commits from logs",
292 description => "run as a cgi",
296 cgi_disable_uploads => {
299 description => "whether CGI should accept file uploads",
306 description => "run as a post-commit hook",
313 description => "running in rebuild mode",
320 description => "running in refresh mode",
327 description => "running in getctime mode",
334 description => "running in w3mmode",
341 description => "setup file to read",
348 example => "$ENV{HOME}/.ikiwiki/",
349 description => "extra library and plugin directory",
355 sub defaultconfig () { #{{{
358 foreach my $key (keys %s) {
359 push @ret, $key, $s{$key}->{default};
365 sub checkconfig () { #{{{
366 # locale stuff; avoid LC_ALL since it overrides everything
367 if (defined $ENV{LC_ALL}) {
368 $ENV{LANG} = $ENV{LC_ALL};
371 if (defined $config{locale}) {
372 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
373 $ENV{LANG}=$config{locale};
378 if (ref $config{ENV} eq 'HASH') {
379 foreach my $val (keys %{$config{ENV}}) {
380 $ENV{$val}=$config{ENV}{$val};
384 if ($config{w3mmode}) {
385 eval q{use Cwd q{abs_path}};
387 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
388 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
389 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
390 unless $config{cgiurl} =~ m!file:///!;
391 $config{url}="file://".$config{destdir};
394 if ($config{cgi} && ! length $config{url}) {
395 error(gettext("Must specify url to wiki with --url when using --cgi"));
398 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
399 unless exists $config{wikistatedir};
402 eval qq{use IkiWiki::Rcs::$config{rcs}};
404 error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
408 require IkiWiki::Rcs::Stub;
411 if (exists $config{umask}) {
412 umask(possibly_foolish_untaint($config{umask}));
415 run_hooks(checkconfig => sub { shift->() });
420 sub loadplugins () { #{{{
421 if (defined $config{libdir}) {
422 unshift @INC, possibly_foolish_untaint($config{libdir});
425 loadplugin($_) foreach @{$config{default_plugins}}, @{$config{add_plugins}};
427 run_hooks(getopt => sub { shift->() });
428 if (grep /^-/, @ARGV) {
429 print STDERR "Unknown option: $_\n"
430 foreach grep /^-/, @ARGV;
437 sub loadplugin ($) { #{{{
440 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
442 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
443 "$installdir/lib/ikiwiki") {
444 if (defined $dir && -x "$dir/plugins/$plugin") {
445 require IkiWiki::Plugin::external;
446 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
451 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
454 error("Failed to load plugin $mod: $@");
459 sub error ($;$) { #{{{
462 log_message('err' => $message) if $config{syslog};
463 if (defined $cleaner) {
470 return unless $config{verbose};
471 return log_message(debug => @_);
475 sub log_message ($$) { #{{{
478 if ($config{syslog}) {
481 Sys::Syslog::setlogsock('unix');
482 Sys::Syslog::openlog('ikiwiki', '', 'user');
486 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
489 elsif (! $config{cgi}) {
493 return print STDERR "@_\n";
497 sub possibly_foolish_untaint ($) { #{{{
499 my ($untainted)=$tainted=~/(.*)/s;
503 sub basename ($) { #{{{
510 sub dirname ($) { #{{{
517 sub pagetype ($) { #{{{
520 if ($page =~ /\.([^.]+)$/) {
521 return $1 if exists $hooks{htmlize}{$1};
526 sub isinternal ($) { #{{{
528 return exists $pagesources{$page} &&
529 $pagesources{$page} =~ /\._([^.]+)$/;
532 sub pagename ($) { #{{{
535 my $type=pagetype($file);
537 $page=~s/\Q.$type\E*$// if defined $type;
541 sub targetpage ($$) { #{{{
545 if (! $config{usedirs} || $page =~ /^index$/ ) {
546 return $page.".".$ext;
548 return $page."/index.".$ext;
552 sub htmlpage ($) { #{{{
555 return targetpage($page, $config{htmlext});
558 sub srcfile_stat { #{{{
562 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
563 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
564 return "$dir/$file", stat(_) if -e "$dir/$file";
566 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
570 sub srcfile ($;$) { #{{{
571 return (srcfile_stat(@_))[0];
574 sub add_underlay ($) { #{{{
578 unshift @{$config{underlaydirs}}, $dir;
581 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
587 sub readfile ($;$$) { #{{{
593 error("cannot read a symlink ($file)");
597 open (my $in, "<", $file) || error("failed to read $file: $!");
598 binmode($in) if ($binary);
599 return \*$in if $wantfd;
601 close $in || error("failed to read $file: $!");
605 sub prep_writefile ($$) { #{{{
610 while (length $test) {
611 if (-l "$destdir/$test") {
612 error("cannot write to a symlink ($test)");
614 $test=dirname($test);
617 my $dir=dirname("$destdir/$file");
620 foreach my $s (split(m!/+!, $dir)) {
623 mkdir($d) || error("failed to create directory $d: $!");
631 sub writefile ($$$;$$) { #{{{
632 my $file=shift; # can include subdirs
633 my $destdir=shift; # directory to put file in
638 prep_writefile($file, $destdir);
640 my $newfile="$destdir/$file.ikiwiki-new";
642 error("cannot write to a symlink ($newfile)");
645 my $cleanup = sub { unlink($newfile) };
646 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
647 binmode($out) if ($binary);
649 $writer->(\*$out, $cleanup);
652 print $out $content or error("failed writing to $newfile: $!", $cleanup);
654 close $out || error("failed saving $newfile: $!", $cleanup);
655 rename($newfile, "$destdir/$file") ||
656 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
662 sub will_render ($$;$) { #{{{
667 # Important security check.
668 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
669 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
670 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
673 if (! $clear || $cleared{$page}) {
674 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
677 foreach my $old (@{$renderedfiles{$page}}) {
678 delete $destsources{$old};
680 $renderedfiles{$page}=[$dest];
683 $destsources{$dest}=$page;
688 sub bestlink ($$) { #{{{
693 if ($link=~s/^\/+//) {
701 $l.="/" if length $l;
704 if (exists $links{$l}) {
707 elsif (exists $pagecase{lc $l}) {
708 return $pagecase{lc $l};
710 } while $cwd=~s!/?[^/]+$!!;
712 if (length $config{userdir}) {
713 my $l = "$config{userdir}/".lc($link);
714 if (exists $links{$l}) {
717 elsif (exists $pagecase{lc $l}) {
718 return $pagecase{lc $l};
722 #print STDERR "warning: page $page, broken link: $link\n";
726 sub isinlinableimage ($) { #{{{
729 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
732 sub pagetitle ($;$) { #{{{
737 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
740 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
746 sub titlepage ($) { #{{{
748 $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
752 sub linkpage ($) { #{{{
754 $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
758 sub cgiurl (@) { #{{{
761 return $config{cgiurl}."?".
762 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
765 sub baseurl (;$) { #{{{
768 return "$config{url}/" if ! defined $page;
770 $page=htmlpage($page);
772 $page=~s/[^\/]+\//..\//g;
776 sub abs2rel ($$) { #{{{
777 # Work around very innefficient behavior in File::Spec if abs2rel
778 # is passed two relative paths. It's much faster if paths are
779 # absolute! (Debian bug #376658; fixed in debian unstable now)
784 my $ret=File::Spec->abs2rel($path, $base);
785 $ret=~s/^// if defined $ret;
789 sub displaytime ($;$) { #{{{
792 if (! defined $format) {
793 $format=$config{timeformat};
796 # strftime doesn't know about encodings, so make sure
797 # its output is properly treated as utf8
798 return decode_utf8(POSIX::strftime($format, localtime($time)));
801 sub beautify_urlpath ($) { #{{{
804 if ($config{usedirs}) {
805 $url =~ s!/index.$config{htmlext}$!/!;
808 # Ensure url is not an empty link, and
809 # if it's relative, make that explicit to avoid colon confusion.
817 sub urlto ($$;$) { #{{{
823 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
826 if (! $destsources{$to}) {
831 return $config{url}.beautify_urlpath("/".$to);
834 my $link = abs2rel($to, dirname(htmlpage($from)));
836 return beautify_urlpath($link);
839 sub htmllink ($$$;@) { #{{{
840 my $lpage=shift; # the page doing the linking
841 my $page=shift; # the page that will contain the link (different for inline)
848 if (! $opts{forcesubpage}) {
849 $bestlink=bestlink($lpage, $link);
852 $bestlink="$lpage/".lc($link);
856 if (defined $opts{linktext}) {
857 $linktext=$opts{linktext};
860 $linktext=pagetitle(basename($link));
863 return "<span class=\"selflink\">$linktext</span>"
864 if length $bestlink && $page eq $bestlink &&
865 ! defined $opts{anchor};
867 if (! $destsources{$bestlink}) {
868 $bestlink=htmlpage($bestlink);
870 if (! $destsources{$bestlink}) {
871 return $linktext unless length $config{cgiurl};
872 return "<span class=\"createlink\"><a href=\"".
878 "\" rel=\"nofollow\">?</a>$linktext</span>"
882 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
883 $bestlink=beautify_urlpath($bestlink);
885 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
886 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
889 if (defined $opts{anchor}) {
890 $bestlink.="#".$opts{anchor};
894 if (defined $opts{rel}) {
895 push @attrs, ' rel="'.$opts{rel}.'"';
897 if (defined $opts{class}) {
898 push @attrs, ' class="'.$opts{class}.'"';
901 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
904 sub userlink ($) { #{{{
907 my $oiduser=eval { openiduser($user) };
908 if (defined $oiduser) {
909 return "<a href=\"$user\">$oiduser</a>";
912 eval q{use CGI 'escapeHTML'};
915 return htmllink("", "", escapeHTML(
916 length $config{userdir} ? $config{userdir}."/".$user : $user
917 ), noimageinline => 1);
921 sub htmlize ($$$$) { #{{{
927 my $oneline = $content !~ /\n/;
929 if (exists $hooks{htmlize}{$type}) {
930 $content=$hooks{htmlize}{$type}{call}->(
936 error("htmlization of $type not supported");
939 run_hooks(sanitize => sub {
942 destpage => $destpage,
948 # hack to get rid of enclosing junk added by markdown
949 # and other htmlizers
951 $content=~s/<\/p>$//i;
958 sub linkify ($$$) { #{{{
963 run_hooks(linkify => sub {
966 destpage => $destpage,
975 our $preprocess_preview=0;
976 sub preprocess ($$$;$$) { #{{{
977 my $page=shift; # the page the data comes from
978 my $destpage=shift; # the page the data will appear in (different for inline)
983 # Using local because it needs to be set within any nested calls
985 local $preprocess_preview=$preview if defined $preview;
992 if (length $escape) {
993 return "[[$prefix$command $params]]";
995 elsif (exists $hooks{preprocess}{$command}) {
996 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
997 # Note: preserve order of params, some plugins may
998 # consider it significant.
1000 while ($params =~ m{
1001 (?:([-\w]+)=)? # 1: named parameter key?
1003 """(.*?)""" # 2: triple-quoted value
1005 "([^"]+)" # 3: single-quoted value
1007 (\S+) # 4: unquoted value
1009 (?:\s+|$) # delimiter to next param
1019 elsif (defined $3) {
1022 elsif (defined $4) {
1027 push @params, $key, $val;
1030 push @params, $val, '';
1033 if ($preprocessing{$page}++ > 3) {
1034 # Avoid loops of preprocessed pages preprocessing
1035 # other pages that preprocess them, etc.
1036 #translators: The first parameter is a
1037 #translators: preprocessor directive name,
1038 #translators: the second a page name, the
1039 #translators: third a number.
1040 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
1041 $command, $page, $preprocessing{$page}).
1047 $hooks{preprocess}{$command}{call}->(
1050 destpage => $destpage,
1051 preview => $preprocess_preview,
1056 $ret="[[!$command <span class=\"error\">".
1057 gettext("Error").": $@"."</span>]]";
1061 # use void context during scan pass
1063 $hooks{preprocess}{$command}{call}->(
1066 destpage => $destpage,
1067 preview => $preprocess_preview,
1072 $preprocessing{$page}--;
1076 return "[[$prefix$command $params]]";
1081 if ($config{prefix_directives}) {
1084 \[\[(!) # directive open; 2: prefix
1085 ([-\w]+) # 3: command
1086 ( # 4: the parameters..
1087 \s+ # Must have space if parameters present
1089 (?:[-\w]+=)? # named parameter key?
1091 """.*?""" # triple-quoted value
1093 "[^"]+" # single-quoted value
1095 [^\s\]]+ # unquoted value
1097 \s* # whitespace or end
1100 *)? # 0 or more parameters
1101 \]\] # directive closed
1107 \[\[(!?) # directive open; 2: optional prefix
1108 ([-\w]+) # 3: command
1110 ( # 4: the parameters..
1112 (?:[-\w]+=)? # named parameter key?
1114 """.*?""" # triple-quoted value
1116 "[^"]+" # single-quoted value
1118 [^\s\]]+ # unquoted value
1120 \s* # whitespace or end
1123 *) # 0 or more parameters
1124 \]\] # directive closed
1128 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1132 sub filter ($$$) { #{{{
1137 run_hooks(filter => sub {
1138 $content=shift->(page => $page, destpage => $destpage,
1139 content => $content);
1145 sub indexlink () { #{{{
1146 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1151 sub lockwiki (;$) { #{{{
1152 my $wait=@_ ? shift : 1;
1153 # Take an exclusive lock on the wiki to prevent multiple concurrent
1154 # run issues. The lock will be dropped on program exit.
1155 if (! -d $config{wikistatedir}) {
1156 mkdir($config{wikistatedir});
1158 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1159 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1160 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1162 debug("wiki seems to be locked, waiting for lock");
1163 my $wait=600; # arbitrary, but don't hang forever to
1164 # prevent process pileup
1166 return if flock($wikilock, 2 | 4);
1169 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1178 sub unlockwiki () { #{{{
1179 return close($wikilock) if $wikilock;
1185 sub commit_hook_enabled () { #{{{
1186 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1187 error("cannot write to $config{wikistatedir}/commitlock: $!");
1188 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1189 close($commitlock) || error("failed closing commitlock: $!");
1192 close($commitlock) || error("failed closing commitlock: $!");
1196 sub disable_commit_hook () { #{{{
1197 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1198 error("cannot write to $config{wikistatedir}/commitlock: $!");
1199 if (! flock($commitlock, 2)) { # LOCK_EX
1200 error("failed to get commit lock");
1205 sub enable_commit_hook () { #{{{
1206 return close($commitlock) if $commitlock;
1210 sub loadindex () { #{{{
1211 %oldrenderedfiles=%pagectime=();
1212 if (! $config{rebuild}) {
1213 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1214 %destsources=%renderedfiles=%pagecase=%pagestate=();
1217 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1218 if (-e "$config{wikistatedir}/index") {
1219 system("ikiwiki-transition", "indexdb", $config{srcdir});
1220 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1226 my $ret=Storable::fd_retrieve($in);
1227 if (! defined $ret) {
1231 foreach my $src (keys %index) {
1232 my %d=%{$index{$src}};
1233 my $page=pagename($src);
1234 $pagectime{$page}=$d{ctime};
1235 if (! $config{rebuild}) {
1236 $pagesources{$page}=$src;
1237 $pagemtime{$page}=$d{mtime};
1238 $renderedfiles{$page}=$d{dest};
1239 if (exists $d{links} && ref $d{links}) {
1240 $links{$page}=$d{links};
1241 $oldlinks{$page}=[@{$d{links}}];
1243 if (exists $d{depends}) {
1244 $depends{$page}=$d{depends};
1246 if (exists $d{state}) {
1247 $pagestate{$page}=$d{state};
1250 $oldrenderedfiles{$page}=[@{$d{dest}}];
1252 foreach my $page (keys %pagesources) {
1253 $pagecase{lc $page}=$page;
1255 foreach my $page (keys %renderedfiles) {
1256 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1261 sub saveindex () { #{{{
1262 run_hooks(savestate => sub { shift->() });
1265 foreach my $type (keys %hooks) {
1266 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1268 my @hookids=keys %hookids;
1270 if (! -d $config{wikistatedir}) {
1271 mkdir($config{wikistatedir});
1273 my $newfile="$config{wikistatedir}/indexdb.new";
1274 my $cleanup = sub { unlink($newfile) };
1275 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1277 foreach my $page (keys %pagemtime) {
1278 next unless $pagemtime{$page};
1279 my $src=$pagesources{$page};
1282 ctime => $pagectime{$page},
1283 mtime => $pagemtime{$page},
1284 dest => $renderedfiles{$page},
1285 links => $links{$page},
1288 if (exists $depends{$page}) {
1289 $index{$src}{depends} = $depends{$page};
1292 if (exists $pagestate{$page}) {
1293 foreach my $id (@hookids) {
1294 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1295 $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1300 my $ret=Storable::nstore_fd(\%index, $out);
1301 return if ! defined $ret || ! $ret;
1302 close $out || error("failed saving to $newfile: $!", $cleanup);
1303 rename($newfile, "$config{wikistatedir}/indexdb") ||
1304 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1309 sub template_file ($) { #{{{
1312 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1313 return "$dir/$template" if -e "$dir/$template";
1318 sub template_params (@) { #{{{
1319 my $filename=template_file(shift);
1321 if (! defined $filename) {
1322 return if wantarray;
1328 my $text_ref = shift;
1329 ${$text_ref} = decode_utf8(${$text_ref});
1331 filename => $filename,
1332 loop_context_vars => 1,
1333 die_on_bad_params => 0,
1336 return wantarray ? @ret : {@ret};
1339 sub template ($;@) { #{{{
1340 require HTML::Template;
1341 return HTML::Template->new(template_params(@_));
1344 sub misctemplate ($$;@) { #{{{
1348 my $template=template("misc.tmpl");
1351 indexlink => indexlink(),
1352 wikiname => $config{wikiname},
1353 pagebody => $pagebody,
1354 baseurl => baseurl(),
1357 run_hooks(pagetemplate => sub {
1358 shift->(page => "", destpage => "", template => $template);
1360 return $template->output;
1363 sub hook (@) { # {{{
1366 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1367 error 'hook requires type, call, and id parameters';
1370 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1372 $hooks{$param{type}}{$param{id}}=\%param;
1376 sub run_hooks ($$) { # {{{
1377 # Calls the given sub for each hook of the given type,
1378 # passing it the hook function to call.
1382 if (exists $hooks{$type}) {
1384 foreach my $id (keys %{$hooks{$type}}) {
1385 if ($hooks{$type}{$id}{last}) {
1386 push @deferred, $id;
1389 $sub->($hooks{$type}{$id}{call});
1391 foreach my $id (@deferred) {
1392 $sub->($hooks{$type}{$id}{call});
1399 sub globlist_to_pagespec ($) { #{{{
1400 my @globlist=split(' ', shift);
1403 foreach my $glob (@globlist) {
1404 if ($glob=~/^!(.*)/) {
1412 my $spec=join(' or ', @spec);
1414 my $skip=join(' and ', @skip);
1416 $spec="$skip and ($spec)";
1425 sub is_globlist ($) { #{{{
1427 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1430 sub safequote ($) { #{{{
1436 sub add_depends ($$) { #{{{
1440 return unless pagespec_valid($pagespec);
1442 if (! exists $depends{$page}) {
1443 $depends{$page}=$pagespec;
1446 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1452 sub file_pruned ($$) { #{{{
1454 my $file=File::Spec->canonpath(shift);
1455 my $base=File::Spec->canonpath(shift);
1456 $file =~ s#^\Q$base\E/+##;
1458 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1459 return $file =~ m/$regexp/ && $file ne $base;
1463 # Only use gettext in the rare cases it's needed.
1464 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1465 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1466 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1467 if (! $gettext_obj) {
1468 $gettext_obj=eval q{
1469 use Locale::gettext q{textdomain};
1470 Locale::gettext->domain('ikiwiki')
1478 return $gettext_obj->get(shift);
1485 sub yesno ($) { #{{{
1488 return (defined $val && lc($val) eq gettext("yes"));
1491 sub pagespec_merge ($$) { #{{{
1495 return $a if $a eq $b;
1497 # Support for old-style GlobLists.
1498 if (is_globlist($a)) {
1499 $a=globlist_to_pagespec($a);
1501 if (is_globlist($b)) {
1502 $b=globlist_to_pagespec($b);
1505 return "($a) or ($b)";
1508 sub pagespec_translate ($) { #{{{
1511 # Support for old-style GlobLists.
1512 if (is_globlist($spec)) {
1513 $spec=globlist_to_pagespec($spec);
1516 # Convert spec to perl code.
1519 \s* # ignore whitespace
1520 ( # 1: match a single word
1527 \w+\([^\)]*\) # command(params)
1529 [^\s()]+ # any other text
1531 \s* # ignore whitespace
1534 if (lc $word eq 'and') {
1537 elsif (lc $word eq 'or') {
1540 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1543 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1544 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1545 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1552 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1556 if (! length $code) {
1561 return eval 'sub { my $page=shift; '.$code.' }';
1564 sub pagespec_match ($$;@) { #{{{
1569 # Backwards compatability with old calling convention.
1571 unshift @params, 'location';
1574 my $sub=pagespec_translate($spec);
1575 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1576 return $sub->($page, @params);
1579 sub pagespec_valid ($) { #{{{
1582 my $sub=pagespec_translate($spec);
1586 sub glob2re ($) { #{{{
1587 my $re=quotemeta(shift);
1593 package IkiWiki::FailReason;
1596 '""' => sub { ${$_[0]} },
1598 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1605 return bless \$value, $class;
1608 package IkiWiki::SuccessReason;
1611 '""' => sub { ${$_[0]} },
1613 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1620 return bless \$value, $class;
1623 package IkiWiki::PageSpec;
1625 sub match_glob ($$;@) { #{{{
1630 my $from=exists $params{location} ? $params{location} : '';
1633 if ($glob =~ m!^\./!) {
1634 $from=~s#/?[^/]+$##;
1636 $glob="$from/$glob" if length $from;
1639 my $regexp=IkiWiki::glob2re($glob);
1640 if ($page=~/^$regexp$/i) {
1641 if (! IkiWiki::isinternal($page) || $params{internal}) {
1642 return IkiWiki::SuccessReason->new("$glob matches $page");
1645 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1649 return IkiWiki::FailReason->new("$glob does not match $page");
1653 sub match_internal ($$;@) { #{{{
1654 return match_glob($_[0], $_[1], @_, internal => 1)
1657 sub match_link ($$;@) { #{{{
1662 my $from=exists $params{location} ? $params{location} : '';
1665 if ($link =~ m!^\.! && defined $from) {
1666 $from=~s#/?[^/]+$##;
1668 $link="$from/$link" if length $from;
1671 my $links = $IkiWiki::links{$page};
1672 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1673 my $bestlink = IkiWiki::bestlink($from, $link);
1674 foreach my $p (@{$links}) {
1675 if (length $bestlink) {
1676 return IkiWiki::SuccessReason->new("$page links to $link")
1677 if $bestlink eq IkiWiki::bestlink($page, $p);
1680 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1681 if match_glob($p, $link, %params);
1684 return IkiWiki::FailReason->new("$page does not link to $link");
1687 sub match_backlink ($$;@) { #{{{
1688 return match_link($_[1], $_[0], @_);
1691 sub match_created_before ($$;@) { #{{{
1695 if (exists $IkiWiki::pagectime{$testpage}) {
1696 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1697 return IkiWiki::SuccessReason->new("$page created before $testpage");
1700 return IkiWiki::FailReason->new("$page not created before $testpage");
1704 return IkiWiki::FailReason->new("$testpage has no ctime");
1708 sub match_created_after ($$;@) { #{{{
1712 if (exists $IkiWiki::pagectime{$testpage}) {
1713 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1714 return IkiWiki::SuccessReason->new("$page created after $testpage");
1717 return IkiWiki::FailReason->new("$page not created after $testpage");
1721 return IkiWiki::FailReason->new("$testpage has no ctime");
1725 sub match_creation_day ($$;@) { #{{{
1726 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1727 return IkiWiki::SuccessReason->new('creation_day matched');
1730 return IkiWiki::FailReason->new('creation_day did not match');
1734 sub match_creation_month ($$;@) { #{{{
1735 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1736 return IkiWiki::SuccessReason->new('creation_month matched');
1739 return IkiWiki::FailReason->new('creation_month did not match');
1743 sub match_creation_year ($$;@) { #{{{
1744 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1745 return IkiWiki::SuccessReason->new('creation_year matched');
1748 return IkiWiki::FailReason->new('creation_year did not match');