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 ($$) { #{{{
659 if (! $config{usedirs} || $page eq 'index') {
660 return $page.".".$ext;
663 return $page."/index.".$ext;
667 sub htmlpage ($) { #{{{
670 return targetpage($page, $config{htmlext});
673 sub srcfile_stat { #{{{
677 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
678 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
679 return "$dir/$file", stat(_) if -e "$dir/$file";
681 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
685 sub srcfile ($;$) { #{{{
686 return (srcfile_stat(@_))[0];
689 sub add_underlay ($) { #{{{
693 $dir="$config{underlaydir}/../$dir";
696 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
697 unshift @{$config{underlaydirs}}, $dir;
703 sub readfile ($;$$) { #{{{
709 error("cannot read a symlink ($file)");
713 open (my $in, "<", $file) || error("failed to read $file: $!");
714 binmode($in) if ($binary);
715 return \*$in if $wantfd;
717 close $in || error("failed to read $file: $!");
721 sub prep_writefile ($$) { #{{{
726 while (length $test) {
727 if (-l "$destdir/$test") {
728 error("cannot write to a symlink ($test)");
730 $test=dirname($test);
733 my $dir=dirname("$destdir/$file");
736 foreach my $s (split(m!/+!, $dir)) {
739 mkdir($d) || error("failed to create directory $d: $!");
747 sub writefile ($$$;$$) { #{{{
748 my $file=shift; # can include subdirs
749 my $destdir=shift; # directory to put file in
754 prep_writefile($file, $destdir);
756 my $newfile="$destdir/$file.ikiwiki-new";
758 error("cannot write to a symlink ($newfile)");
761 my $cleanup = sub { unlink($newfile) };
762 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
763 binmode($out) if ($binary);
765 $writer->(\*$out, $cleanup);
768 print $out $content or error("failed writing to $newfile: $!", $cleanup);
770 close $out || error("failed saving $newfile: $!", $cleanup);
771 rename($newfile, "$destdir/$file") ||
772 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
778 sub will_render ($$;$) { #{{{
783 # Important security check.
784 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
785 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
786 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
789 if (! $clear || $cleared{$page}) {
790 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
793 foreach my $old (@{$renderedfiles{$page}}) {
794 delete $destsources{$old};
796 $renderedfiles{$page}=[$dest];
799 $destsources{$dest}=$page;
804 sub bestlink ($$) { #{{{
809 if ($link=~s/^\/+//) {
817 $l.="/" if length $l;
820 if (exists $links{$l}) {
823 elsif (exists $pagecase{lc $l}) {
824 return $pagecase{lc $l};
826 } while $cwd=~s{/?[^/]+$}{};
828 if (length $config{userdir}) {
829 my $l = "$config{userdir}/".lc($link);
830 if (exists $links{$l}) {
833 elsif (exists $pagecase{lc $l}) {
834 return $pagecase{lc $l};
838 #print STDERR "warning: page $page, broken link: $link\n";
842 sub isinlinableimage ($) { #{{{
845 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
848 sub pagetitle ($;$) { #{{{
853 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
856 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
862 sub titlepage ($) { #{{{
864 # support use w/o %config set
865 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
866 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
870 sub linkpage ($) { #{{{
872 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
873 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
877 sub cgiurl (@) { #{{{
880 return $config{cgiurl}."?".
881 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
884 sub baseurl (;$) { #{{{
887 return "$config{url}/" if ! defined $page;
889 $page=htmlpage($page);
891 $page=~s/[^\/]+\//..\//g;
895 sub abs2rel ($$) { #{{{
896 # Work around very innefficient behavior in File::Spec if abs2rel
897 # is passed two relative paths. It's much faster if paths are
898 # absolute! (Debian bug #376658; fixed in debian unstable now)
903 my $ret=File::Spec->abs2rel($path, $base);
904 $ret=~s/^// if defined $ret;
908 sub displaytime ($;$) { #{{{
909 # Plugins can override this function to mark up the time to
911 return '<span class="date">'.formattime(@_).'</span>';
914 sub formattime ($;$) { #{{{
915 # Plugins can override this function to format the time.
918 if (! defined $format) {
919 $format=$config{timeformat};
922 # strftime doesn't know about encodings, so make sure
923 # its output is properly treated as utf8
924 return decode_utf8(POSIX::strftime($format, localtime($time)));
927 sub beautify_urlpath ($) { #{{{
930 if ($config{usedirs}) {
931 $url =~ s!/index.$config{htmlext}$!/!;
934 # Ensure url is not an empty link, and
935 # if it's relative, make that explicit to avoid colon confusion.
943 sub urlto ($$;$) { #{{{
949 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
952 if (! $destsources{$to}) {
957 return $config{url}.beautify_urlpath("/".$to);
960 my $link = abs2rel($to, dirname(htmlpage($from)));
962 return beautify_urlpath($link);
965 sub htmllink ($$$;@) { #{{{
966 my $lpage=shift; # the page doing the linking
967 my $page=shift; # the page that will contain the link (different for inline)
974 if (! $opts{forcesubpage}) {
975 $bestlink=bestlink($lpage, $link);
978 $bestlink="$lpage/".lc($link);
982 if (defined $opts{linktext}) {
983 $linktext=$opts{linktext};
986 $linktext=pagetitle(basename($link));
989 return "<span class=\"selflink\">$linktext</span>"
990 if length $bestlink && $page eq $bestlink &&
991 ! defined $opts{anchor};
993 if (! $destsources{$bestlink}) {
994 $bestlink=htmlpage($bestlink);
996 if (! $destsources{$bestlink}) {
997 return $linktext unless length $config{cgiurl};
998 return "<span class=\"createlink\"><a href=\"".
1004 "\" rel=\"nofollow\">?</a>$linktext</span>"
1008 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1009 $bestlink=beautify_urlpath($bestlink);
1011 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1012 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1015 if (defined $opts{anchor}) {
1016 $bestlink.="#".$opts{anchor};
1020 if (defined $opts{rel}) {
1021 push @attrs, ' rel="'.$opts{rel}.'"';
1023 if (defined $opts{class}) {
1024 push @attrs, ' class="'.$opts{class}.'"';
1027 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1030 sub userlink ($) { #{{{
1033 my $oiduser=eval { openiduser($user) };
1034 if (defined $oiduser) {
1035 return "<a href=\"$user\">$oiduser</a>";
1038 eval q{use CGI 'escapeHTML'};
1041 return htmllink("", "", escapeHTML(
1042 length $config{userdir} ? $config{userdir}."/".$user : $user
1043 ), noimageinline => 1);
1047 sub htmlize ($$$$) { #{{{
1053 my $oneline = $content !~ /\n/;
1055 if (exists $hooks{htmlize}{$type}) {
1056 $content=$hooks{htmlize}{$type}{call}->(
1058 content => $content,
1062 error("htmlization of $type not supported");
1065 run_hooks(sanitize => sub {
1068 destpage => $destpage,
1069 content => $content,
1074 # hack to get rid of enclosing junk added by markdown
1075 # and other htmlizers
1076 $content=~s/^<p>//i;
1077 $content=~s/<\/p>$//i;
1084 sub linkify ($$$) { #{{{
1089 run_hooks(linkify => sub {
1092 destpage => $destpage,
1093 content => $content,
1101 our $preprocess_preview=0;
1102 sub preprocess ($$$;$$) { #{{{
1103 my $page=shift; # the page the data comes from
1104 my $destpage=shift; # the page the data will appear in (different for inline)
1109 # Using local because it needs to be set within any nested calls
1111 local $preprocess_preview=$preview if defined $preview;
1118 $params="" if ! defined $params;
1120 if (length $escape) {
1121 return "[[$prefix$command $params]]";
1123 elsif (exists $hooks{preprocess}{$command}) {
1124 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1125 # Note: preserve order of params, some plugins may
1126 # consider it significant.
1128 while ($params =~ m{
1129 (?:([-\w]+)=)? # 1: named parameter key?
1131 """(.*?)""" # 2: triple-quoted value
1133 "([^"]+)" # 3: single-quoted value
1135 (\S+) # 4: unquoted value
1137 (?:\s+|$) # delimiter to next param
1147 elsif (defined $3) {
1150 elsif (defined $4) {
1155 push @params, $key, $val;
1158 push @params, $val, '';
1161 if ($preprocessing{$page}++ > 3) {
1162 # Avoid loops of preprocessed pages preprocessing
1163 # other pages that preprocess them, etc.
1164 return "[[!$command <span class=\"error\">".
1165 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1166 $page, $preprocessing{$page}).
1172 $hooks{preprocess}{$command}{call}->(
1175 destpage => $destpage,
1176 preview => $preprocess_preview,
1181 $ret="[[!$command <span class=\"error\">".
1182 gettext("Error").": $@"."</span>]]";
1186 # use void context during scan pass
1188 $hooks{preprocess}{$command}{call}->(
1191 destpage => $destpage,
1192 preview => $preprocess_preview,
1197 $preprocessing{$page}--;
1201 return "[[$prefix$command $params]]";
1206 if ($config{prefix_directives}) {
1209 \[\[(!) # directive open; 2: prefix
1210 ([-\w]+) # 3: command
1211 ( # 4: the parameters..
1212 \s+ # Must have space if parameters present
1214 (?:[-\w]+=)? # named parameter key?
1216 """.*?""" # triple-quoted value
1218 "[^"]+" # single-quoted value
1220 [^\s\]]+ # unquoted value
1222 \s* # whitespace or end
1225 *)? # 0 or more parameters
1226 \]\] # directive closed
1232 \[\[(!?) # directive open; 2: optional prefix
1233 ([-\w]+) # 3: command
1235 ( # 4: the parameters..
1237 (?:[-\w]+=)? # named parameter key?
1239 """.*?""" # triple-quoted value
1241 "[^"]+" # single-quoted value
1243 [^\s\]]+ # unquoted value
1245 \s* # whitespace or end
1248 *) # 0 or more parameters
1249 \]\] # directive closed
1253 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1257 sub filter ($$$) { #{{{
1262 run_hooks(filter => sub {
1263 $content=shift->(page => $page, destpage => $destpage,
1264 content => $content);
1270 sub indexlink () { #{{{
1271 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1276 sub lockwiki (;$) { #{{{
1277 my $wait=@_ ? shift : 1;
1278 # Take an exclusive lock on the wiki to prevent multiple concurrent
1279 # run issues. The lock will be dropped on program exit.
1280 if (! -d $config{wikistatedir}) {
1281 mkdir($config{wikistatedir});
1283 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1284 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1285 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1287 debug("wiki seems to be locked, waiting for lock");
1288 my $wait=600; # arbitrary, but don't hang forever to
1289 # prevent process pileup
1291 return if flock($wikilock, 2 | 4);
1294 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1303 sub unlockwiki () { #{{{
1304 return close($wikilock) if $wikilock;
1310 sub commit_hook_enabled () { #{{{
1311 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1312 error("cannot write to $config{wikistatedir}/commitlock: $!");
1313 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1314 close($commitlock) || error("failed closing commitlock: $!");
1317 close($commitlock) || error("failed closing commitlock: $!");
1321 sub disable_commit_hook () { #{{{
1322 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1323 error("cannot write to $config{wikistatedir}/commitlock: $!");
1324 if (! flock($commitlock, 2)) { # LOCK_EX
1325 error("failed to get commit lock");
1330 sub enable_commit_hook () { #{{{
1331 return close($commitlock) if $commitlock;
1335 sub loadindex () { #{{{
1336 %oldrenderedfiles=%pagectime=();
1337 if (! $config{rebuild}) {
1338 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1339 %destsources=%renderedfiles=%pagecase=%pagestate=();
1342 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1343 if (-e "$config{wikistatedir}/index") {
1344 system("ikiwiki-transition", "indexdb", $config{srcdir});
1345 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1352 my $index=Storable::fd_retrieve($in);
1353 if (! defined $index) {
1358 if (exists $index->{version} && ! ref $index->{version}) {
1359 $pages=$index->{page};
1360 %wikistate=%{$index->{state}};
1367 foreach my $src (keys %$pages) {
1368 my $d=$pages->{$src};
1369 my $page=pagename($src);
1370 $pagectime{$page}=$d->{ctime};
1371 if (! $config{rebuild}) {
1372 $pagesources{$page}=$src;
1373 $pagemtime{$page}=$d->{mtime};
1374 $renderedfiles{$page}=$d->{dest};
1375 if (exists $d->{links} && ref $d->{links}) {
1376 $links{$page}=$d->{links};
1377 $oldlinks{$page}=[@{$d->{links}}];
1379 if (exists $d->{depends}) {
1380 $depends{$page}=$d->{depends};
1382 if (exists $d->{state}) {
1383 $pagestate{$page}=$d->{state};
1386 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1388 foreach my $page (keys %pagesources) {
1389 $pagecase{lc $page}=$page;
1391 foreach my $page (keys %renderedfiles) {
1392 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1397 sub saveindex () { #{{{
1398 run_hooks(savestate => sub { shift->() });
1401 foreach my $type (keys %hooks) {
1402 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1404 my @hookids=keys %hookids;
1406 if (! -d $config{wikistatedir}) {
1407 mkdir($config{wikistatedir});
1409 my $newfile="$config{wikistatedir}/indexdb.new";
1410 my $cleanup = sub { unlink($newfile) };
1411 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1414 foreach my $page (keys %pagemtime) {
1415 next unless $pagemtime{$page};
1416 my $src=$pagesources{$page};
1418 $index{page}{$src}={
1419 ctime => $pagectime{$page},
1420 mtime => $pagemtime{$page},
1421 dest => $renderedfiles{$page},
1422 links => $links{$page},
1425 if (exists $depends{$page}) {
1426 $index{page}{$src}{depends} = $depends{$page};
1429 if (exists $pagestate{$page}) {
1430 foreach my $id (@hookids) {
1431 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1432 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1439 foreach my $id (@hookids) {
1440 foreach my $key (keys %{$wikistate{$id}}) {
1441 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1445 $index{version}="3";
1446 my $ret=Storable::nstore_fd(\%index, $out);
1447 return if ! defined $ret || ! $ret;
1448 close $out || error("failed saving to $newfile: $!", $cleanup);
1449 rename($newfile, "$config{wikistatedir}/indexdb") ||
1450 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1455 sub template_file ($) { #{{{
1458 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1459 return "$dir/$template" if -e "$dir/$template";
1464 sub template_params (@) { #{{{
1465 my $filename=template_file(shift);
1467 if (! defined $filename) {
1468 return if wantarray;
1474 my $text_ref = shift;
1475 ${$text_ref} = decode_utf8(${$text_ref});
1477 filename => $filename,
1478 loop_context_vars => 1,
1479 die_on_bad_params => 0,
1482 return wantarray ? @ret : {@ret};
1485 sub template ($;@) { #{{{
1486 require HTML::Template;
1487 return HTML::Template->new(template_params(@_));
1490 sub misctemplate ($$;@) { #{{{
1494 my $template=template("misc.tmpl");
1497 indexlink => indexlink(),
1498 wikiname => $config{wikiname},
1499 pagebody => $pagebody,
1500 baseurl => baseurl(),
1503 run_hooks(pagetemplate => sub {
1504 shift->(page => "", destpage => "", template => $template);
1506 return $template->output;
1509 sub hook (@) { # {{{
1512 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1513 error 'hook requires type, call, and id parameters';
1516 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1518 $hooks{$param{type}}{$param{id}}=\%param;
1522 sub run_hooks ($$) { # {{{
1523 # Calls the given sub for each hook of the given type,
1524 # passing it the hook function to call.
1528 if (exists $hooks{$type}) {
1530 foreach my $id (keys %{$hooks{$type}}) {
1531 if ($hooks{$type}{$id}{last}) {
1532 push @deferred, $id;
1535 $sub->($hooks{$type}{$id}{call});
1537 foreach my $id (@deferred) {
1538 $sub->($hooks{$type}{$id}{call});
1545 sub rcs_update () { #{{{
1546 $hooks{rcs}{rcs_update}{call}->(@_);
1549 sub rcs_prepedit ($) { #{{{
1550 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1553 sub rcs_commit ($$$;$$) { #{{{
1554 $hooks{rcs}{rcs_commit}{call}->(@_);
1557 sub rcs_commit_staged ($$$) { #{{{
1558 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1561 sub rcs_add ($) { #{{{
1562 $hooks{rcs}{rcs_add}{call}->(@_);
1565 sub rcs_remove ($) { #{{{
1566 $hooks{rcs}{rcs_remove}{call}->(@_);
1569 sub rcs_rename ($$) { #{{{
1570 $hooks{rcs}{rcs_rename}{call}->(@_);
1573 sub rcs_recentchanges ($) { #{{{
1574 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1577 sub rcs_diff ($) { #{{{
1578 $hooks{rcs}{rcs_diff}{call}->(@_);
1581 sub rcs_getctime ($) { #{{{
1582 $hooks{rcs}{rcs_getctime}{call}->(@_);
1585 sub rcs_receive () { #{{{
1586 $hooks{rcs}{rcs_receive}{call}->();
1589 sub globlist_to_pagespec ($) { #{{{
1590 my @globlist=split(' ', shift);
1593 foreach my $glob (@globlist) {
1594 if ($glob=~/^!(.*)/) {
1602 my $spec=join(' or ', @spec);
1604 my $skip=join(' and ', @skip);
1606 $spec="$skip and ($spec)";
1615 sub is_globlist ($) { #{{{
1617 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1620 sub safequote ($) { #{{{
1626 sub add_depends ($$) { #{{{
1630 return unless pagespec_valid($pagespec);
1632 if (! exists $depends{$page}) {
1633 $depends{$page}=$pagespec;
1636 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1642 sub file_pruned ($$) { #{{{
1644 my $file=File::Spec->canonpath(shift);
1645 my $base=File::Spec->canonpath(shift);
1646 $file =~ s#^\Q$base\E/+##;
1648 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1649 return $file =~ m/$regexp/ && $file ne $base;
1653 # Only use gettext in the rare cases it's needed.
1654 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1655 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1656 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1657 if (! $gettext_obj) {
1658 $gettext_obj=eval q{
1659 use Locale::gettext q{textdomain};
1660 Locale::gettext->domain('ikiwiki')
1668 return $gettext_obj->get(shift);
1675 sub yesno ($) { #{{{
1678 return (defined $val && lc($val) eq gettext("yes"));
1682 # Injects a new function into the symbol table to replace an
1683 # exported function.
1686 # This is deep ugly perl foo, beware.
1689 if (! defined $params{parent}) {
1690 $params{parent}='::';
1691 $params{old}=\&{$params{name}};
1692 $params{name}=~s/.*:://;
1694 my $parent=$params{parent};
1695 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1696 $ns = $params{parent} . $ns;
1697 inject(%params, parent => $ns) unless $ns eq '::main::';
1698 *{$ns . $params{name}} = $params{call}
1699 if exists ${$ns}{$params{name}} &&
1700 \&{${$ns}{$params{name}}} == $params{old};
1706 sub pagespec_merge ($$) { #{{{
1710 return $a if $a eq $b;
1712 # Support for old-style GlobLists.
1713 if (is_globlist($a)) {
1714 $a=globlist_to_pagespec($a);
1716 if (is_globlist($b)) {
1717 $b=globlist_to_pagespec($b);
1720 return "($a) or ($b)";
1723 sub pagespec_translate ($) { #{{{
1726 # Support for old-style GlobLists.
1727 if (is_globlist($spec)) {
1728 $spec=globlist_to_pagespec($spec);
1731 # Convert spec to perl code.
1734 \s* # ignore whitespace
1735 ( # 1: match a single word
1742 \w+\([^\)]*\) # command(params)
1744 [^\s()]+ # any other text
1746 \s* # ignore whitespace
1749 if (lc $word eq 'and') {
1752 elsif (lc $word eq 'or') {
1755 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1758 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1759 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1760 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1767 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1771 if (! length $code) {
1776 return eval 'sub { my $page=shift; '.$code.' }';
1779 sub pagespec_match ($$;@) { #{{{
1784 # Backwards compatability with old calling convention.
1786 unshift @params, 'location';
1789 my $sub=pagespec_translate($spec);
1790 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1791 return $sub->($page, @params);
1794 sub pagespec_valid ($) { #{{{
1797 my $sub=pagespec_translate($spec);
1801 sub glob2re ($) { #{{{
1802 my $re=quotemeta(shift);
1808 package IkiWiki::FailReason;
1811 '""' => sub { ${$_[0]} },
1813 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1820 return bless \$value, $class;
1823 package IkiWiki::SuccessReason;
1826 '""' => sub { ${$_[0]} },
1828 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1835 return bless \$value, $class;
1838 package IkiWiki::PageSpec;
1840 sub match_glob ($$;@) { #{{{
1845 my $from=exists $params{location} ? $params{location} : '';
1848 if ($glob =~ m!^\./!) {
1849 $from=~s#/?[^/]+$##;
1851 $glob="$from/$glob" if length $from;
1854 my $regexp=IkiWiki::glob2re($glob);
1855 if ($page=~/^$regexp$/i) {
1856 if (! IkiWiki::isinternal($page) || $params{internal}) {
1857 return IkiWiki::SuccessReason->new("$glob matches $page");
1860 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1864 return IkiWiki::FailReason->new("$glob does not match $page");
1868 sub match_internal ($$;@) { #{{{
1869 return match_glob($_[0], $_[1], @_, internal => 1)
1872 sub match_link ($$;@) { #{{{
1877 my $from=exists $params{location} ? $params{location} : '';
1880 if ($link =~ m!^\.! && defined $from) {
1881 $from=~s#/?[^/]+$##;
1883 $link="$from/$link" if length $from;
1886 my $links = $IkiWiki::links{$page};
1887 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1888 my $bestlink = IkiWiki::bestlink($from, $link);
1889 foreach my $p (@{$links}) {
1890 if (length $bestlink) {
1891 return IkiWiki::SuccessReason->new("$page links to $link")
1892 if $bestlink eq IkiWiki::bestlink($page, $p);
1895 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1896 if match_glob($p, $link, %params);
1899 return IkiWiki::FailReason->new("$page does not link to $link");
1902 sub match_backlink ($$;@) { #{{{
1903 return match_link($_[1], $_[0], @_);
1906 sub match_created_before ($$;@) { #{{{
1910 if (exists $IkiWiki::pagectime{$testpage}) {
1911 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1912 return IkiWiki::SuccessReason->new("$page created before $testpage");
1915 return IkiWiki::FailReason->new("$page not created before $testpage");
1919 return IkiWiki::FailReason->new("$testpage has no ctime");
1923 sub match_created_after ($$;@) { #{{{
1927 if (exists $IkiWiki::pagectime{$testpage}) {
1928 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1929 return IkiWiki::SuccessReason->new("$page created after $testpage");
1932 return IkiWiki::FailReason->new("$page not created after $testpage");
1936 return IkiWiki::FailReason->new("$testpage has no ctime");
1940 sub match_creation_day ($$;@) { #{{{
1941 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1942 return IkiWiki::SuccessReason->new('creation_day matched');
1945 return IkiWiki::FailReason->new('creation_day did not match');
1949 sub match_creation_month ($$;@) { #{{{
1950 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1951 return IkiWiki::SuccessReason->new('creation_month matched');
1954 return IkiWiki::FailReason->new('creation_month did not match');
1958 sub match_creation_year ($$;@) { #{{{
1959 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1960 return IkiWiki::SuccessReason->new('creation_year matched');
1963 return IkiWiki::FailReason->new('creation_year did not match');
1967 sub match_user ($$;@) { #{{{
1972 if (! exists $params{user}) {
1973 return IkiWiki::FailReason->new("no user specified");
1976 if (defined $params{user} && lc $params{user} eq lc $user) {
1977 return IkiWiki::SuccessReason->new("user is $user");
1979 elsif (! defined $params{user}) {
1980 return IkiWiki::FailReason->new("not logged in");
1983 return IkiWiki::FailReason->new("user is $params{user}, not $user");
1987 sub match_admin ($$;@) { #{{{
1992 if (! exists $params{user}) {
1993 return IkiWiki::FailReason->new("no user specified");
1996 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
1997 return IkiWiki::SuccessReason->new("user is an admin");
1999 elsif (! defined $params{user}) {
2000 return IkiWiki::FailReason->new("not logged in");
2003 return IkiWiki::FailReason->new("user is not an admin");
2007 sub match_ip ($$;@) { #{{{
2012 if (! exists $params{ip}) {
2013 return IkiWiki::FailReason->new("no IP specified");
2016 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2017 return IkiWiki::SuccessReason->new("IP is $ip");
2020 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");