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
17 $gettext_obj %loaded_plugins};
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
23 add_underlay pagetitle titlepage linkpage newpagefile
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=''; # 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",
163 description => "wrappers to generate",
170 description => "additional underlays to use",
177 description => "display verbose messages?",
184 description => "log to syslog?",
191 description => "create output files named page/index.html?",
192 safe => 0, # changing requires manual transition
195 prefix_directives => {
198 description => "use '!'-prefixed preprocessor directives?",
199 safe => 0, # changing requires manual transition
205 description => "use page/index.mdwn source files",
212 description => "enable Discussion pages?",
219 description => "only send cookies over SSL connections?",
227 description => "extension to use for new pages",
228 safe => 0, # not sanitized
234 description => "extension to use for html files",
235 safe => 0, # not sanitized
241 description => "strftime format string to display date",
249 example => "en_US.UTF-8",
250 description => "UTF-8 locale to use",
259 description => "put user pages below specified page",
266 description => "how many backlinks to show before hiding excess (0 to show all)",
273 description => "attempt to hardlink source files? (optimisation for large files)",
275 safe => 0, # paranoia
281 description => "force ikiwiki to use a particular umask",
283 safe => 0, # paranoia
288 example => "ikiwiki",
289 description => "group for wrappers to run in",
291 safe => 0, # paranoia
297 example => "$ENV{HOME}/.ikiwiki/",
298 description => "extra library and plugin directory",
300 safe => 0, # directory
306 description => "environment variables",
307 safe => 0, # paranoia
314 description => "regexp of source files to ignore",
319 wiki_file_prune_regexps => {
321 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
322 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
323 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
326 description => "regexps of source files to ignore",
332 description => "specifies the characters that are allowed in source filenames",
333 default => "-[:alnum:]+/.:_",
337 wiki_file_regexp => {
339 description => "regexp of legal source files",
343 web_commit_regexp => {
345 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
346 description => "regexp to parse web commits from logs",
353 description => "run as a cgi",
357 cgi_disable_uploads => {
360 description => "whether CGI should accept file uploads",
367 description => "run as a post-commit hook",
374 description => "running in rebuild mode",
381 description => "running in setup mode",
388 description => "running in refresh mode",
395 description => "running in receive test mode",
402 description => "running in getctime mode",
409 description => "running in w3mmode",
416 description => "path to the .ikiwiki directory holding ikiwiki state",
423 description => "path to setup file",
427 allow_symlinks_before_srcdir => {
430 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
436 sub defaultconfig () {
439 foreach my $key (keys %s) {
440 push @ret, $key, $s{$key}->{default};
447 # locale stuff; avoid LC_ALL since it overrides everything
448 if (defined $ENV{LC_ALL}) {
449 $ENV{LANG} = $ENV{LC_ALL};
452 if (defined $config{locale}) {
453 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
454 $ENV{LANG}=$config{locale};
459 if (! defined $config{wiki_file_regexp}) {
460 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
463 if (ref $config{ENV} eq 'HASH') {
464 foreach my $val (keys %{$config{ENV}}) {
465 $ENV{$val}=$config{ENV}{$val};
469 if ($config{w3mmode}) {
470 eval q{use Cwd q{abs_path}};
472 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
473 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
474 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
475 unless $config{cgiurl} =~ m!file:///!;
476 $config{url}="file://".$config{destdir};
479 if ($config{cgi} && ! length $config{url}) {
480 error(gettext("Must specify url to wiki with --url when using --cgi"));
483 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
484 unless exists $config{wikistatedir} && defined $config{wikistatedir};
486 if (defined $config{umask}) {
487 umask(possibly_foolish_untaint($config{umask}));
490 run_hooks(checkconfig => sub { shift->() });
498 foreach my $dir (@INC, $config{libdir}) {
499 next unless defined $dir && length $dir;
500 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
501 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
505 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
506 next unless defined $dir && length $dir;
507 foreach my $file (glob("$dir/plugins/*")) {
508 $ret{basename($file)}=1 if -x $file;
516 if (defined $config{libdir} && length $config{libdir}) {
517 unshift @INC, possibly_foolish_untaint($config{libdir});
520 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
525 if (exists $IkiWiki::hooks{rcs}) {
526 error(gettext("cannot use multiple rcs plugins"));
528 loadplugin($config{rcs});
530 if (! exists $IkiWiki::hooks{rcs}) {
534 run_hooks(getopt => sub { shift->() });
535 if (grep /^-/, @ARGV) {
536 print STDERR "Unknown option: $_\n"
537 foreach grep /^-/, @ARGV;
547 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
549 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
550 "$installdir/lib/ikiwiki") {
551 if (defined $dir && -x "$dir/plugins/$plugin") {
552 eval { require IkiWiki::Plugin::external };
555 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
557 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
558 $loaded_plugins{$plugin}=1;
563 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
566 error("Failed to load plugin $mod: $@");
568 $loaded_plugins{$plugin}=1;
575 log_message('err' => $message) if $config{syslog};
576 if (defined $cleaner) {
583 return unless $config{verbose};
584 return log_message(debug => @_);
588 sub log_message ($$) {
591 if ($config{syslog}) {
594 Sys::Syslog::setlogsock('unix');
595 Sys::Syslog::openlog('ikiwiki', '', 'user');
599 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
602 elsif (! $config{cgi}) {
606 return print STDERR "@_\n";
610 sub possibly_foolish_untaint ($) {
612 my ($untainted)=$tainted=~/(.*)/s;
632 return exists $pagesources{$page} &&
633 $pagesources{$page} =~ /\._([^.]+)$/;
639 if ($file =~ /\.([^.]+)$/) {
640 return $1 if exists $hooks{htmlize}{$1};
642 elsif ($hooks{htmlize}{basename($file)}{noextension}) {
643 return basename($file);
651 my $type=pagetype($file);
653 $page=~s/\Q.$type\E*$//
654 if defined $type && !$hooks{htmlize}{$type}{keepextension}
655 && !$hooks{htmlize}{$type}{noextension};
656 if ($config{indexpages} && $page=~/(.*)\/index$/) {
662 sub newpagefile ($$) {
666 if (! $config{indexpages} || $page eq 'index') {
667 return $page.".".$type;
670 return $page."/index.".$type;
674 sub targetpage ($$;$) {
679 if (defined $filename) {
680 return $page."/".$filename.".".$ext;
682 elsif (! $config{usedirs} || $page eq 'index') {
683 return $page.".".$ext;
686 return $page."/index.".$ext;
693 return targetpage($page, $config{htmlext});
700 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
701 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
702 return "$dir/$file", stat(_) if -e "$dir/$file";
704 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
709 return (srcfile_stat(@_))[0];
712 sub add_underlay ($) {
716 $dir="$config{underlaydir}/../$dir";
719 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
720 unshift @{$config{underlaydirs}}, $dir;
726 sub readfile ($;$$) {
732 error("cannot read a symlink ($file)");
736 open (my $in, "<", $file) || error("failed to read $file: $!");
737 binmode($in) if ($binary);
738 return \*$in if $wantfd;
740 # check for invalid utf-8, and toss it back to avoid crashes
741 if (! utf8::valid($ret)) {
742 $ret=encode_utf8($ret);
744 close $in || error("failed to read $file: $!");
748 sub prep_writefile ($$) {
753 while (length $test) {
754 if (-l "$destdir/$test") {
755 error("cannot write to a symlink ($test)");
757 $test=dirname($test);
760 my $dir=dirname("$destdir/$file");
763 foreach my $s (split(m!/+!, $dir)) {
766 mkdir($d) || error("failed to create directory $d: $!");
774 sub writefile ($$$;$$) {
775 my $file=shift; # can include subdirs
776 my $destdir=shift; # directory to put file in
781 prep_writefile($file, $destdir);
783 my $newfile="$destdir/$file.ikiwiki-new";
785 error("cannot write to a symlink ($newfile)");
788 my $cleanup = sub { unlink($newfile) };
789 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
790 binmode($out) if ($binary);
792 $writer->(\*$out, $cleanup);
795 print $out $content or error("failed writing to $newfile: $!", $cleanup);
797 close $out || error("failed saving $newfile: $!", $cleanup);
798 rename($newfile, "$destdir/$file") ||
799 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
805 sub will_render ($$;$) {
810 # Important security check.
811 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
812 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
813 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
816 if (! $clear || $cleared{$page}) {
817 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
820 foreach my $old (@{$renderedfiles{$page}}) {
821 delete $destsources{$old};
823 $renderedfiles{$page}=[$dest];
826 $destsources{$dest}=$page;
836 if ($link=~s/^\/+//) {
844 $l.="/" if length $l;
847 if (exists $links{$l}) {
850 elsif (exists $pagecase{lc $l}) {
851 return $pagecase{lc $l};
853 } while $cwd=~s{/?[^/]+$}{};
855 if (length $config{userdir}) {
856 my $l = "$config{userdir}/".lc($link);
857 if (exists $links{$l}) {
860 elsif (exists $pagecase{lc $l}) {
861 return $pagecase{lc $l};
865 #print STDERR "warning: page $page, broken link: $link\n";
869 sub isinlinableimage ($) {
872 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
875 sub pagetitle ($;$) {
880 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
883 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
891 # support use w/o %config set
892 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
893 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
899 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
900 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
907 return $config{cgiurl}."?".
908 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
914 return "$config{url}/" if ! defined $page;
916 $page=htmlpage($page);
918 $page=~s/[^\/]+\//..\//g;
923 # Work around very innefficient behavior in File::Spec if abs2rel
924 # is passed two relative paths. It's much faster if paths are
925 # absolute! (Debian bug #376658; fixed in debian unstable now)
930 my $ret=File::Spec->abs2rel($path, $base);
931 $ret=~s/^// if defined $ret;
935 sub displaytime ($;$) {
936 # Plugins can override this function to mark up the time to
938 return '<span class="date">'.formattime(@_).'</span>';
941 sub formattime ($;$) {
942 # Plugins can override this function to format the time.
945 if (! defined $format) {
946 $format=$config{timeformat};
949 # strftime doesn't know about encodings, so make sure
950 # its output is properly treated as utf8
951 return decode_utf8(POSIX::strftime($format, localtime($time)));
954 sub beautify_urlpath ($) {
957 # Ensure url is not an empty link, and if necessary,
958 # add ./ to avoid colon confusion.
959 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
963 if ($config{usedirs}) {
964 $url =~ s!/index.$config{htmlext}$!/!;
976 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
979 if (! $destsources{$to}) {
984 return $config{url}.beautify_urlpath("/".$to);
987 my $link = abs2rel($to, dirname(htmlpage($from)));
989 return beautify_urlpath($link);
992 sub htmllink ($$$;@) {
993 my $lpage=shift; # the page doing the linking
994 my $page=shift; # the page that will contain the link (different for inline)
1001 if (! $opts{forcesubpage}) {
1002 $bestlink=bestlink($lpage, $link);
1005 $bestlink="$lpage/".lc($link);
1009 if (defined $opts{linktext}) {
1010 $linktext=$opts{linktext};
1013 $linktext=pagetitle(basename($link));
1016 return "<span class=\"selflink\">$linktext</span>"
1017 if length $bestlink && $page eq $bestlink &&
1018 ! defined $opts{anchor};
1020 if (! $destsources{$bestlink}) {
1021 $bestlink=htmlpage($bestlink);
1023 if (! $destsources{$bestlink}) {
1024 return $linktext unless length $config{cgiurl};
1025 return "<span class=\"createlink\"><a href=\"".
1031 "\" rel=\"nofollow\">?</a>$linktext</span>"
1035 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1036 $bestlink=beautify_urlpath($bestlink);
1038 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1039 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1042 if (defined $opts{anchor}) {
1043 $bestlink.="#".$opts{anchor};
1047 if (defined $opts{rel}) {
1048 push @attrs, ' rel="'.$opts{rel}.'"';
1050 if (defined $opts{class}) {
1051 push @attrs, ' class="'.$opts{class}.'"';
1054 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1060 my $oiduser=eval { openiduser($user) };
1061 if (defined $oiduser) {
1062 return "<a href=\"$user\">$oiduser</a>";
1065 eval q{use CGI 'escapeHTML'};
1068 return htmllink("", "", escapeHTML(
1069 length $config{userdir} ? $config{userdir}."/".$user : $user
1070 ), noimageinline => 1);
1074 sub htmlize ($$$$) {
1080 my $oneline = $content !~ /\n/;
1082 if (exists $hooks{htmlize}{$type}) {
1083 $content=$hooks{htmlize}{$type}{call}->(
1085 content => $content,
1089 error("htmlization of $type not supported");
1092 run_hooks(sanitize => sub {
1095 destpage => $destpage,
1096 content => $content,
1101 # hack to get rid of enclosing junk added by markdown
1102 # and other htmlizers
1103 $content=~s/^<p>//i;
1104 $content=~s/<\/p>$//i;
1116 run_hooks(linkify => sub {
1119 destpage => $destpage,
1120 content => $content,
1128 our $preprocess_preview=0;
1129 sub preprocess ($$$;$$) {
1130 my $page=shift; # the page the data comes from
1131 my $destpage=shift; # the page the data will appear in (different for inline)
1136 # Using local because it needs to be set within any nested calls
1138 local $preprocess_preview=$preview if defined $preview;
1145 $params="" if ! defined $params;
1147 if (length $escape) {
1148 return "[[$prefix$command $params]]";
1150 elsif (exists $hooks{preprocess}{$command}) {
1151 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1152 # Note: preserve order of params, some plugins may
1153 # consider it significant.
1155 while ($params =~ m{
1156 (?:([-\w]+)=)? # 1: named parameter key?
1158 """(.*?)""" # 2: triple-quoted value
1160 "([^"]+)" # 3: single-quoted value
1162 (\S+) # 4: unquoted value
1164 (?:\s+|$) # delimiter to next param
1174 elsif (defined $3) {
1177 elsif (defined $4) {
1182 push @params, $key, $val;
1185 push @params, $val, '';
1188 if ($preprocessing{$page}++ > 3) {
1189 # Avoid loops of preprocessed pages preprocessing
1190 # other pages that preprocess them, etc.
1191 return "[[!$command <span class=\"error\">".
1192 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1193 $page, $preprocessing{$page}).
1199 $hooks{preprocess}{$command}{call}->(
1202 destpage => $destpage,
1203 preview => $preprocess_preview,
1208 $ret="[[!$command <span class=\"error\">".
1209 gettext("Error").": $@"."</span>]]";
1213 # use void context during scan pass
1215 $hooks{preprocess}{$command}{call}->(
1218 destpage => $destpage,
1219 preview => $preprocess_preview,
1224 $preprocessing{$page}--;
1228 return "[[$prefix$command $params]]";
1233 if ($config{prefix_directives}) {
1236 \[\[(!) # directive open; 2: prefix
1237 ([-\w]+) # 3: command
1238 ( # 4: the parameters..
1239 \s+ # Must have space if parameters present
1241 (?:[-\w]+=)? # named parameter key?
1243 """.*?""" # triple-quoted value
1245 "[^"]+" # single-quoted value
1247 [^\s\]]+ # unquoted value
1249 \s* # whitespace or end
1252 *)? # 0 or more parameters
1253 \]\] # directive closed
1259 \[\[(!?) # directive open; 2: optional prefix
1260 ([-\w]+) # 3: command
1262 ( # 4: the parameters..
1264 (?:[-\w]+=)? # named parameter key?
1266 """.*?""" # triple-quoted value
1268 "[^"]+" # single-quoted value
1270 [^\s\]]+ # unquoted value
1272 \s* # whitespace or end
1275 *) # 0 or more parameters
1276 \]\] # directive closed
1280 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1289 run_hooks(filter => sub {
1290 $content=shift->(page => $page, destpage => $destpage,
1291 content => $content);
1298 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1301 sub check_canedit ($$$;$) {
1308 run_hooks(canedit => sub {
1309 return if defined $canedit;
1310 my $ret=shift->($page, $q, $session);
1315 elsif (ref $ret eq 'CODE') {
1316 $ret->() unless $nonfatal;
1319 elsif (defined $ret) {
1320 error($ret) unless $nonfatal;
1325 return defined $canedit ? $canedit : 1;
1328 sub check_content (@) {
1331 return 1 if ! exists $hooks{checkcontent}; # optimisation
1333 if (exists $pagesources{$params{page}}) {
1335 my %old=map { $_ => 1 }
1336 split("\n", readfile(srcfile($pagesources{$params{page}})));
1337 foreach my $line (split("\n", $params{content})) {
1338 push @diff, $line if ! exists $old{$_};
1340 $params{content}=join("\n", @diff);
1344 run_hooks(checkcontent => sub {
1345 return if defined $ok;
1346 my $ret=shift->(%params);
1351 elsif (ref $ret eq 'CODE') {
1352 $ret->() unless $params{nonfatal};
1355 elsif (defined $ret) {
1356 error($ret) unless $params{nonfatal};
1362 return defined $ok ? $ok : 1;
1368 # Take an exclusive lock on the wiki to prevent multiple concurrent
1369 # run issues. The lock will be dropped on program exit.
1370 if (! -d $config{wikistatedir}) {
1371 mkdir($config{wikistatedir});
1373 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1374 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1375 if (! flock($wikilock, 2)) { # LOCK_EX
1376 error("failed to get lock");
1382 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1383 return close($wikilock) if $wikilock;
1389 sub commit_hook_enabled () {
1390 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1391 error("cannot write to $config{wikistatedir}/commitlock: $!");
1392 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1393 close($commitlock) || error("failed closing commitlock: $!");
1396 close($commitlock) || error("failed closing commitlock: $!");
1400 sub disable_commit_hook () {
1401 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1402 error("cannot write to $config{wikistatedir}/commitlock: $!");
1403 if (! flock($commitlock, 2)) { # LOCK_EX
1404 error("failed to get commit lock");
1409 sub enable_commit_hook () {
1410 return close($commitlock) if $commitlock;
1415 %oldrenderedfiles=%pagectime=();
1416 if (! $config{rebuild}) {
1417 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1418 %destsources=%renderedfiles=%pagecase=%pagestate=();
1421 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1422 if (-e "$config{wikistatedir}/index") {
1423 system("ikiwiki-transition", "indexdb", $config{srcdir});
1424 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1431 my $index=Storable::fd_retrieve($in);
1432 if (! defined $index) {
1437 if (exists $index->{version} && ! ref $index->{version}) {
1438 $pages=$index->{page};
1439 %wikistate=%{$index->{state}};
1446 foreach my $src (keys %$pages) {
1447 my $d=$pages->{$src};
1448 my $page=pagename($src);
1449 $pagectime{$page}=$d->{ctime};
1450 if (! $config{rebuild}) {
1451 $pagesources{$page}=$src;
1452 $pagemtime{$page}=$d->{mtime};
1453 $renderedfiles{$page}=$d->{dest};
1454 if (exists $d->{links} && ref $d->{links}) {
1455 $links{$page}=$d->{links};
1456 $oldlinks{$page}=[@{$d->{links}}];
1458 if (exists $d->{depends}) {
1459 $depends{$page}=$d->{depends};
1461 if (exists $d->{state}) {
1462 $pagestate{$page}=$d->{state};
1465 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1467 foreach my $page (keys %pagesources) {
1468 $pagecase{lc $page}=$page;
1470 foreach my $page (keys %renderedfiles) {
1471 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1477 run_hooks(savestate => sub { shift->() });
1480 foreach my $type (keys %hooks) {
1481 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1483 my @hookids=keys %hookids;
1485 if (! -d $config{wikistatedir}) {
1486 mkdir($config{wikistatedir});
1488 my $newfile="$config{wikistatedir}/indexdb.new";
1489 my $cleanup = sub { unlink($newfile) };
1490 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1493 foreach my $page (keys %pagemtime) {
1494 next unless $pagemtime{$page};
1495 my $src=$pagesources{$page};
1497 $index{page}{$src}={
1498 ctime => $pagectime{$page},
1499 mtime => $pagemtime{$page},
1500 dest => $renderedfiles{$page},
1501 links => $links{$page},
1504 if (exists $depends{$page}) {
1505 $index{page}{$src}{depends} = $depends{$page};
1508 if (exists $pagestate{$page}) {
1509 foreach my $id (@hookids) {
1510 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1511 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1518 foreach my $id (@hookids) {
1519 foreach my $key (keys %{$wikistate{$id}}) {
1520 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1524 $index{version}="3";
1525 my $ret=Storable::nstore_fd(\%index, $out);
1526 return if ! defined $ret || ! $ret;
1527 close $out || error("failed saving to $newfile: $!", $cleanup);
1528 rename($newfile, "$config{wikistatedir}/indexdb") ||
1529 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1534 sub template_file ($) {
1537 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1538 return "$dir/$template" if -e "$dir/$template";
1543 sub template_params (@) {
1544 my $filename=template_file(shift);
1546 if (! defined $filename) {
1547 return if wantarray;
1553 my $text_ref = shift;
1554 ${$text_ref} = decode_utf8(${$text_ref});
1556 filename => $filename,
1557 loop_context_vars => 1,
1558 die_on_bad_params => 0,
1561 return wantarray ? @ret : {@ret};
1564 sub template ($;@) {
1565 require HTML::Template;
1566 return HTML::Template->new(template_params(@_));
1569 sub misctemplate ($$;@) {
1573 my $template=template("misc.tmpl");
1576 indexlink => indexlink(),
1577 wikiname => $config{wikiname},
1578 pagebody => $pagebody,
1579 baseurl => baseurl(),
1582 run_hooks(pagetemplate => sub {
1583 shift->(page => "", destpage => "", template => $template);
1585 return $template->output;
1591 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1592 error 'hook requires type, call, and id parameters';
1595 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1597 $hooks{$param{type}}{$param{id}}=\%param;
1601 sub run_hooks ($$) {
1602 # Calls the given sub for each hook of the given type,
1603 # passing it the hook function to call.
1607 if (exists $hooks{$type}) {
1608 my (@first, @middle, @last);
1609 foreach my $id (keys %{$hooks{$type}}) {
1610 if ($hooks{$type}{$id}{first}) {
1613 elsif ($hooks{$type}{$id}{last}) {
1620 foreach my $id (@first, @middle, @last) {
1621 $sub->($hooks{$type}{$id}{call});
1629 $hooks{rcs}{rcs_update}{call}->(@_);
1632 sub rcs_prepedit ($) {
1633 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1636 sub rcs_commit ($$$;$$) {
1637 $hooks{rcs}{rcs_commit}{call}->(@_);
1640 sub rcs_commit_staged ($$$) {
1641 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1645 $hooks{rcs}{rcs_add}{call}->(@_);
1648 sub rcs_remove ($) {
1649 $hooks{rcs}{rcs_remove}{call}->(@_);
1652 sub rcs_rename ($$) {
1653 $hooks{rcs}{rcs_rename}{call}->(@_);
1656 sub rcs_recentchanges ($) {
1657 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1661 $hooks{rcs}{rcs_diff}{call}->(@_);
1664 sub rcs_getctime ($) {
1665 $hooks{rcs}{rcs_getctime}{call}->(@_);
1668 sub rcs_receive () {
1669 $hooks{rcs}{rcs_receive}{call}->();
1678 sub add_depends ($$) {
1682 return unless pagespec_valid($pagespec);
1684 if (! exists $depends{$page}) {
1685 $depends{$page}=$pagespec;
1688 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1694 sub file_pruned ($$) {
1696 my $file=File::Spec->canonpath(shift);
1697 my $base=File::Spec->canonpath(shift);
1698 $file =~ s#^\Q$base\E/+##;
1700 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1701 return $file =~ m/$regexp/ && $file ne $base;
1705 # Only use gettext in the rare cases it's needed.
1706 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1707 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1708 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1709 if (! $gettext_obj) {
1710 $gettext_obj=eval q{
1711 use Locale::gettext q{textdomain};
1712 Locale::gettext->domain('ikiwiki')
1720 return $gettext_obj->get(shift);
1730 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1734 # Injects a new function into the symbol table to replace an
1735 # exported function.
1738 # This is deep ugly perl foo, beware.
1741 if (! defined $params{parent}) {
1742 $params{parent}='::';
1743 $params{old}=\&{$params{name}};
1744 $params{name}=~s/.*:://;
1746 my $parent=$params{parent};
1747 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1748 $ns = $params{parent} . $ns;
1749 inject(%params, parent => $ns) unless $ns eq '::main::';
1750 *{$ns . $params{name}} = $params{call}
1751 if exists ${$ns}{$params{name}} &&
1752 \&{${$ns}{$params{name}}} == $params{old};
1758 sub pagespec_merge ($$) {
1762 return $a if $a eq $b;
1763 return "($a) or ($b)";
1766 sub pagespec_translate ($) {
1769 # Convert spec to perl code.
1772 \s* # ignore whitespace
1773 ( # 1: match a single word
1780 \w+\([^\)]*\) # command(params)
1782 [^\s()]+ # any other text
1784 \s* # ignore whitespace
1787 if (lc $word eq 'and') {
1790 elsif (lc $word eq 'or') {
1793 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1796 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1797 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1798 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1801 $code.="IkiWiki::FailReason->new(".safequote(qq{unknown function in pagespec "$word"}).")";
1805 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1809 if (! length $code) {
1810 $code="IkiWiki::FailReason->new('empty pagespec')";
1814 return eval 'sub { my $page=shift; '.$code.' }';
1817 sub pagespec_match ($$;@) {
1822 # Backwards compatability with old calling convention.
1824 unshift @params, 'location';
1827 my $sub=pagespec_translate($spec);
1828 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"")
1829 if $@ || ! defined $sub;
1830 return $sub->($page, @params);
1833 sub pagespec_valid ($) {
1836 my $sub=pagespec_translate($spec);
1841 my $re=quotemeta(shift);
1847 package IkiWiki::FailReason;
1850 '""' => sub { ${$_[0]} },
1852 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1859 return bless \$value, $class;
1862 package IkiWiki::SuccessReason;
1865 '""' => sub { ${$_[0]} },
1867 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1874 return bless \$value, $class;
1877 package IkiWiki::PageSpec;
1883 if ($path =~ m!^\./!) {
1884 $from=~s#/?[^/]+$## if defined $from;
1886 $path="$from/$path" if length $from;
1892 sub match_glob ($$;@) {
1897 $glob=derel($glob, $params{location});
1899 my $regexp=IkiWiki::glob2re($glob);
1900 if ($page=~/^$regexp$/i) {
1901 if (! IkiWiki::isinternal($page) || $params{internal}) {
1902 return IkiWiki::SuccessReason->new("$glob matches $page");
1905 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1909 return IkiWiki::FailReason->new("$glob does not match $page");
1913 sub match_internal ($$;@) {
1914 return match_glob($_[0], $_[1], @_, internal => 1)
1917 sub match_link ($$;@) {
1922 $link=derel($link, $params{location});
1923 my $from=exists $params{location} ? $params{location} : '';
1925 my $links = $IkiWiki::links{$page};
1926 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1927 my $bestlink = IkiWiki::bestlink($from, $link);
1928 foreach my $p (@{$links}) {
1929 if (length $bestlink) {
1930 return IkiWiki::SuccessReason->new("$page links to $link")
1931 if $bestlink eq IkiWiki::bestlink($page, $p);
1934 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1935 if match_glob($p, $link, %params);
1938 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1939 if match_glob($p, $link, %params);
1942 return IkiWiki::FailReason->new("$page does not link to $link");
1945 sub match_backlink ($$;@) {
1946 return match_link($_[1], $_[0], @_);
1949 sub match_created_before ($$;@) {
1954 $testpage=derel($testpage, $params{location});
1956 if (exists $IkiWiki::pagectime{$testpage}) {
1957 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1958 return IkiWiki::SuccessReason->new("$page created before $testpage");
1961 return IkiWiki::FailReason->new("$page not created before $testpage");
1965 return IkiWiki::FailReason->new("$testpage has no ctime");
1969 sub match_created_after ($$;@) {
1974 $testpage=derel($testpage, $params{location});
1976 if (exists $IkiWiki::pagectime{$testpage}) {
1977 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1978 return IkiWiki::SuccessReason->new("$page created after $testpage");
1981 return IkiWiki::FailReason->new("$page not created after $testpage");
1985 return IkiWiki::FailReason->new("$testpage has no ctime");
1989 sub match_creation_day ($$;@) {
1990 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1991 return IkiWiki::SuccessReason->new('creation_day matched');
1994 return IkiWiki::FailReason->new('creation_day did not match');
1998 sub match_creation_month ($$;@) {
1999 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2000 return IkiWiki::SuccessReason->new('creation_month matched');
2003 return IkiWiki::FailReason->new('creation_month did not match');
2007 sub match_creation_year ($$;@) {
2008 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2009 return IkiWiki::SuccessReason->new('creation_year matched');
2012 return IkiWiki::FailReason->new('creation_year did not match');
2016 sub match_user ($$;@) {
2021 if (! exists $params{user}) {
2022 return IkiWiki::FailReason->new("no user specified");
2025 if (defined $params{user} && lc $params{user} eq lc $user) {
2026 return IkiWiki::SuccessReason->new("user is $user");
2028 elsif (! defined $params{user}) {
2029 return IkiWiki::FailReason->new("not logged in");
2032 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2036 sub match_admin ($$;@) {
2041 if (! exists $params{user}) {
2042 return IkiWiki::FailReason->new("no user specified");
2045 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2046 return IkiWiki::SuccessReason->new("user is an admin");
2048 elsif (! defined $params{user}) {
2049 return IkiWiki::FailReason->new("not logged in");
2052 return IkiWiki::FailReason->new("user is not an admin");
2056 sub match_ip ($$;@) {
2061 if (! exists $params{ip}) {
2062 return IkiWiki::FailReason->new("no IP specified");
2065 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2066 return IkiWiki::SuccessReason->new("IP is $ip");
2069 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");