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 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 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 the .ikiwiki directory holding ikiwiki state",
416 description => "path to setup file",
420 allow_symlinks_before_srcdir => {
423 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
429 sub defaultconfig () { #{{{
432 foreach my $key (keys %s) {
433 push @ret, $key, $s{$key}->{default};
439 sub checkconfig () { #{{{
440 # locale stuff; avoid LC_ALL since it overrides everything
441 if (defined $ENV{LC_ALL}) {
442 $ENV{LANG} = $ENV{LC_ALL};
445 if (defined $config{locale}) {
446 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
447 $ENV{LANG}=$config{locale};
452 if (! defined $config{wiki_file_regexp}) {
453 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
456 if (ref $config{ENV} eq 'HASH') {
457 foreach my $val (keys %{$config{ENV}}) {
458 $ENV{$val}=$config{ENV}{$val};
462 if ($config{w3mmode}) {
463 eval q{use Cwd q{abs_path}};
465 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
466 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
467 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
468 unless $config{cgiurl} =~ m!file:///!;
469 $config{url}="file://".$config{destdir};
472 if ($config{cgi} && ! length $config{url}) {
473 error(gettext("Must specify url to wiki with --url when using --cgi"));
476 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
477 unless exists $config{wikistatedir} && defined $config{wikistatedir};
479 if (defined $config{umask}) {
480 umask(possibly_foolish_untaint($config{umask}));
483 run_hooks(checkconfig => sub { shift->() });
488 sub listplugins () { #{{{
491 foreach my $dir (@INC, $config{libdir}) {
492 next unless defined $dir && length $dir;
493 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
494 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
498 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
499 next unless defined $dir && length $dir;
500 foreach my $file (glob("$dir/plugins/*")) {
501 $ret{basename($file)}=1 if -x $file;
508 sub loadplugins () { #{{{
509 if (defined $config{libdir} && length $config{libdir}) {
510 unshift @INC, possibly_foolish_untaint($config{libdir});
513 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
518 if (exists $IkiWiki::hooks{rcs}) {
519 error(gettext("cannot use multiple rcs plugins"));
521 loadplugin($config{rcs});
523 if (! exists $IkiWiki::hooks{rcs}) {
527 run_hooks(getopt => sub { shift->() });
528 if (grep /^-/, @ARGV) {
529 print STDERR "Unknown option: $_\n"
530 foreach grep /^-/, @ARGV;
537 sub loadplugin ($) { #{{{
540 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
542 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
543 "$installdir/lib/ikiwiki") {
544 if (defined $dir && -x "$dir/plugins/$plugin") {
545 eval { require IkiWiki::Plugin::external };
548 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
550 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
551 $loaded_plugins{$plugin}=1;
556 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
559 error("Failed to load plugin $mod: $@");
561 $loaded_plugins{$plugin}=1;
565 sub error ($;$) { #{{{
568 log_message('err' => $message) if $config{syslog};
569 if (defined $cleaner) {
576 return unless $config{verbose};
577 return log_message(debug => @_);
581 sub log_message ($$) { #{{{
584 if ($config{syslog}) {
587 Sys::Syslog::setlogsock('unix');
588 Sys::Syslog::openlog('ikiwiki', '', 'user');
592 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
595 elsif (! $config{cgi}) {
599 return print STDERR "@_\n";
603 sub possibly_foolish_untaint ($) { #{{{
605 my ($untainted)=$tainted=~/(.*)/s;
609 sub basename ($) { #{{{
616 sub dirname ($) { #{{{
623 sub pagetype ($) { #{{{
626 if ($page =~ /\.([^.]+)$/) {
627 return $1 if exists $hooks{htmlize}{$1};
632 sub isinternal ($) { #{{{
634 return exists $pagesources{$page} &&
635 $pagesources{$page} =~ /\._([^.]+)$/;
638 sub pagename ($) { #{{{
641 my $type=pagetype($file);
643 $page=~s/\Q.$type\E*$// if defined $type && !$hooks{htmlize}{$type}{keepextension};
644 if ($config{indexpages} && $page=~/(.*)\/index$/) {
650 sub newpagefile ($$) { #{{{
654 if (! $config{indexpages} || $page eq 'index') {
655 return $page.".".$type;
658 return $page."/index.".$type;
662 sub targetpage ($$) { #{{{
666 if (! $config{usedirs} || $page eq 'index') {
667 return $page.".".$ext;
670 return $page."/index.".$ext;
674 sub htmlpage ($) { #{{{
677 return targetpage($page, $config{htmlext});
680 sub srcfile_stat { #{{{
684 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
685 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
686 return "$dir/$file", stat(_) if -e "$dir/$file";
688 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
692 sub srcfile ($;$) { #{{{
693 return (srcfile_stat(@_))[0];
696 sub add_underlay ($) { #{{{
700 $dir="$config{underlaydir}/../$dir";
703 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
704 unshift @{$config{underlaydirs}}, $dir;
710 sub readfile ($;$$) { #{{{
716 error("cannot read a symlink ($file)");
720 open (my $in, "<", $file) || error("failed to read $file: $!");
721 binmode($in) if ($binary);
722 return \*$in if $wantfd;
724 # check for invalid utf-8, and toss it back to avoid crashes
725 if (! utf8::valid($ret)) {
726 $ret=encode_utf8($ret);
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 ($$) { #{{{
820 if ($link=~s/^\/+//) {
828 $l.="/" if length $l;
831 if (exists $links{$l}) {
834 elsif (exists $pagecase{lc $l}) {
835 return $pagecase{lc $l};
837 } while $cwd=~s{/?[^/]+$}{};
839 if (length $config{userdir}) {
840 my $l = "$config{userdir}/".lc($link);
841 if (exists $links{$l}) {
844 elsif (exists $pagecase{lc $l}) {
845 return $pagecase{lc $l};
849 #print STDERR "warning: page $page, broken link: $link\n";
853 sub isinlinableimage ($) { #{{{
856 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
859 sub pagetitle ($;$) { #{{{
864 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
867 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
873 sub titlepage ($) { #{{{
875 # support use w/o %config set
876 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
877 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
881 sub linkpage ($) { #{{{
883 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
884 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
888 sub cgiurl (@) { #{{{
891 return $config{cgiurl}."?".
892 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
895 sub baseurl (;$) { #{{{
898 return "$config{url}/" if ! defined $page;
900 $page=htmlpage($page);
902 $page=~s/[^\/]+\//..\//g;
906 sub abs2rel ($$) { #{{{
907 # Work around very innefficient behavior in File::Spec if abs2rel
908 # is passed two relative paths. It's much faster if paths are
909 # absolute! (Debian bug #376658; fixed in debian unstable now)
914 my $ret=File::Spec->abs2rel($path, $base);
915 $ret=~s/^// if defined $ret;
919 sub displaytime ($;$) { #{{{
920 # Plugins can override this function to mark up the time to
922 return '<span class="date">'.formattime(@_).'</span>';
925 sub formattime ($;$) { #{{{
926 # Plugins can override this function to format the time.
929 if (! defined $format) {
930 $format=$config{timeformat};
933 # strftime doesn't know about encodings, so make sure
934 # its output is properly treated as utf8
935 return decode_utf8(POSIX::strftime($format, localtime($time)));
938 sub beautify_urlpath ($) { #{{{
941 if ($config{usedirs}) {
942 $url =~ s!/index.$config{htmlext}$!/!;
945 # Ensure url is not an empty link, and
946 # if it's relative, make that explicit to avoid colon confusion.
954 sub urlto ($$;$) { #{{{
960 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
963 if (! $destsources{$to}) {
968 return $config{url}.beautify_urlpath("/".$to);
971 my $link = abs2rel($to, dirname(htmlpage($from)));
973 return beautify_urlpath($link);
976 sub htmllink ($$$;@) { #{{{
977 my $lpage=shift; # the page doing the linking
978 my $page=shift; # the page that will contain the link (different for inline)
985 if (! $opts{forcesubpage}) {
986 $bestlink=bestlink($lpage, $link);
989 $bestlink="$lpage/".lc($link);
993 if (defined $opts{linktext}) {
994 $linktext=$opts{linktext};
997 $linktext=pagetitle(basename($link));
1000 return "<span class=\"selflink\">$linktext</span>"
1001 if length $bestlink && $page eq $bestlink &&
1002 ! defined $opts{anchor};
1004 if (! $destsources{$bestlink}) {
1005 $bestlink=htmlpage($bestlink);
1007 if (! $destsources{$bestlink}) {
1008 return $linktext unless length $config{cgiurl};
1009 return "<span class=\"createlink\"><a href=\"".
1015 "\" rel=\"nofollow\">?</a>$linktext</span>"
1019 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1020 $bestlink=beautify_urlpath($bestlink);
1022 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1023 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1026 if (defined $opts{anchor}) {
1027 $bestlink.="#".$opts{anchor};
1031 if (defined $opts{rel}) {
1032 push @attrs, ' rel="'.$opts{rel}.'"';
1034 if (defined $opts{class}) {
1035 push @attrs, ' class="'.$opts{class}.'"';
1038 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1041 sub userlink ($) { #{{{
1044 my $oiduser=eval { openiduser($user) };
1045 if (defined $oiduser) {
1046 return "<a href=\"$user\">$oiduser</a>";
1049 eval q{use CGI 'escapeHTML'};
1052 return htmllink("", "", escapeHTML(
1053 length $config{userdir} ? $config{userdir}."/".$user : $user
1054 ), noimageinline => 1);
1058 sub htmlize ($$$$) { #{{{
1064 my $oneline = $content !~ /\n/;
1066 if (exists $hooks{htmlize}{$type}) {
1067 $content=$hooks{htmlize}{$type}{call}->(
1069 content => $content,
1073 error("htmlization of $type not supported");
1076 run_hooks(sanitize => sub {
1079 destpage => $destpage,
1080 content => $content,
1085 # hack to get rid of enclosing junk added by markdown
1086 # and other htmlizers
1087 $content=~s/^<p>//i;
1088 $content=~s/<\/p>$//i;
1095 sub linkify ($$$) { #{{{
1100 run_hooks(linkify => sub {
1103 destpage => $destpage,
1104 content => $content,
1112 our $preprocess_preview=0;
1113 sub preprocess ($$$;$$) { #{{{
1114 my $page=shift; # the page the data comes from
1115 my $destpage=shift; # the page the data will appear in (different for inline)
1120 # Using local because it needs to be set within any nested calls
1122 local $preprocess_preview=$preview if defined $preview;
1129 $params="" if ! defined $params;
1131 if (length $escape) {
1132 return "[[$prefix$command $params]]";
1134 elsif (exists $hooks{preprocess}{$command}) {
1135 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1136 # Note: preserve order of params, some plugins may
1137 # consider it significant.
1139 while ($params =~ m{
1140 (?:([-\w]+)=)? # 1: named parameter key?
1142 """(.*?)""" # 2: triple-quoted value
1144 "([^"]+)" # 3: single-quoted value
1146 (\S+) # 4: unquoted value
1148 (?:\s+|$) # delimiter to next param
1158 elsif (defined $3) {
1161 elsif (defined $4) {
1166 push @params, $key, $val;
1169 push @params, $val, '';
1172 if ($preprocessing{$page}++ > 3) {
1173 # Avoid loops of preprocessed pages preprocessing
1174 # other pages that preprocess them, etc.
1175 return "[[!$command <span class=\"error\">".
1176 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1177 $page, $preprocessing{$page}).
1183 $hooks{preprocess}{$command}{call}->(
1186 destpage => $destpage,
1187 preview => $preprocess_preview,
1192 $ret="[[!$command <span class=\"error\">".
1193 gettext("Error").": $@"."</span>]]";
1197 # use void context during scan pass
1199 $hooks{preprocess}{$command}{call}->(
1202 destpage => $destpage,
1203 preview => $preprocess_preview,
1208 $preprocessing{$page}--;
1212 return "[[$prefix$command $params]]";
1217 if ($config{prefix_directives}) {
1220 \[\[(!) # directive open; 2: prefix
1221 ([-\w]+) # 3: command
1222 ( # 4: the parameters..
1223 \s+ # Must have space if parameters present
1225 (?:[-\w]+=)? # named parameter key?
1227 """.*?""" # triple-quoted value
1229 "[^"]+" # single-quoted value
1231 [^\s\]]+ # unquoted value
1233 \s* # whitespace or end
1236 *)? # 0 or more parameters
1237 \]\] # directive closed
1243 \[\[(!?) # directive open; 2: optional prefix
1244 ([-\w]+) # 3: command
1246 ( # 4: the parameters..
1248 (?:[-\w]+=)? # named parameter key?
1250 """.*?""" # triple-quoted value
1252 "[^"]+" # single-quoted value
1254 [^\s\]]+ # unquoted value
1256 \s* # whitespace or end
1259 *) # 0 or more parameters
1260 \]\] # directive closed
1264 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1268 sub filter ($$$) { #{{{
1273 run_hooks(filter => sub {
1274 $content=shift->(page => $page, destpage => $destpage,
1275 content => $content);
1281 sub indexlink () { #{{{
1282 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1287 sub lockwiki () { #{{{
1288 # Take an exclusive lock on the wiki to prevent multiple concurrent
1289 # run issues. The lock will be dropped on program exit.
1290 if (! -d $config{wikistatedir}) {
1291 mkdir($config{wikistatedir});
1293 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1294 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1295 if (! flock($wikilock, 2)) { # LOCK_EX
1296 error("failed to get lock");
1301 sub unlockwiki () { #{{{
1302 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1303 return close($wikilock) if $wikilock;
1309 sub commit_hook_enabled () { #{{{
1310 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1311 error("cannot write to $config{wikistatedir}/commitlock: $!");
1312 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1313 close($commitlock) || error("failed closing commitlock: $!");
1316 close($commitlock) || error("failed closing commitlock: $!");
1320 sub disable_commit_hook () { #{{{
1321 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1322 error("cannot write to $config{wikistatedir}/commitlock: $!");
1323 if (! flock($commitlock, 2)) { # LOCK_EX
1324 error("failed to get commit lock");
1329 sub enable_commit_hook () { #{{{
1330 return close($commitlock) if $commitlock;
1334 sub loadindex () { #{{{
1335 %oldrenderedfiles=%pagectime=();
1336 if (! $config{rebuild}) {
1337 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1338 %destsources=%renderedfiles=%pagecase=%pagestate=();
1341 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1342 if (-e "$config{wikistatedir}/index") {
1343 system("ikiwiki-transition", "indexdb", $config{srcdir});
1344 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1351 my $index=Storable::fd_retrieve($in);
1352 if (! defined $index) {
1357 if (exists $index->{version} && ! ref $index->{version}) {
1358 $pages=$index->{page};
1359 %wikistate=%{$index->{state}};
1366 foreach my $src (keys %$pages) {
1367 my $d=$pages->{$src};
1368 my $page=pagename($src);
1369 $pagectime{$page}=$d->{ctime};
1370 if (! $config{rebuild}) {
1371 $pagesources{$page}=$src;
1372 $pagemtime{$page}=$d->{mtime};
1373 $renderedfiles{$page}=$d->{dest};
1374 if (exists $d->{links} && ref $d->{links}) {
1375 $links{$page}=$d->{links};
1376 $oldlinks{$page}=[@{$d->{links}}];
1378 if (exists $d->{depends}) {
1379 $depends{$page}=$d->{depends};
1381 if (exists $d->{state}) {
1382 $pagestate{$page}=$d->{state};
1385 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1387 foreach my $page (keys %pagesources) {
1388 $pagecase{lc $page}=$page;
1390 foreach my $page (keys %renderedfiles) {
1391 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1396 sub saveindex () { #{{{
1397 run_hooks(savestate => sub { shift->() });
1400 foreach my $type (keys %hooks) {
1401 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1403 my @hookids=keys %hookids;
1405 if (! -d $config{wikistatedir}) {
1406 mkdir($config{wikistatedir});
1408 my $newfile="$config{wikistatedir}/indexdb.new";
1409 my $cleanup = sub { unlink($newfile) };
1410 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1413 foreach my $page (keys %pagemtime) {
1414 next unless $pagemtime{$page};
1415 my $src=$pagesources{$page};
1417 $index{page}{$src}={
1418 ctime => $pagectime{$page},
1419 mtime => $pagemtime{$page},
1420 dest => $renderedfiles{$page},
1421 links => $links{$page},
1424 if (exists $depends{$page}) {
1425 $index{page}{$src}{depends} = $depends{$page};
1428 if (exists $pagestate{$page}) {
1429 foreach my $id (@hookids) {
1430 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1431 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1438 foreach my $id (@hookids) {
1439 foreach my $key (keys %{$wikistate{$id}}) {
1440 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1444 $index{version}="3";
1445 my $ret=Storable::nstore_fd(\%index, $out);
1446 return if ! defined $ret || ! $ret;
1447 close $out || error("failed saving to $newfile: $!", $cleanup);
1448 rename($newfile, "$config{wikistatedir}/indexdb") ||
1449 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1454 sub template_file ($) { #{{{
1457 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1458 return "$dir/$template" if -e "$dir/$template";
1463 sub template_params (@) { #{{{
1464 my $filename=template_file(shift);
1466 if (! defined $filename) {
1467 return if wantarray;
1473 my $text_ref = shift;
1474 ${$text_ref} = decode_utf8(${$text_ref});
1476 filename => $filename,
1477 loop_context_vars => 1,
1478 die_on_bad_params => 0,
1481 return wantarray ? @ret : {@ret};
1484 sub template ($;@) { #{{{
1485 require HTML::Template;
1486 return HTML::Template->new(template_params(@_));
1489 sub misctemplate ($$;@) { #{{{
1493 my $template=template("misc.tmpl");
1496 indexlink => indexlink(),
1497 wikiname => $config{wikiname},
1498 pagebody => $pagebody,
1499 baseurl => baseurl(),
1502 run_hooks(pagetemplate => sub {
1503 shift->(page => "", destpage => "", template => $template);
1505 return $template->output;
1508 sub hook (@) { # {{{
1511 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1512 error 'hook requires type, call, and id parameters';
1515 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1517 $hooks{$param{type}}{$param{id}}=\%param;
1521 sub run_hooks ($$) { # {{{
1522 # Calls the given sub for each hook of the given type,
1523 # passing it the hook function to call.
1527 if (exists $hooks{$type}) {
1529 foreach my $id (keys %{$hooks{$type}}) {
1530 if ($hooks{$type}{$id}{last}) {
1531 push @deferred, $id;
1534 $sub->($hooks{$type}{$id}{call});
1536 foreach my $id (@deferred) {
1537 $sub->($hooks{$type}{$id}{call});
1544 sub rcs_update () { #{{{
1545 $hooks{rcs}{rcs_update}{call}->(@_);
1548 sub rcs_prepedit ($) { #{{{
1549 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1552 sub rcs_commit ($$$;$$) { #{{{
1553 $hooks{rcs}{rcs_commit}{call}->(@_);
1556 sub rcs_commit_staged ($$$) { #{{{
1557 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1560 sub rcs_add ($) { #{{{
1561 $hooks{rcs}{rcs_add}{call}->(@_);
1564 sub rcs_remove ($) { #{{{
1565 $hooks{rcs}{rcs_remove}{call}->(@_);
1568 sub rcs_rename ($$) { #{{{
1569 $hooks{rcs}{rcs_rename}{call}->(@_);
1572 sub rcs_recentchanges ($) { #{{{
1573 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1576 sub rcs_diff ($) { #{{{
1577 $hooks{rcs}{rcs_diff}{call}->(@_);
1580 sub rcs_getctime ($) { #{{{
1581 $hooks{rcs}{rcs_getctime}{call}->(@_);
1584 sub rcs_receive () { #{{{
1585 $hooks{rcs}{rcs_receive}{call}->();
1588 sub globlist_to_pagespec ($) { #{{{
1589 my @globlist=split(' ', shift);
1592 foreach my $glob (@globlist) {
1593 if ($glob=~/^!(.*)/) {
1601 my $spec=join(' or ', @spec);
1603 my $skip=join(' and ', @skip);
1605 $spec="$skip and ($spec)";
1614 sub is_globlist ($) { #{{{
1616 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1619 sub safequote ($) { #{{{
1625 sub add_depends ($$) { #{{{
1629 return unless pagespec_valid($pagespec);
1631 if (! exists $depends{$page}) {
1632 $depends{$page}=$pagespec;
1635 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1641 sub file_pruned ($$) { #{{{
1643 my $file=File::Spec->canonpath(shift);
1644 my $base=File::Spec->canonpath(shift);
1645 $file =~ s#^\Q$base\E/+##;
1647 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1648 return $file =~ m/$regexp/ && $file ne $base;
1652 # Only use gettext in the rare cases it's needed.
1653 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1654 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1655 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1656 if (! $gettext_obj) {
1657 $gettext_obj=eval q{
1658 use Locale::gettext q{textdomain};
1659 Locale::gettext->domain('ikiwiki')
1667 return $gettext_obj->get(shift);
1674 sub yesno ($) { #{{{
1677 return (defined $val && lc($val) eq gettext("yes"));
1681 # Injects a new function into the symbol table to replace an
1682 # exported function.
1685 # This is deep ugly perl foo, beware.
1688 if (! defined $params{parent}) {
1689 $params{parent}='::';
1690 $params{old}=\&{$params{name}};
1691 $params{name}=~s/.*:://;
1693 my $parent=$params{parent};
1694 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1695 $ns = $params{parent} . $ns;
1696 inject(%params, parent => $ns) unless $ns eq '::main::';
1697 *{$ns . $params{name}} = $params{call}
1698 if exists ${$ns}{$params{name}} &&
1699 \&{${$ns}{$params{name}}} == $params{old};
1705 sub pagespec_merge ($$) { #{{{
1709 return $a if $a eq $b;
1711 # Support for old-style GlobLists.
1712 if (is_globlist($a)) {
1713 $a=globlist_to_pagespec($a);
1715 if (is_globlist($b)) {
1716 $b=globlist_to_pagespec($b);
1719 return "($a) or ($b)";
1722 sub pagespec_translate ($) { #{{{
1725 # Support for old-style GlobLists.
1726 if (is_globlist($spec)) {
1727 $spec=globlist_to_pagespec($spec);
1730 # Convert spec to perl code.
1733 \s* # ignore whitespace
1734 ( # 1: match a single word
1741 \w+\([^\)]*\) # command(params)
1743 [^\s()]+ # any other text
1745 \s* # ignore whitespace
1748 if (lc $word eq 'and') {
1751 elsif (lc $word eq 'or') {
1754 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1757 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1758 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1759 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1766 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1770 if (! length $code) {
1775 return eval 'sub { my $page=shift; '.$code.' }';
1778 sub pagespec_match ($$;@) { #{{{
1783 # Backwards compatability with old calling convention.
1785 unshift @params, 'location';
1788 my $sub=pagespec_translate($spec);
1789 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1790 return $sub->($page, @params);
1793 sub pagespec_valid ($) { #{{{
1796 my $sub=pagespec_translate($spec);
1800 sub glob2re ($) { #{{{
1801 my $re=quotemeta(shift);
1807 package IkiWiki::FailReason;
1810 '""' => sub { ${$_[0]} },
1812 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1819 return bless \$value, $class;
1822 package IkiWiki::SuccessReason;
1825 '""' => sub { ${$_[0]} },
1827 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1834 return bless \$value, $class;
1837 package IkiWiki::PageSpec;
1839 sub match_glob ($$;@) { #{{{
1844 my $from=exists $params{location} ? $params{location} : '';
1847 if ($glob =~ m!^\./!) {
1848 $from=~s#/?[^/]+$##;
1850 $glob="$from/$glob" if length $from;
1853 my $regexp=IkiWiki::glob2re($glob);
1854 if ($page=~/^$regexp$/i) {
1855 if (! IkiWiki::isinternal($page) || $params{internal}) {
1856 return IkiWiki::SuccessReason->new("$glob matches $page");
1859 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1863 return IkiWiki::FailReason->new("$glob does not match $page");
1867 sub match_internal ($$;@) { #{{{
1868 return match_glob($_[0], $_[1], @_, internal => 1)
1871 sub match_link ($$;@) { #{{{
1876 my $from=exists $params{location} ? $params{location} : '';
1879 if ($link =~ m!^\.! && defined $from) {
1880 $from=~s#/?[^/]+$##;
1882 $link="$from/$link" if length $from;
1885 my $links = $IkiWiki::links{$page};
1886 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1887 my $bestlink = IkiWiki::bestlink($from, $link);
1888 foreach my $p (@{$links}) {
1889 if (length $bestlink) {
1890 return IkiWiki::SuccessReason->new("$page links to $link")
1891 if $bestlink eq IkiWiki::bestlink($page, $p);
1894 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1895 if match_glob($p, $link, %params);
1898 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1899 if match_glob($p, $link, %params);
1902 return IkiWiki::FailReason->new("$page does not link to $link");
1905 sub match_backlink ($$;@) { #{{{
1906 return match_link($_[1], $_[0], @_);
1909 sub match_created_before ($$;@) { #{{{
1913 if (exists $IkiWiki::pagectime{$testpage}) {
1914 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1915 return IkiWiki::SuccessReason->new("$page created before $testpage");
1918 return IkiWiki::FailReason->new("$page not created before $testpage");
1922 return IkiWiki::FailReason->new("$testpage has no ctime");
1926 sub match_created_after ($$;@) { #{{{
1930 if (exists $IkiWiki::pagectime{$testpage}) {
1931 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1932 return IkiWiki::SuccessReason->new("$page created after $testpage");
1935 return IkiWiki::FailReason->new("$page not created after $testpage");
1939 return IkiWiki::FailReason->new("$testpage has no ctime");
1943 sub match_creation_day ($$;@) { #{{{
1944 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1945 return IkiWiki::SuccessReason->new('creation_day matched');
1948 return IkiWiki::FailReason->new('creation_day did not match');
1952 sub match_creation_month ($$;@) { #{{{
1953 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1954 return IkiWiki::SuccessReason->new('creation_month matched');
1957 return IkiWiki::FailReason->new('creation_month did not match');
1961 sub match_creation_year ($$;@) { #{{{
1962 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1963 return IkiWiki::SuccessReason->new('creation_year matched');
1966 return IkiWiki::FailReason->new('creation_year did not match');
1970 sub match_user ($$;@) { #{{{
1975 if (! exists $params{user}) {
1976 return IkiWiki::FailReason->new("no user specified");
1979 if (defined $params{user} && lc $params{user} eq lc $user) {
1980 return IkiWiki::SuccessReason->new("user is $user");
1982 elsif (! defined $params{user}) {
1983 return IkiWiki::FailReason->new("not logged in");
1986 return IkiWiki::FailReason->new("user is $params{user}, not $user");
1990 sub match_admin ($$;@) { #{{{
1995 if (! exists $params{user}) {
1996 return IkiWiki::FailReason->new("no user specified");
1999 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2000 return IkiWiki::SuccessReason->new("user is an admin");
2002 elsif (! defined $params{user}) {
2003 return IkiWiki::FailReason->new("not logged in");
2006 return IkiWiki::FailReason->new("user is not an admin");
2010 sub match_ip ($$;@) { #{{{
2015 if (! exists $params{ip}) {
2016 return IkiWiki::FailReason->new("no IP specified");
2019 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2020 return IkiWiki::SuccessReason->new("IP is $ip");
2023 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");