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 = 2.00; # plugin interface version, next is ikiwiki version
28 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
29 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
34 memoize("pagespec_translate");
35 memoize("file_pruned");
37 sub getsetup () { #{{{
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 => "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 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 when building?",
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
282 description => "force ikiwiki to use a particular umask",
284 safe => 0, # paranoia
290 example => "$ENV{HOME}/.ikiwiki/",
291 description => "extra library and plugin directory",
293 safe => 0, # directory
299 description => "environment variables",
300 safe => 0, # paranoia
307 description => "regexp of source files to ignore",
312 wiki_file_prune_regexps => {
314 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
315 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
316 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
319 description => "regexps of source files to ignore",
325 description => "specifies the characters that are allowed in source filenames",
326 default => "-[:alnum:]+/.:_",
330 wiki_file_regexp => {
332 description => "regexp of legal source files",
336 web_commit_regexp => {
338 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
339 description => "regexp to parse web commits from logs",
346 description => "run as a cgi",
350 cgi_disable_uploads => {
353 description => "whether CGI should accept file uploads",
360 description => "run as a post-commit hook",
367 description => "running in rebuild mode",
374 description => "running in setup mode",
381 description => "running in refresh mode",
388 description => "running in receive test mode",
395 description => "running in getctime mode",
402 description => "running in w3mmode",
409 description => "path to setup file",
413 allow_symlinks_before_srcdir => {
416 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
422 sub defaultconfig () { #{{{
425 foreach my $key (keys %s) {
426 push @ret, $key, $s{$key}->{default};
432 sub checkconfig () { #{{{
433 # locale stuff; avoid LC_ALL since it overrides everything
434 if (defined $ENV{LC_ALL}) {
435 $ENV{LANG} = $ENV{LC_ALL};
438 if (defined $config{locale}) {
439 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
440 $ENV{LANG}=$config{locale};
445 if (! defined $config{wiki_file_regexp}) {
446 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
449 if (ref $config{ENV} eq 'HASH') {
450 foreach my $val (keys %{$config{ENV}}) {
451 $ENV{$val}=$config{ENV}{$val};
455 if ($config{w3mmode}) {
456 eval q{use Cwd q{abs_path}};
458 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
459 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
460 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
461 unless $config{cgiurl} =~ m!file:///!;
462 $config{url}="file://".$config{destdir};
465 if ($config{cgi} && ! length $config{url}) {
466 error(gettext("Must specify url to wiki with --url when using --cgi"));
469 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
470 unless exists $config{wikistatedir};
472 if (defined $config{umask}) {
473 umask(possibly_foolish_untaint($config{umask}));
476 run_hooks(checkconfig => sub { shift->() });
481 sub listplugins () { #{{{
484 foreach my $dir (@INC, $config{libdir}) {
485 next unless defined $dir && length $dir;
486 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
487 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
491 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
492 next unless defined $dir && length $dir;
493 foreach my $file (glob("$dir/plugins/*")) {
494 $ret{basename($file)}=1 if -x $file;
501 sub loadplugins () { #{{{
502 if (defined $config{libdir} && length $config{libdir}) {
503 unshift @INC, possibly_foolish_untaint($config{libdir});
506 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
511 if (exists $IkiWiki::hooks{rcs}) {
512 error(gettext("cannot use multiple rcs plugins"));
514 loadplugin($config{rcs});
516 if (! exists $IkiWiki::hooks{rcs}) {
520 run_hooks(getopt => sub { shift->() });
521 if (grep /^-/, @ARGV) {
522 print STDERR "Unknown option: $_\n"
523 foreach grep /^-/, @ARGV;
530 sub loadplugin ($) { #{{{
533 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
535 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
536 "$installdir/lib/ikiwiki") {
537 if (defined $dir && -x "$dir/plugins/$plugin") {
538 eval { require IkiWiki::Plugin::external };
541 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
543 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
544 $loaded_plugins{$plugin}=1;
549 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
552 error("Failed to load plugin $mod: $@");
554 $loaded_plugins{$plugin}=1;
558 sub error ($;$) { #{{{
561 log_message('err' => $message) if $config{syslog};
562 if (defined $cleaner) {
569 return unless $config{verbose};
570 return log_message(debug => @_);
574 sub log_message ($$) { #{{{
577 if ($config{syslog}) {
580 Sys::Syslog::setlogsock('unix');
581 Sys::Syslog::openlog('ikiwiki', '', 'user');
585 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
588 elsif (! $config{cgi}) {
592 return print STDERR "@_\n";
596 sub possibly_foolish_untaint ($) { #{{{
598 my ($untainted)=$tainted=~/(.*)/s;
602 sub basename ($) { #{{{
609 sub dirname ($) { #{{{
616 sub pagetype ($) { #{{{
619 if ($page =~ /\.([^.]+)$/) {
620 return $1 if exists $hooks{htmlize}{$1};
625 sub isinternal ($) { #{{{
627 return exists $pagesources{$page} &&
628 $pagesources{$page} =~ /\._([^.]+)$/;
631 sub pagename ($) { #{{{
634 my $type=pagetype($file);
636 $page=~s/\Q.$type\E*$// if defined $type && !$hooks{htmlize}{$type}{keepextension};
637 if ($config{indexpages} && $page=~/(.*)\/index$/) {
643 sub newpagefile ($$) { #{{{
647 if (! $config{indexpages} || $page eq 'index') {
648 return $page.".".$type;
651 return $page."/index.".$type;
655 sub targetpage ($$) { #{{{
660 run_hooks(targetpage => sub {
667 if (defined $targetpage && (length($targetpage) > 0)) {
670 elsif (! $config{usedirs} || $page eq 'index') {
671 return $page.".".$ext;
674 return $page."/index.".$ext;
678 sub htmlpage ($) { #{{{
681 return targetpage($page, $config{htmlext});
684 sub srcfile_stat { #{{{
688 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
689 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
690 return "$dir/$file", stat(_) if -e "$dir/$file";
692 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
696 sub srcfile ($;$) { #{{{
697 return (srcfile_stat(@_))[0];
700 sub add_underlay ($) { #{{{
704 $dir="$config{underlaydir}/../$dir";
707 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
708 unshift @{$config{underlaydirs}}, $dir;
714 sub readfile ($;$$) { #{{{
720 error("cannot read a symlink ($file)");
724 open (my $in, "<", $file) || error("failed to read $file: $!");
725 binmode($in) if ($binary);
726 return \*$in if $wantfd;
728 close $in || error("failed to read $file: $!");
732 sub prep_writefile ($$) { #{{{
737 while (length $test) {
738 if (-l "$destdir/$test") {
739 error("cannot write to a symlink ($test)");
741 $test=dirname($test);
744 my $dir=dirname("$destdir/$file");
747 foreach my $s (split(m!/+!, $dir)) {
750 mkdir($d) || error("failed to create directory $d: $!");
758 sub writefile ($$$;$$) { #{{{
759 my $file=shift; # can include subdirs
760 my $destdir=shift; # directory to put file in
765 prep_writefile($file, $destdir);
767 my $newfile="$destdir/$file.ikiwiki-new";
769 error("cannot write to a symlink ($newfile)");
772 my $cleanup = sub { unlink($newfile) };
773 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
774 binmode($out) if ($binary);
776 $writer->(\*$out, $cleanup);
779 print $out $content or error("failed writing to $newfile: $!", $cleanup);
781 close $out || error("failed saving $newfile: $!", $cleanup);
782 rename($newfile, "$destdir/$file") ||
783 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
789 sub will_render ($$;$) { #{{{
794 # Important security check.
795 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
796 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
797 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
800 if (! $clear || $cleared{$page}) {
801 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
804 foreach my $old (@{$renderedfiles{$page}}) {
805 delete $destsources{$old};
807 $renderedfiles{$page}=[$dest];
810 $destsources{$dest}=$page;
815 sub bestlink ($$) { #{{{
821 if ($link=~s/^\/+//) {
829 $l.="/" if length $l;
832 if (exists $links{$l}) {
835 elsif (exists $pagecase{lc $l}) {
836 $res=$pagecase{lc $l};
838 } while ($cwd=~s{/?[^/]+$}{} && ! defined $res);
840 if (! defined $res && length $config{userdir}) {
841 my $l = "$config{userdir}/".lc($link);
842 if (exists $links{$l}) {
845 elsif (exists $pagecase{lc $l}) {
846 $res=$pagecase{lc $l};
851 run_hooks(tweakbestlink => sub {
859 #print STDERR "warning: page $page, broken link: $link\n";
864 sub isinlinableimage ($) { #{{{
867 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
870 sub pagetitle ($;$) { #{{{
875 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
878 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
884 sub titlepage ($) { #{{{
886 # support use w/o %config set
887 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
888 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
892 sub linkpage ($) { #{{{
894 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
895 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
899 sub cgiurl (@) { #{{{
902 return $config{cgiurl}."?".
903 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
906 sub baseurl (;$) { #{{{
909 return "$config{url}/" if ! defined $page;
911 $page=htmlpage($page);
913 $page=~s/[^\/]+\//..\//g;
917 sub abs2rel ($$) { #{{{
918 # Work around very innefficient behavior in File::Spec if abs2rel
919 # is passed two relative paths. It's much faster if paths are
920 # absolute! (Debian bug #376658; fixed in debian unstable now)
925 my $ret=File::Spec->abs2rel($path, $base);
926 $ret=~s/^// if defined $ret;
930 sub displaytime ($;$) { #{{{
931 # Plugins can override this function to mark up the time to
933 return '<span class="date">'.formattime(@_).'</span>';
936 sub formattime ($;$) { #{{{
937 # Plugins can override this function to format the time.
940 if (! defined $format) {
941 $format=$config{timeformat};
944 # strftime doesn't know about encodings, so make sure
945 # its output is properly treated as utf8
946 return decode_utf8(POSIX::strftime($format, localtime($time)));
949 sub beautify_urlpath ($) { #{{{
952 if ($config{usedirs}) {
953 $url =~ s!/index.$config{htmlext}$!/!;
956 run_hooks(tweakurlpath => sub {
957 $url=shift->(url => $url);
960 # Ensure url is not an empty link, and
961 # if it's relative, make that explicit to avoid colon confusion.
969 sub urlto ($$;$) { #{{{
975 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
978 if (! $destsources{$to}) {
983 return $config{url}.beautify_urlpath("/".$to);
986 my $link = abs2rel($to, dirname(htmlpage($from)));
988 return beautify_urlpath($link);
991 sub htmllink ($$$;@) { #{{{
992 my $lpage=shift; # the page doing the linking
993 my $page=shift; # the page that will contain the link (different for inline)
1000 if (! $opts{forcesubpage}) {
1001 $bestlink=bestlink($lpage, $link);
1004 $bestlink="$lpage/".lc($link);
1008 if (defined $opts{linktext}) {
1009 $linktext=$opts{linktext};
1012 $linktext=pagetitle(basename($link));
1015 return "<span class=\"selflink\">$linktext</span>"
1016 if length $bestlink && $page eq $bestlink &&
1017 ! defined $opts{anchor};
1019 if (! $destsources{$bestlink}) {
1020 $bestlink=htmlpage($bestlink);
1022 if (! $destsources{$bestlink}) {
1023 return $linktext unless length $config{cgiurl};
1024 return "<span class=\"createlink\"><a href=\"".
1030 "\" rel=\"nofollow\">?</a>$linktext</span>"
1034 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1035 $bestlink=beautify_urlpath($bestlink);
1037 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1038 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1041 if (defined $opts{anchor}) {
1042 $bestlink.="#".$opts{anchor};
1046 if (defined $opts{rel}) {
1047 push @attrs, ' rel="'.$opts{rel}.'"';
1049 if (defined $opts{class}) {
1050 push @attrs, ' class="'.$opts{class}.'"';
1053 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1056 sub userlink ($) { #{{{
1059 my $oiduser=eval { openiduser($user) };
1060 if (defined $oiduser) {
1061 return "<a href=\"$user\">$oiduser</a>";
1064 eval q{use CGI 'escapeHTML'};
1067 return htmllink("", "", escapeHTML(
1068 length $config{userdir} ? $config{userdir}."/".$user : $user
1069 ), noimageinline => 1);
1073 sub htmlize ($$$$) { #{{{
1079 my $oneline = $content !~ /\n/;
1081 if (exists $hooks{htmlize}{$type}) {
1082 $content=$hooks{htmlize}{$type}{call}->(
1084 content => $content,
1088 error("htmlization of $type not supported");
1091 run_hooks(sanitize => sub {
1094 destpage => $destpage,
1095 content => $content,
1100 # hack to get rid of enclosing junk added by markdown
1101 # and other htmlizers
1102 $content=~s/^<p>//i;
1103 $content=~s/<\/p>$//i;
1110 sub linkify ($$$) { #{{{
1115 run_hooks(linkify => sub {
1118 destpage => $destpage,
1119 content => $content,
1127 our $preprocess_preview=0;
1128 sub preprocess ($$$;$$) { #{{{
1129 my $page=shift; # the page the data comes from
1130 my $destpage=shift; # the page the data will appear in (different for inline)
1135 # Using local because it needs to be set within any nested calls
1137 local $preprocess_preview=$preview if defined $preview;
1144 $params="" if ! defined $params;
1146 if (length $escape) {
1147 return "[[$prefix$command $params]]";
1149 elsif (exists $hooks{preprocess}{$command}) {
1150 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1151 # Note: preserve order of params, some plugins may
1152 # consider it significant.
1154 while ($params =~ m{
1155 (?:([-\w]+)=)? # 1: named parameter key?
1157 """(.*?)""" # 2: triple-quoted value
1159 "([^"]+)" # 3: single-quoted value
1161 (\S+) # 4: unquoted value
1163 (?:\s+|$) # delimiter to next param
1173 elsif (defined $3) {
1176 elsif (defined $4) {
1181 push @params, $key, $val;
1184 push @params, $val, '';
1187 if ($preprocessing{$page}++ > 3) {
1188 # Avoid loops of preprocessed pages preprocessing
1189 # other pages that preprocess them, etc.
1190 return "[[!$command <span class=\"error\">".
1191 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1192 $page, $preprocessing{$page}).
1198 $hooks{preprocess}{$command}{call}->(
1201 destpage => $destpage,
1202 preview => $preprocess_preview,
1207 $ret="[[!$command <span class=\"error\">".
1208 gettext("Error").": $@"."</span>]]";
1212 # use void context during scan pass
1214 $hooks{preprocess}{$command}{call}->(
1217 destpage => $destpage,
1218 preview => $preprocess_preview,
1223 $preprocessing{$page}--;
1227 return "[[$prefix$command $params]]";
1232 if ($config{prefix_directives}) {
1235 \[\[(!) # directive open; 2: prefix
1236 ([-\w]+) # 3: command
1237 ( # 4: the parameters..
1238 \s+ # Must have space if parameters present
1240 (?:[-\w]+=)? # named parameter key?
1242 """.*?""" # triple-quoted value
1244 "[^"]+" # single-quoted value
1246 [^\s\]]+ # unquoted value
1248 \s* # whitespace or end
1251 *)? # 0 or more parameters
1252 \]\] # directive closed
1258 \[\[(!?) # directive open; 2: optional prefix
1259 ([-\w]+) # 3: command
1261 ( # 4: the parameters..
1263 (?:[-\w]+=)? # named parameter key?
1265 """.*?""" # triple-quoted value
1267 "[^"]+" # single-quoted value
1269 [^\s\]]+ # unquoted value
1271 \s* # whitespace or end
1274 *) # 0 or more parameters
1275 \]\] # directive closed
1279 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1283 sub filter ($$$) { #{{{
1288 run_hooks(filter => sub {
1289 $content=shift->(page => $page, destpage => $destpage,
1290 content => $content);
1296 sub indexlink () { #{{{
1297 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1302 sub lockwiki (;$) { #{{{
1303 my $wait=@_ ? shift : 1;
1304 # Take an exclusive lock on the wiki to prevent multiple concurrent
1305 # run issues. The lock will be dropped on program exit.
1306 if (! -d $config{wikistatedir}) {
1307 mkdir($config{wikistatedir});
1309 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1310 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1311 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1313 debug("wiki seems to be locked, waiting for lock");
1314 my $wait=600; # arbitrary, but don't hang forever to
1315 # prevent process pileup
1317 return if flock($wikilock, 2 | 4);
1320 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1329 sub unlockwiki () { #{{{
1330 return close($wikilock) if $wikilock;
1336 sub commit_hook_enabled () { #{{{
1337 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1338 error("cannot write to $config{wikistatedir}/commitlock: $!");
1339 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1340 close($commitlock) || error("failed closing commitlock: $!");
1343 close($commitlock) || error("failed closing commitlock: $!");
1347 sub disable_commit_hook () { #{{{
1348 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1349 error("cannot write to $config{wikistatedir}/commitlock: $!");
1350 if (! flock($commitlock, 2)) { # LOCK_EX
1351 error("failed to get commit lock");
1356 sub enable_commit_hook () { #{{{
1357 return close($commitlock) if $commitlock;
1361 sub loadindex () { #{{{
1362 %oldrenderedfiles=%pagectime=();
1363 if (! $config{rebuild}) {
1364 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1365 %destsources=%renderedfiles=%pagecase=%pagestate=();
1368 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1369 if (-e "$config{wikistatedir}/index") {
1370 system("ikiwiki-transition", "indexdb", $config{srcdir});
1371 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1378 my $index=Storable::fd_retrieve($in);
1379 if (! defined $index) {
1384 if (exists $index->{version} && ! ref $index->{version}) {
1385 $pages=$index->{page};
1386 %wikistate=%{$index->{state}};
1393 foreach my $src (keys %$pages) {
1394 my $d=$pages->{$src};
1395 my $page=pagename($src);
1396 $pagectime{$page}=$d->{ctime};
1397 if (! $config{rebuild}) {
1398 $pagesources{$page}=$src;
1399 $pagemtime{$page}=$d->{mtime};
1400 $renderedfiles{$page}=$d->{dest};
1401 if (exists $d->{links} && ref $d->{links}) {
1402 $links{$page}=$d->{links};
1403 $oldlinks{$page}=[@{$d->{links}}];
1405 if (exists $d->{depends}) {
1406 $depends{$page}=$d->{depends};
1408 if (exists $d->{state}) {
1409 $pagestate{$page}=$d->{state};
1412 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1414 foreach my $page (keys %pagesources) {
1415 $pagecase{lc $page}=$page;
1417 foreach my $page (keys %renderedfiles) {
1418 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1423 sub saveindex () { #{{{
1424 run_hooks(savestate => sub { shift->() });
1427 foreach my $type (keys %hooks) {
1428 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1430 my @hookids=keys %hookids;
1432 if (! -d $config{wikistatedir}) {
1433 mkdir($config{wikistatedir});
1435 my $newfile="$config{wikistatedir}/indexdb.new";
1436 my $cleanup = sub { unlink($newfile) };
1437 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1440 foreach my $page (keys %pagemtime) {
1441 next unless $pagemtime{$page};
1442 my $src=$pagesources{$page};
1444 $index{page}{$src}={
1445 ctime => $pagectime{$page},
1446 mtime => $pagemtime{$page},
1447 dest => $renderedfiles{$page},
1448 links => $links{$page},
1451 if (exists $depends{$page}) {
1452 $index{page}{$src}{depends} = $depends{$page};
1455 if (exists $pagestate{$page}) {
1456 foreach my $id (@hookids) {
1457 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1458 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1465 foreach my $id (@hookids) {
1466 foreach my $key (keys %{$wikistate{$id}}) {
1467 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1471 $index{version}="3";
1472 my $ret=Storable::nstore_fd(\%index, $out);
1473 return if ! defined $ret || ! $ret;
1474 close $out || error("failed saving to $newfile: $!", $cleanup);
1475 rename($newfile, "$config{wikistatedir}/indexdb") ||
1476 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1481 sub template_file ($) { #{{{
1484 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1485 return "$dir/$template" if -e "$dir/$template";
1490 sub template_params (@) { #{{{
1491 my $filename=template_file(shift);
1493 if (! defined $filename) {
1494 return if wantarray;
1500 my $text_ref = shift;
1501 ${$text_ref} = decode_utf8(${$text_ref});
1503 filename => $filename,
1504 loop_context_vars => 1,
1505 die_on_bad_params => 0,
1508 return wantarray ? @ret : {@ret};
1511 sub template ($;@) { #{{{
1512 require HTML::Template;
1513 return HTML::Template->new(template_params(@_));
1516 sub misctemplate ($$;@) { #{{{
1520 my $template=template("misc.tmpl");
1523 indexlink => indexlink(),
1524 wikiname => $config{wikiname},
1525 pagebody => $pagebody,
1526 baseurl => baseurl(),
1529 run_hooks(pagetemplate => sub {
1530 shift->(page => "", destpage => "", template => $template);
1532 return $template->output;
1535 sub hook (@) { # {{{
1538 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1539 error 'hook requires type, call, and id parameters';
1542 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1544 $hooks{$param{type}}{$param{id}}=\%param;
1548 sub run_hooks ($$) { # {{{
1549 # Calls the given sub for each hook of the given type,
1550 # passing it the hook function to call.
1554 if (exists $hooks{$type}) {
1556 foreach my $id (keys %{$hooks{$type}}) {
1557 if ($hooks{$type}{$id}{last}) {
1558 push @deferred, $id;
1561 $sub->($hooks{$type}{$id}{call});
1563 foreach my $id (@deferred) {
1564 $sub->($hooks{$type}{$id}{call});
1571 sub rcs_update () { #{{{
1572 $hooks{rcs}{rcs_update}{call}->(@_);
1575 sub rcs_prepedit ($) { #{{{
1576 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1579 sub rcs_commit ($$$;$$) { #{{{
1580 $hooks{rcs}{rcs_commit}{call}->(@_);
1583 sub rcs_commit_staged ($$$) { #{{{
1584 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1587 sub rcs_add ($) { #{{{
1588 $hooks{rcs}{rcs_add}{call}->(@_);
1591 sub rcs_remove ($) { #{{{
1592 $hooks{rcs}{rcs_remove}{call}->(@_);
1595 sub rcs_rename ($$) { #{{{
1596 $hooks{rcs}{rcs_rename}{call}->(@_);
1599 sub rcs_recentchanges ($) { #{{{
1600 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1603 sub rcs_diff ($) { #{{{
1604 $hooks{rcs}{rcs_diff}{call}->(@_);
1607 sub rcs_getctime ($) { #{{{
1608 $hooks{rcs}{rcs_getctime}{call}->(@_);
1611 sub rcs_receive () { #{{{
1612 $hooks{rcs}{rcs_receive}{call}->();
1615 sub globlist_to_pagespec ($) { #{{{
1616 my @globlist=split(' ', shift);
1619 foreach my $glob (@globlist) {
1620 if ($glob=~/^!(.*)/) {
1628 my $spec=join(' or ', @spec);
1630 my $skip=join(' and ', @skip);
1632 $spec="$skip and ($spec)";
1641 sub is_globlist ($) { #{{{
1643 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1646 sub safequote ($) { #{{{
1652 sub add_depends ($$) { #{{{
1656 return unless pagespec_valid($pagespec);
1658 if (! exists $depends{$page}) {
1659 $depends{$page}=$pagespec;
1662 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1668 sub file_pruned ($$) { #{{{
1670 my $file=File::Spec->canonpath(shift);
1671 my $base=File::Spec->canonpath(shift);
1672 $file =~ s#^\Q$base\E/+##;
1674 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1675 return $file =~ m/$regexp/ && $file ne $base;
1679 # Only use gettext in the rare cases it's needed.
1680 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1681 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1682 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1683 if (! $gettext_obj) {
1684 $gettext_obj=eval q{
1685 use Locale::gettext q{textdomain};
1686 Locale::gettext->domain('ikiwiki')
1694 return $gettext_obj->get(shift);
1701 sub yesno ($) { #{{{
1704 return (defined $val && lc($val) eq gettext("yes"));
1708 # Injects a new function into the symbol table to replace an
1709 # exported function.
1712 # This is deep ugly perl foo, beware.
1715 if (! defined $params{parent}) {
1716 $params{parent}='::';
1717 $params{old}=\&{$params{name}};
1718 $params{name}=~s/.*:://;
1720 my $parent=$params{parent};
1721 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1722 $ns = $params{parent} . $ns;
1723 inject(%params, parent => $ns) unless $ns eq '::main::';
1724 *{$ns . $params{name}} = $params{call}
1725 if exists ${$ns}{$params{name}} &&
1726 \&{${$ns}{$params{name}}} == $params{old};
1732 sub pagespec_merge ($$) { #{{{
1736 return $a if $a eq $b;
1738 # Support for old-style GlobLists.
1739 if (is_globlist($a)) {
1740 $a=globlist_to_pagespec($a);
1742 if (is_globlist($b)) {
1743 $b=globlist_to_pagespec($b);
1746 return "($a) or ($b)";
1749 sub pagespec_translate ($) { #{{{
1752 # Support for old-style GlobLists.
1753 if (is_globlist($spec)) {
1754 $spec=globlist_to_pagespec($spec);
1757 # Convert spec to perl code.
1760 \s* # ignore whitespace
1761 ( # 1: match a single word
1768 \w+\([^\)]*\) # command(params)
1770 [^\s()]+ # any other text
1772 \s* # ignore whitespace
1775 if (lc $word eq 'and') {
1778 elsif (lc $word eq 'or') {
1781 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1784 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1785 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1786 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1793 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1797 if (! length $code) {
1802 return eval 'sub { my $page=shift; '.$code.' }';
1805 sub pagespec_match ($$;@) { #{{{
1810 # Backwards compatability with old calling convention.
1812 unshift @params, 'location';
1815 my $sub=pagespec_translate($spec);
1816 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1817 return $sub->($page, @params);
1820 sub pagespec_valid ($) { #{{{
1823 my $sub=pagespec_translate($spec);
1827 sub glob2re ($) { #{{{
1828 my $re=quotemeta(shift);
1834 package IkiWiki::FailReason;
1837 '""' => sub { ${$_[0]} },
1839 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1846 return bless \$value, $class;
1849 package IkiWiki::SuccessReason;
1852 '""' => sub { ${$_[0]} },
1854 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1861 return bless \$value, $class;
1864 package IkiWiki::PageSpec;
1866 sub match_glob ($$;@) { #{{{
1871 my $from=exists $params{location} ? $params{location} : '';
1874 if ($glob =~ m!^\./!) {
1875 $from=~s#/?[^/]+$##;
1877 $glob="$from/$glob" if length $from;
1880 my $regexp=IkiWiki::glob2re($glob);
1881 if ($page=~/^$regexp$/i) {
1882 if (! IkiWiki::isinternal($page) || $params{internal}) {
1883 return IkiWiki::SuccessReason->new("$glob matches $page");
1886 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1890 return IkiWiki::FailReason->new("$glob does not match $page");
1894 sub match_internal ($$;@) { #{{{
1895 return match_glob($_[0], $_[1], @_, internal => 1)
1898 sub match_link ($$;@) { #{{{
1903 my $from=exists $params{location} ? $params{location} : '';
1906 if ($link =~ m!^\.! && defined $from) {
1907 $from=~s#/?[^/]+$##;
1909 $link="$from/$link" if length $from;
1912 my $links = $IkiWiki::links{$page};
1913 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1914 my $bestlink = IkiWiki::bestlink($from, $link);
1915 foreach my $p (@{$links}) {
1916 if (length $bestlink) {
1917 return IkiWiki::SuccessReason->new("$page links to $link")
1918 if $bestlink eq IkiWiki::bestlink($page, $p);
1921 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1922 if match_glob($p, $link, %params);
1925 return IkiWiki::FailReason->new("$page does not link to $link");
1928 sub match_backlink ($$;@) { #{{{
1929 return match_link($_[1], $_[0], @_);
1932 sub match_created_before ($$;@) { #{{{
1936 if (exists $IkiWiki::pagectime{$testpage}) {
1937 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1938 return IkiWiki::SuccessReason->new("$page created before $testpage");
1941 return IkiWiki::FailReason->new("$page not created before $testpage");
1945 return IkiWiki::FailReason->new("$testpage has no ctime");
1949 sub match_created_after ($$;@) { #{{{
1953 if (exists $IkiWiki::pagectime{$testpage}) {
1954 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1955 return IkiWiki::SuccessReason->new("$page created after $testpage");
1958 return IkiWiki::FailReason->new("$page not created after $testpage");
1962 return IkiWiki::FailReason->new("$testpage has no ctime");
1966 sub match_creation_day ($$;@) { #{{{
1967 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1968 return IkiWiki::SuccessReason->new('creation_day matched');
1971 return IkiWiki::FailReason->new('creation_day did not match');
1975 sub match_creation_month ($$;@) { #{{{
1976 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1977 return IkiWiki::SuccessReason->new('creation_month matched');
1980 return IkiWiki::FailReason->new('creation_month did not match');
1984 sub match_creation_year ($$;@) { #{{{
1985 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1986 return IkiWiki::SuccessReason->new('creation_year matched');
1989 return IkiWiki::FailReason->new('creation_year did not match');
1993 sub match_user ($$;@) { #{{{
1998 if (! exists $params{user}) {
1999 return IkiWiki::FailReason->new("no user specified");
2002 if (defined $params{user} && lc $params{user} eq lc $user) {
2003 return IkiWiki::SuccessReason->new("user is $user");
2005 elsif (! defined $params{user}) {
2006 return IkiWiki::FailReason->new("not logged in");
2009 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2013 sub match_admin ($$;@) { #{{{
2018 if (! exists $params{user}) {
2019 return IkiWiki::FailReason->new("no user specified");
2022 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2023 return IkiWiki::SuccessReason->new("user is an admin");
2025 elsif (! defined $params{user}) {
2026 return IkiWiki::FailReason->new("not logged in");
2029 return IkiWiki::FailReason->new("user is not an admin");
2033 sub match_ip ($$;@) { #{{{
2038 if (! exists $params{ip}) {
2039 return IkiWiki::FailReason->new("no IP specified");
2042 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2043 return IkiWiki::SuccessReason->new("IP is $ip");
2046 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");