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 %wikistate %renderedfiles %oldrenderedfiles
16 %pagesources %destsources %depends %hooks %forcerebuild
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
21 pagespec_match_list bestlink htmllink readfile writefile
22 pagetype srcfile pagename displaytime will_render gettext urlto
23 targetpage add_underlay pagetitle titlepage linkpage
24 newpagefile inject add_link
25 %config %links %pagestate %wikistate %renderedfiles
26 %pagesources %destsources);
27 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
28 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
29 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
34 memoize("pagespec_translate");
35 memoize("file_pruned");
41 description => "name of the wiki",
48 example => 'me@example.com',
49 description => "contact email for wiki",
56 description => "users who are wiki admins",
63 description => "users who are banned from the wiki",
70 example => "$ENV{HOME}/wiki",
71 description => "where the source of the wiki is located",
78 example => "/var/www/wiki",
79 description => "where to build the wiki",
86 example => "http://example.com/wiki",
87 description => "base url to the wiki",
94 example => "http://example.com/wiki/ikiwiki.cgi",
95 description => "url to the ikiwiki.cgi",
102 example => "/var/www/wiki/ikiwiki.cgi",
103 description => "filename of cgi wrapper to generate",
110 description => "mode for cgi_wrapper (can safely be made suid)",
117 description => "rcs backend to use",
118 safe => 0, # don't allow overriding
123 default => [qw{mdwn link inline meta htmlscrubber passwordauth
124 openid signinedit lockedit conditional
125 recentchanges parentlinks editpage}],
126 description => "plugins to enable by default",
133 description => "plugins to add to the default configuration",
140 description => "plugins to disable",
146 default => "$installdir/share/ikiwiki/templates",
147 description => "location of template files",
154 default => "$installdir/share/ikiwiki/basewiki",
155 description => "base wiki source location",
162 default => "$installdir/share/ikiwiki",
163 description => "parent directory containing additional underlays",
170 description => "wrappers to generate",
177 description => "additional underlays to use",
184 description => "display verbose messages?",
191 description => "log to syslog?",
198 description => "create output files named page/index.html?",
199 safe => 0, # changing requires manual transition
202 prefix_directives => {
205 description => "use '!'-prefixed preprocessor directives?",
206 safe => 0, # changing requires manual transition
212 description => "use page/index.mdwn source files",
219 description => "enable Discussion pages?",
226 description => "only send cookies over SSL connections?",
234 description => "extension to use for new pages",
235 safe => 0, # not sanitized
241 description => "extension to use for html files",
242 safe => 0, # not sanitized
248 description => "strftime format string to display date",
256 example => "en_US.UTF-8",
257 description => "UTF-8 locale to use",
266 description => "put user pages below specified page",
273 description => "how many backlinks to show before hiding excess (0 to show all)",
280 description => "attempt to hardlink source files? (optimisation for large files)",
282 safe => 0, # paranoia
288 description => "force ikiwiki to use a particular umask",
290 safe => 0, # paranoia
295 example => "ikiwiki",
296 description => "group for wrappers to run in",
298 safe => 0, # paranoia
304 example => "$ENV{HOME}/.ikiwiki/",
305 description => "extra library and plugin directory",
307 safe => 0, # directory
313 description => "environment variables",
314 safe => 0, # paranoia
321 description => "regexp of source files to ignore",
326 wiki_file_prune_regexps => {
328 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
329 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
330 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
331 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
333 description => "regexps of source files to ignore",
339 description => "specifies the characters that are allowed in source filenames",
340 default => "-[:alnum:]+/.:_",
344 wiki_file_regexp => {
346 description => "regexp of legal source files",
350 web_commit_regexp => {
352 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
353 description => "regexp to parse web commits from logs",
360 description => "run as a cgi",
364 cgi_disable_uploads => {
367 description => "whether CGI should accept file uploads",
374 description => "run as a post-commit hook",
381 description => "running in rebuild mode",
388 description => "running in setup mode",
395 description => "running in refresh mode",
402 description => "running in receive test mode",
409 description => "running in getctime mode",
416 description => "running in w3mmode",
423 description => "path to the .ikiwiki directory holding ikiwiki state",
430 description => "path to setup file",
434 allow_symlinks_before_srcdir => {
437 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
443 sub defaultconfig () {
446 foreach my $key (keys %s) {
447 push @ret, $key, $s{$key}->{default};
454 # locale stuff; avoid LC_ALL since it overrides everything
455 if (defined $ENV{LC_ALL}) {
456 $ENV{LANG} = $ENV{LC_ALL};
459 if (defined $config{locale}) {
460 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
461 $ENV{LANG}=$config{locale};
466 if (! defined $config{wiki_file_regexp}) {
467 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
470 if (ref $config{ENV} eq 'HASH') {
471 foreach my $val (keys %{$config{ENV}}) {
472 $ENV{$val}=$config{ENV}{$val};
476 if ($config{w3mmode}) {
477 eval q{use Cwd q{abs_path}};
479 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
480 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
481 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
482 unless $config{cgiurl} =~ m!file:///!;
483 $config{url}="file://".$config{destdir};
486 if ($config{cgi} && ! length $config{url}) {
487 error(gettext("Must specify url to wiki with --url when using --cgi"));
490 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
491 unless exists $config{wikistatedir} && defined $config{wikistatedir};
493 if (defined $config{umask}) {
494 umask(possibly_foolish_untaint($config{umask}));
497 run_hooks(checkconfig => sub { shift->() });
505 foreach my $dir (@INC, $config{libdir}) {
506 next unless defined $dir && length $dir;
507 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
508 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
512 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
513 next unless defined $dir && length $dir;
514 foreach my $file (glob("$dir/plugins/*")) {
515 $ret{basename($file)}=1 if -x $file;
523 if (defined $config{libdir} && length $config{libdir}) {
524 unshift @INC, possibly_foolish_untaint($config{libdir});
527 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
532 if (exists $IkiWiki::hooks{rcs}) {
533 error(gettext("cannot use multiple rcs plugins"));
535 loadplugin($config{rcs});
537 if (! exists $IkiWiki::hooks{rcs}) {
541 run_hooks(getopt => sub { shift->() });
542 if (grep /^-/, @ARGV) {
543 print STDERR "Unknown option (or missing parameter): $_\n"
544 foreach grep /^-/, @ARGV;
554 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
556 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
557 "$installdir/lib/ikiwiki") {
558 if (defined $dir && -x "$dir/plugins/$plugin") {
559 eval { require IkiWiki::Plugin::external };
562 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
564 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
565 $loaded_plugins{$plugin}=1;
570 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
573 error("Failed to load plugin $mod: $@");
575 $loaded_plugins{$plugin}=1;
582 log_message('err' => $message) if $config{syslog};
583 if (defined $cleaner) {
590 return unless $config{verbose};
591 return log_message(debug => @_);
595 sub log_message ($$) {
598 if ($config{syslog}) {
601 Sys::Syslog::setlogsock('unix');
602 Sys::Syslog::openlog('ikiwiki', '', 'user');
606 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
609 elsif (! $config{cgi}) {
613 return print STDERR "@_\n";
617 sub possibly_foolish_untaint ($) {
619 my ($untainted)=$tainted=~/(.*)/s;
639 return exists $pagesources{$page} &&
640 $pagesources{$page} =~ /\._([^.]+)$/;
646 if ($file =~ /\.([^.]+)$/) {
647 return $1 if exists $hooks{htmlize}{$1};
649 my $base=basename($file);
650 if (exists $hooks{htmlize}{$base} &&
651 $hooks{htmlize}{$base}{noextension}) {
660 my $type=pagetype($file);
662 $page=~s/\Q.$type\E*$//
663 if defined $type && !$hooks{htmlize}{$type}{keepextension}
664 && !$hooks{htmlize}{$type}{noextension};
665 if ($config{indexpages} && $page=~/(.*)\/index$/) {
671 sub newpagefile ($$) {
675 if (! $config{indexpages} || $page eq 'index') {
676 return $page.".".$type;
679 return $page."/index.".$type;
683 sub targetpage ($$;$) {
688 if (defined $filename) {
689 return $page."/".$filename.".".$ext;
691 elsif (! $config{usedirs} || $page eq 'index') {
692 return $page.".".$ext;
695 return $page."/index.".$ext;
702 return targetpage($page, $config{htmlext});
709 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
710 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
711 return "$dir/$file", stat(_) if -e "$dir/$file";
713 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
718 return (srcfile_stat(@_))[0];
721 sub add_underlay ($) {
725 $dir="$config{underlaydirbase}/$dir";
728 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
729 unshift @{$config{underlaydirs}}, $dir;
735 sub readfile ($;$$) {
741 error("cannot read a symlink ($file)");
745 open (my $in, "<", $file) || error("failed to read $file: $!");
746 binmode($in) if ($binary);
747 return \*$in if $wantfd;
749 # check for invalid utf-8, and toss it back to avoid crashes
750 if (! utf8::valid($ret)) {
751 $ret=encode_utf8($ret);
753 close $in || error("failed to read $file: $!");
757 sub prep_writefile ($$) {
762 while (length $test) {
763 if (-l "$destdir/$test") {
764 error("cannot write to a symlink ($test)");
766 $test=dirname($test);
769 my $dir=dirname("$destdir/$file");
772 foreach my $s (split(m!/+!, $dir)) {
775 mkdir($d) || error("failed to create directory $d: $!");
783 sub writefile ($$$;$$) {
784 my $file=shift; # can include subdirs
785 my $destdir=shift; # directory to put file in
790 prep_writefile($file, $destdir);
792 my $newfile="$destdir/$file.ikiwiki-new";
794 error("cannot write to a symlink ($newfile)");
797 my $cleanup = sub { unlink($newfile) };
798 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
799 binmode($out) if ($binary);
801 $writer->(\*$out, $cleanup);
804 print $out $content or error("failed writing to $newfile: $!", $cleanup);
806 close $out || error("failed saving $newfile: $!", $cleanup);
807 rename($newfile, "$destdir/$file") ||
808 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
814 sub will_render ($$;$) {
819 # Important security check.
820 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
821 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
822 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
825 if (! $clear || $cleared{$page}) {
826 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
829 foreach my $old (@{$renderedfiles{$page}}) {
830 delete $destsources{$old};
832 $renderedfiles{$page}=[$dest];
835 $destsources{$dest}=$page;
845 if ($link=~s/^\/+//) {
853 $l.="/" if length $l;
856 if (exists $links{$l}) {
859 elsif (exists $pagecase{lc $l}) {
860 return $pagecase{lc $l};
862 } while $cwd=~s{/?[^/]+$}{};
864 if (length $config{userdir}) {
865 my $l = "$config{userdir}/".lc($link);
866 if (exists $links{$l}) {
869 elsif (exists $pagecase{lc $l}) {
870 return $pagecase{lc $l};
874 #print STDERR "warning: page $page, broken link: $link\n";
878 sub isinlinableimage ($) {
881 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
884 sub pagetitle ($;$) {
889 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
892 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
900 # support use w/o %config set
901 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
902 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
908 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
909 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
916 return $config{cgiurl}."?".
917 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
923 return "$config{url}/" if ! defined $page;
925 $page=htmlpage($page);
927 $page=~s/[^\/]+\//..\//g;
932 # Work around very innefficient behavior in File::Spec if abs2rel
933 # is passed two relative paths. It's much faster if paths are
934 # absolute! (Debian bug #376658; fixed in debian unstable now)
939 my $ret=File::Spec->abs2rel($path, $base);
940 $ret=~s/^// if defined $ret;
944 sub displaytime ($;$) {
945 # Plugins can override this function to mark up the time to
947 return '<span class="date">'.formattime(@_).'</span>';
950 sub formattime ($;$) {
951 # Plugins can override this function to format the time.
954 if (! defined $format) {
955 $format=$config{timeformat};
958 # strftime doesn't know about encodings, so make sure
959 # its output is properly treated as utf8
960 return decode_utf8(POSIX::strftime($format, localtime($time)));
963 sub beautify_urlpath ($) {
966 # Ensure url is not an empty link, and if necessary,
967 # add ./ to avoid colon confusion.
968 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
972 if ($config{usedirs}) {
973 $url =~ s!/index.$config{htmlext}$!/!;
985 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
988 if (! $destsources{$to}) {
993 return $config{url}.beautify_urlpath("/".$to);
996 my $link = abs2rel($to, dirname(htmlpage($from)));
998 return beautify_urlpath($link);
1001 sub htmllink ($$$;@) {
1002 my $lpage=shift; # the page doing the linking
1003 my $page=shift; # the page that will contain the link (different for inline)
1010 if (! $opts{forcesubpage}) {
1011 $bestlink=bestlink($lpage, $link);
1014 $bestlink="$lpage/".lc($link);
1018 if (defined $opts{linktext}) {
1019 $linktext=$opts{linktext};
1022 $linktext=pagetitle(basename($link));
1025 return "<span class=\"selflink\">$linktext</span>"
1026 if length $bestlink && $page eq $bestlink &&
1027 ! defined $opts{anchor};
1029 if (! $destsources{$bestlink}) {
1030 $bestlink=htmlpage($bestlink);
1032 if (! $destsources{$bestlink}) {
1033 return $linktext unless length $config{cgiurl};
1034 return "<span class=\"createlink\"><a href=\"".
1040 "\" rel=\"nofollow\">?</a>$linktext</span>"
1044 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1045 $bestlink=beautify_urlpath($bestlink);
1047 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1048 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1051 if (defined $opts{anchor}) {
1052 $bestlink.="#".$opts{anchor};
1056 if (defined $opts{rel}) {
1057 push @attrs, ' rel="'.$opts{rel}.'"';
1059 if (defined $opts{class}) {
1060 push @attrs, ' class="'.$opts{class}.'"';
1063 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1069 my $oiduser=eval { openiduser($user) };
1070 if (defined $oiduser) {
1071 return "<a href=\"$user\">$oiduser</a>";
1074 eval q{use CGI 'escapeHTML'};
1077 return htmllink("", "", escapeHTML(
1078 length $config{userdir} ? $config{userdir}."/".$user : $user
1079 ), noimageinline => 1);
1083 sub htmlize ($$$$) {
1089 my $oneline = $content !~ /\n/;
1091 if (exists $hooks{htmlize}{$type}) {
1092 $content=$hooks{htmlize}{$type}{call}->(
1094 content => $content,
1098 error("htmlization of $type not supported");
1101 run_hooks(sanitize => sub {
1104 destpage => $destpage,
1105 content => $content,
1110 # hack to get rid of enclosing junk added by markdown
1111 # and other htmlizers
1112 $content=~s/^<p>//i;
1113 $content=~s/<\/p>$//i;
1125 run_hooks(linkify => sub {
1128 destpage => $destpage,
1129 content => $content,
1137 our $preprocess_preview=0;
1138 sub preprocess ($$$;$$) {
1139 my $page=shift; # the page the data comes from
1140 my $destpage=shift; # the page the data will appear in (different for inline)
1145 # Using local because it needs to be set within any nested calls
1147 local $preprocess_preview=$preview if defined $preview;
1154 $params="" if ! defined $params;
1156 if (length $escape) {
1157 return "[[$prefix$command $params]]";
1159 elsif (exists $hooks{preprocess}{$command}) {
1160 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1161 # Note: preserve order of params, some plugins may
1162 # consider it significant.
1164 while ($params =~ m{
1165 (?:([-\w]+)=)? # 1: named parameter key?
1167 """(.*?)""" # 2: triple-quoted value
1169 "([^"]+)" # 3: single-quoted value
1171 (\S+) # 4: unquoted value
1173 (?:\s+|$) # delimiter to next param
1183 elsif (defined $3) {
1186 elsif (defined $4) {
1191 push @params, $key, $val;
1194 push @params, $val, '';
1197 if ($preprocessing{$page}++ > 3) {
1198 # Avoid loops of preprocessed pages preprocessing
1199 # other pages that preprocess them, etc.
1200 return "[[!$command <span class=\"error\">".
1201 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1202 $page, $preprocessing{$page}).
1208 $hooks{preprocess}{$command}{call}->(
1211 destpage => $destpage,
1212 preview => $preprocess_preview,
1217 $ret="[[!$command <span class=\"error\">".
1218 gettext("Error").": $@"."</span>]]";
1222 # use void context during scan pass
1224 $hooks{preprocess}{$command}{call}->(
1227 destpage => $destpage,
1228 preview => $preprocess_preview,
1233 $preprocessing{$page}--;
1237 return "[[$prefix$command $params]]";
1242 if ($config{prefix_directives}) {
1245 \[\[(!) # directive open; 2: prefix
1246 ([-\w]+) # 3: command
1247 ( # 4: the parameters..
1248 \s+ # Must have space if parameters present
1250 (?:[-\w]+=)? # named parameter key?
1252 """.*?""" # triple-quoted value
1254 "[^"]+" # single-quoted value
1256 [^"\s\]]+ # unquoted value
1258 \s* # whitespace or end
1261 *)? # 0 or more parameters
1262 \]\] # directive closed
1268 \[\[(!?) # directive open; 2: optional prefix
1269 ([-\w]+) # 3: command
1271 ( # 4: the parameters..
1273 (?:[-\w]+=)? # named parameter key?
1275 """.*?""" # triple-quoted value
1277 "[^"]+" # single-quoted value
1279 [^"\s\]]+ # unquoted value
1281 \s* # whitespace or end
1284 *) # 0 or more parameters
1285 \]\] # directive closed
1289 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1298 run_hooks(filter => sub {
1299 $content=shift->(page => $page, destpage => $destpage,
1300 content => $content);
1307 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1310 sub check_canedit ($$$;$) {
1317 run_hooks(canedit => sub {
1318 return if defined $canedit;
1319 my $ret=shift->($page, $q, $session);
1324 elsif (ref $ret eq 'CODE') {
1325 $ret->() unless $nonfatal;
1328 elsif (defined $ret) {
1329 error($ret) unless $nonfatal;
1334 return defined $canedit ? $canedit : 1;
1337 sub check_content (@) {
1340 return 1 if ! exists $hooks{checkcontent}; # optimisation
1342 if (exists $pagesources{$params{page}}) {
1344 my %old=map { $_ => 1 }
1345 split("\n", readfile(srcfile($pagesources{$params{page}})));
1346 foreach my $line (split("\n", $params{content})) {
1347 push @diff, $line if ! exists $old{$_};
1349 $params{content}=join("\n", @diff);
1353 run_hooks(checkcontent => sub {
1354 return if defined $ok;
1355 my $ret=shift->(%params);
1360 elsif (ref $ret eq 'CODE') {
1361 $ret->() unless $params{nonfatal};
1364 elsif (defined $ret) {
1365 error($ret) unless $params{nonfatal};
1371 return defined $ok ? $ok : 1;
1377 # Take an exclusive lock on the wiki to prevent multiple concurrent
1378 # run issues. The lock will be dropped on program exit.
1379 if (! -d $config{wikistatedir}) {
1380 mkdir($config{wikistatedir});
1382 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1383 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1384 if (! flock($wikilock, 2)) { # LOCK_EX
1385 error("failed to get lock");
1391 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1392 return close($wikilock) if $wikilock;
1398 sub commit_hook_enabled () {
1399 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1400 error("cannot write to $config{wikistatedir}/commitlock: $!");
1401 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1402 close($commitlock) || error("failed closing commitlock: $!");
1405 close($commitlock) || error("failed closing commitlock: $!");
1409 sub disable_commit_hook () {
1410 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1411 error("cannot write to $config{wikistatedir}/commitlock: $!");
1412 if (! flock($commitlock, 2)) { # LOCK_EX
1413 error("failed to get commit lock");
1418 sub enable_commit_hook () {
1419 return close($commitlock) if $commitlock;
1424 %oldrenderedfiles=%pagectime=();
1425 if (! $config{rebuild}) {
1426 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1427 %destsources=%renderedfiles=%pagecase=%pagestate=();
1430 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1431 if (-e "$config{wikistatedir}/index") {
1432 system("ikiwiki-transition", "indexdb", $config{srcdir});
1433 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1440 my $index=Storable::fd_retrieve($in);
1441 if (! defined $index) {
1446 if (exists $index->{version} && ! ref $index->{version}) {
1447 $pages=$index->{page};
1448 %wikistate=%{$index->{state}};
1455 foreach my $src (keys %$pages) {
1456 my $d=$pages->{$src};
1457 my $page=pagename($src);
1458 $pagectime{$page}=$d->{ctime};
1459 if (! $config{rebuild}) {
1460 $pagesources{$page}=$src;
1461 $pagemtime{$page}=$d->{mtime};
1462 $renderedfiles{$page}=$d->{dest};
1463 if (exists $d->{links} && ref $d->{links}) {
1464 $links{$page}=$d->{links};
1465 $oldlinks{$page}=[@{$d->{links}}];
1467 if (exists $d->{depends}) {
1468 $depends{$page}=$d->{depends};
1470 if (exists $d->{state}) {
1471 $pagestate{$page}=$d->{state};
1474 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1476 foreach my $page (keys %pagesources) {
1477 $pagecase{lc $page}=$page;
1479 foreach my $page (keys %renderedfiles) {
1480 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1486 run_hooks(savestate => sub { shift->() });
1489 foreach my $type (keys %hooks) {
1490 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1492 my @hookids=keys %hookids;
1494 if (! -d $config{wikistatedir}) {
1495 mkdir($config{wikistatedir});
1497 my $newfile="$config{wikistatedir}/indexdb.new";
1498 my $cleanup = sub { unlink($newfile) };
1499 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1502 foreach my $page (keys %pagemtime) {
1503 next unless $pagemtime{$page};
1504 my $src=$pagesources{$page};
1506 $index{page}{$src}={
1507 ctime => $pagectime{$page},
1508 mtime => $pagemtime{$page},
1509 dest => $renderedfiles{$page},
1510 links => $links{$page},
1513 if (exists $depends{$page}) {
1514 $index{page}{$src}{depends} = $depends{$page};
1517 if (exists $pagestate{$page}) {
1518 foreach my $id (@hookids) {
1519 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1520 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1527 foreach my $id (@hookids) {
1528 foreach my $key (keys %{$wikistate{$id}}) {
1529 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1533 $index{version}="3";
1534 my $ret=Storable::nstore_fd(\%index, $out);
1535 return if ! defined $ret || ! $ret;
1536 close $out || error("failed saving to $newfile: $!", $cleanup);
1537 rename($newfile, "$config{wikistatedir}/indexdb") ||
1538 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1543 sub template_file ($) {
1546 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1547 return "$dir/$template" if -e "$dir/$template";
1552 sub template_params (@) {
1553 my $filename=template_file(shift);
1555 if (! defined $filename) {
1556 return if wantarray;
1562 my $text_ref = shift;
1563 ${$text_ref} = decode_utf8(${$text_ref});
1565 filename => $filename,
1566 loop_context_vars => 1,
1567 die_on_bad_params => 0,
1570 return wantarray ? @ret : {@ret};
1573 sub template ($;@) {
1574 require HTML::Template;
1575 return HTML::Template->new(template_params(@_));
1578 sub misctemplate ($$;@) {
1582 my $template=template("misc.tmpl");
1585 indexlink => indexlink(),
1586 wikiname => $config{wikiname},
1587 pagebody => $pagebody,
1588 baseurl => baseurl(),
1591 run_hooks(pagetemplate => sub {
1592 shift->(page => "", destpage => "", template => $template);
1594 return $template->output;
1600 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1601 error 'hook requires type, call, and id parameters';
1604 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1606 $hooks{$param{type}}{$param{id}}=\%param;
1610 sub run_hooks ($$) {
1611 # Calls the given sub for each hook of the given type,
1612 # passing it the hook function to call.
1616 if (exists $hooks{$type}) {
1617 my (@first, @middle, @last);
1618 foreach my $id (keys %{$hooks{$type}}) {
1619 if ($hooks{$type}{$id}{first}) {
1622 elsif ($hooks{$type}{$id}{last}) {
1629 foreach my $id (@first, @middle, @last) {
1630 $sub->($hooks{$type}{$id}{call});
1638 $hooks{rcs}{rcs_update}{call}->(@_);
1641 sub rcs_prepedit ($) {
1642 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1645 sub rcs_commit ($$$;$$) {
1646 $hooks{rcs}{rcs_commit}{call}->(@_);
1649 sub rcs_commit_staged ($$$) {
1650 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1654 $hooks{rcs}{rcs_add}{call}->(@_);
1657 sub rcs_remove ($) {
1658 $hooks{rcs}{rcs_remove}{call}->(@_);
1661 sub rcs_rename ($$) {
1662 $hooks{rcs}{rcs_rename}{call}->(@_);
1665 sub rcs_recentchanges ($) {
1666 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1670 $hooks{rcs}{rcs_diff}{call}->(@_);
1673 sub rcs_getctime ($) {
1674 $hooks{rcs}{rcs_getctime}{call}->(@_);
1677 sub rcs_receive () {
1678 $hooks{rcs}{rcs_receive}{call}->();
1681 sub add_depends ($$) {
1685 return unless pagespec_valid($pagespec);
1687 if (! exists $depends{$page}) {
1688 $depends{$page}=$pagespec;
1691 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1697 sub file_pruned ($$) {
1699 my $file=File::Spec->canonpath(shift);
1700 my $base=File::Spec->canonpath(shift);
1701 $file =~ s#^\Q$base\E/+##;
1703 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1704 return $file =~ m/$regexp/ && $file ne $base;
1707 sub define_gettext () {
1708 # If translation is needed, redefine the gettext function to do it.
1709 # Otherwise, it becomes a quick no-op.
1710 no warnings 'redefine';
1711 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1712 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1713 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1715 my $gettext_obj=eval q{
1716 use Locale::gettext q{textdomain};
1717 Locale::gettext->domain('ikiwiki')
1721 $gettext_obj->get(shift);
1729 *gettext=sub { return shift };
1741 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1745 # Injects a new function into the symbol table to replace an
1746 # exported function.
1749 # This is deep ugly perl foo, beware.
1752 if (! defined $params{parent}) {
1753 $params{parent}='::';
1754 $params{old}=\&{$params{name}};
1755 $params{name}=~s/.*:://;
1757 my $parent=$params{parent};
1758 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1759 $ns = $params{parent} . $ns;
1760 inject(%params, parent => $ns) unless $ns eq '::main::';
1761 *{$ns . $params{name}} = $params{call}
1762 if exists ${$ns}{$params{name}} &&
1763 \&{${$ns}{$params{name}}} == $params{old};
1773 push @{$links{$page}}, $link
1774 unless grep { $_ eq $link } @{$links{$page}};
1777 sub pagespec_merge ($$) {
1781 return $a if $a eq $b;
1782 return "($a) or ($b)";
1785 sub pagespec_translate ($) {
1788 # Convert spec to perl code.
1792 \s* # ignore whitespace
1793 ( # 1: match a single word
1800 \w+\([^\)]*\) # command(params)
1802 [^\s()]+ # any other text
1804 \s* # ignore whitespace
1807 if (lc $word eq 'and') {
1810 elsif (lc $word eq 'or') {
1813 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1816 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1817 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1819 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
1822 push @data, qq{unknown function in pagespec "$word"};
1823 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
1828 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
1832 if (! length $code) {
1833 $code="IkiWiki::FailReason->new('empty pagespec')";
1837 return eval 'sub { my $page=shift; '.$code.' }';
1840 sub pagespec_match ($$;@) {
1845 # Backwards compatability with old calling convention.
1847 unshift @params, 'location';
1850 my $sub=pagespec_translate($spec);
1851 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
1852 if $@ || ! defined $sub;
1853 return $sub->($page, @params);
1856 sub pagespec_match_list ($$;@) {
1861 my $sub=pagespec_translate($spec);
1862 error "syntax error in pagespec \"$spec\""
1863 if $@ || ! defined $sub;
1867 foreach my $page (@$pages) {
1868 $r=$sub->($page, @params);
1869 push @ret, $page if $r;
1872 if (! @ret && defined $r && $r->isa("IkiWiki::ErrorReason")) {
1873 error(sprintf(gettext("cannot match pages: %s"), $r));
1880 sub pagespec_valid ($) {
1883 my $sub=pagespec_translate($spec);
1888 my $re=quotemeta(shift);
1894 package IkiWiki::FailReason;
1897 '""' => sub { ${$_[0]} },
1899 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1906 return bless \$value, $class;
1909 package IkiWiki::ErrorReason;
1911 our @ISA = 'IkiWiki::FailReason';
1913 package IkiWiki::SuccessReason;
1916 '""' => sub { ${$_[0]} },
1918 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1925 return bless \$value, $class;
1928 package IkiWiki::PageSpec;
1934 if ($path =~ m!^\./!) {
1935 $from=~s#/?[^/]+$## if defined $from;
1937 $path="$from/$path" if length $from;
1943 sub match_glob ($$;@) {
1948 $glob=derel($glob, $params{location});
1950 my $regexp=IkiWiki::glob2re($glob);
1951 if ($page=~/^$regexp$/i) {
1952 if (! IkiWiki::isinternal($page) || $params{internal}) {
1953 return IkiWiki::SuccessReason->new("$glob matches $page");
1956 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1960 return IkiWiki::FailReason->new("$glob does not match $page");
1964 sub match_internal ($$;@) {
1965 return match_glob($_[0], $_[1], @_, internal => 1)
1968 sub match_link ($$;@) {
1973 $link=derel($link, $params{location});
1974 my $from=exists $params{location} ? $params{location} : '';
1976 my $links = $IkiWiki::links{$page};
1977 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1978 my $bestlink = IkiWiki::bestlink($from, $link);
1979 foreach my $p (@{$links}) {
1980 if (length $bestlink) {
1981 return IkiWiki::SuccessReason->new("$page links to $link")
1982 if $bestlink eq IkiWiki::bestlink($page, $p);
1985 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1986 if match_glob($p, $link, %params);
1989 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1990 if match_glob($p, $link, %params);
1993 return IkiWiki::FailReason->new("$page does not link to $link");
1996 sub match_backlink ($$;@) {
1997 return match_link($_[1], $_[0], @_);
2000 sub match_created_before ($$;@) {
2005 $testpage=derel($testpage, $params{location});
2007 if (exists $IkiWiki::pagectime{$testpage}) {
2008 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2009 return IkiWiki::SuccessReason->new("$page created before $testpage");
2012 return IkiWiki::FailReason->new("$page not created before $testpage");
2016 return IkiWiki::FailReason->new("$testpage has no ctime");
2020 sub match_created_after ($$;@) {
2025 $testpage=derel($testpage, $params{location});
2027 if (exists $IkiWiki::pagectime{$testpage}) {
2028 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2029 return IkiWiki::SuccessReason->new("$page created after $testpage");
2032 return IkiWiki::FailReason->new("$page not created after $testpage");
2036 return IkiWiki::FailReason->new("$testpage has no ctime");
2040 sub match_creation_day ($$;@) {
2041 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2042 return IkiWiki::SuccessReason->new('creation_day matched');
2045 return IkiWiki::FailReason->new('creation_day did not match');
2049 sub match_creation_month ($$;@) {
2050 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2051 return IkiWiki::SuccessReason->new('creation_month matched');
2054 return IkiWiki::FailReason->new('creation_month did not match');
2058 sub match_creation_year ($$;@) {
2059 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2060 return IkiWiki::SuccessReason->new('creation_year matched');
2063 return IkiWiki::FailReason->new('creation_year did not match');
2067 sub match_user ($$;@) {
2072 if (! exists $params{user}) {
2073 return IkiWiki::ErrorReason->new("no user specified");
2076 if (defined $params{user} && lc $params{user} eq lc $user) {
2077 return IkiWiki::SuccessReason->new("user is $user");
2079 elsif (! defined $params{user}) {
2080 return IkiWiki::FailReason->new("not logged in");
2083 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2087 sub match_admin ($$;@) {
2092 if (! exists $params{user}) {
2093 return IkiWiki::ErrorReason->new("no user specified");
2096 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2097 return IkiWiki::SuccessReason->new("user is an admin");
2099 elsif (! defined $params{user}) {
2100 return IkiWiki::FailReason->new("not logged in");
2103 return IkiWiki::FailReason->new("user is not an admin");
2107 sub match_ip ($$;@) {
2112 if (! exists $params{ip}) {
2113 return IkiWiki::ErrorReason->new("no IP specified");
2116 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2117 return IkiWiki::SuccessReason->new("IP is $ip");
2120 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");