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
24 %config %links %pagestate %wikistate %renderedfiles
25 %pagesources %destsources);
26 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
27 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
28 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
33 memoize("pagespec_translate");
34 memoize("file_pruned");
36 sub getsetup () { #{{{
40 description => "name of the wiki",
47 example => 'me@example.com',
48 description => "contact email for wiki",
55 description => "users who are wiki admins",
62 description => "users who are banned from the wiki",
69 example => "$ENV{HOME}/wiki",
70 description => "where the source of the wiki is located",
77 example => "/var/www/wiki",
78 description => "where to build the wiki",
85 example => "http://example.com/wiki",
86 description => "base url to the wiki",
93 example => "http://example.com/wiki/ikiwiki.cgi",
94 description => "url to the ikiwiki.cgi",
101 example => "/var/www/wiki/ikiwiki.cgi",
102 description => "cgi wrapper to generate",
109 description => "mode for cgi_wrapper (can safely be made suid)",
116 description => "rcs backend to use",
117 safe => 0, # don't allow overriding
122 default => [qw{mdwn link inline htmlscrubber passwordauth
123 openid signinedit lockedit conditional
124 recentchanges parentlinks editpage}],
125 description => "plugins to enable by default",
132 description => "plugins to add to the default configuration",
139 description => "plugins to disable",
145 default => "$installdir/share/ikiwiki/templates",
146 description => "location of template files",
153 default => "$installdir/share/ikiwiki/basewiki",
154 description => "base wiki source location",
162 description => "wrappers to generate",
169 description => "additional underlays to use",
176 description => "display verbose messages when building?",
183 description => "log to syslog?",
190 description => "create output files named page/index.html?",
191 safe => 0, # changing requires manual transition
194 prefix_directives => {
197 description => "use '!'-prefixed preprocessor directives?",
198 safe => 0, # changing requires manual transition
204 description => "use page/index.mdwn source files",
211 description => "enable Discussion pages?",
218 description => "only send cookies over SSL connections?",
226 description => "extension to use for new pages",
227 safe => 0, # not sanitized
233 description => "extension to use for html files",
234 safe => 0, # not sanitized
240 description => "strftime format string to display date",
248 example => "en_US.UTF-8",
249 description => "UTF-8 locale to use",
258 description => "put user pages below specified page",
265 description => "how many backlinks to show before hiding excess (0 to show all)",
272 description => "attempt to hardlink source files? (optimisation for large files)",
274 safe => 0, # paranoia
281 description => "force ikiwiki to use a particular umask",
283 safe => 0, # paranoia
289 example => "$ENV{HOME}/.ikiwiki/",
290 description => "extra library and plugin directory",
292 safe => 0, # directory
298 description => "environment variables",
299 safe => 0, # paranoia
306 description => "regexp of source files to ignore",
311 wiki_file_prune_regexps => {
313 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
314 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
315 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
318 description => "regexps of source files to ignore",
324 description => "specifies the characters that are allowed in source filenames",
325 default => "-[:alnum:]+/.:_",
329 wiki_file_regexp => {
331 description => "regexp of legal source files",
335 web_commit_regexp => {
337 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
338 description => "regexp to parse web commits from logs",
345 description => "run as a cgi",
349 cgi_disable_uploads => {
352 description => "whether CGI should accept file uploads",
359 description => "run as a post-commit hook",
366 description => "running in rebuild mode",
373 description => "running in setup mode",
380 description => "running in refresh mode",
387 description => "running in getctime mode",
394 description => "running in w3mmode",
401 description => "path to setup file",
405 allow_symlinks_before_srcdir => {
408 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
414 sub defaultconfig () { #{{{
417 foreach my $key (keys %s) {
418 push @ret, $key, $s{$key}->{default};
424 sub checkconfig () { #{{{
425 # locale stuff; avoid LC_ALL since it overrides everything
426 if (defined $ENV{LC_ALL}) {
427 $ENV{LANG} = $ENV{LC_ALL};
430 if (defined $config{locale}) {
431 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
432 $ENV{LANG}=$config{locale};
437 if (! defined $config{wiki_file_regexp}) {
438 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
441 if (ref $config{ENV} eq 'HASH') {
442 foreach my $val (keys %{$config{ENV}}) {
443 $ENV{$val}=$config{ENV}{$val};
447 if ($config{w3mmode}) {
448 eval q{use Cwd q{abs_path}};
450 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
451 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
452 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
453 unless $config{cgiurl} =~ m!file:///!;
454 $config{url}="file://".$config{destdir};
457 if ($config{cgi} && ! length $config{url}) {
458 error(gettext("Must specify url to wiki with --url when using --cgi"));
461 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
462 unless exists $config{wikistatedir};
464 if (defined $config{umask}) {
465 umask(possibly_foolish_untaint($config{umask}));
468 run_hooks(checkconfig => sub { shift->() });
473 sub listplugins () { #{{{
476 foreach my $dir (@INC, $config{libdir}) {
477 next unless defined $dir && length $dir;
478 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
479 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
483 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
484 next unless defined $dir && length $dir;
485 foreach my $file (glob("$dir/plugins/*")) {
486 $ret{basename($file)}=1 if -x $file;
493 sub loadplugins () { #{{{
494 if (defined $config{libdir} && length $config{libdir}) {
495 unshift @INC, possibly_foolish_untaint($config{libdir});
498 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
503 if (exists $IkiWiki::hooks{rcs}) {
504 error(gettext("cannot use multiple rcs plugins"));
506 loadplugin($config{rcs});
508 if (! exists $IkiWiki::hooks{rcs}) {
512 run_hooks(getopt => sub { shift->() });
513 if (grep /^-/, @ARGV) {
514 print STDERR "Unknown option: $_\n"
515 foreach grep /^-/, @ARGV;
522 sub loadplugin ($) { #{{{
525 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
527 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
528 "$installdir/lib/ikiwiki") {
529 if (defined $dir && -x "$dir/plugins/$plugin") {
530 eval { require IkiWiki::Plugin::external };
533 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
535 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
536 $loaded_plugins{$plugin}=1;
541 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
544 error("Failed to load plugin $mod: $@");
546 $loaded_plugins{$plugin}=1;
550 sub error ($;$) { #{{{
553 log_message('err' => $message) if $config{syslog};
554 if (defined $cleaner) {
561 return unless $config{verbose};
562 return log_message(debug => @_);
566 sub log_message ($$) { #{{{
569 if ($config{syslog}) {
572 Sys::Syslog::setlogsock('unix');
573 Sys::Syslog::openlog('ikiwiki', '', 'user');
577 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
580 elsif (! $config{cgi}) {
584 return print STDERR "@_\n";
588 sub possibly_foolish_untaint ($) { #{{{
590 my ($untainted)=$tainted=~/(.*)/s;
594 sub basename ($) { #{{{
601 sub dirname ($) { #{{{
608 sub pagetype ($) { #{{{
611 if ($page =~ /\.([^.]+)$/) {
612 return $1 if exists $hooks{htmlize}{$1};
617 sub isinternal ($) { #{{{
619 return exists $pagesources{$page} &&
620 $pagesources{$page} =~ /\._([^.]+)$/;
623 sub pagename ($) { #{{{
626 my $type=pagetype($file);
628 $page=~s/\Q.$type\E*$// if defined $type && !$hooks{htmlize}{$type}{keepextension};
629 if ($config{indexpages} && $page=~/(.*)\/index$/) {
635 sub newpagefile ($$) { #{{{
639 if (! $config{indexpages} || $page eq 'index') {
640 return $page.".".$type;
643 return $page."/index.".$type;
647 sub targetpage ($$) { #{{{
651 if (! $config{usedirs} || $page eq 'index') {
652 return $page.".".$ext;
655 return $page."/index.".$ext;
659 sub htmlpage ($) { #{{{
662 return targetpage($page, $config{htmlext});
665 sub srcfile_stat { #{{{
669 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
670 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
671 return "$dir/$file", stat(_) if -e "$dir/$file";
673 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
677 sub srcfile ($;$) { #{{{
678 return (srcfile_stat(@_))[0];
681 sub add_underlay ($) { #{{{
685 $dir="$config{underlaydir}/../$dir";
688 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
689 unshift @{$config{underlaydirs}}, $dir;
695 sub readfile ($;$$) { #{{{
701 error("cannot read a symlink ($file)");
705 open (my $in, "<", $file) || error("failed to read $file: $!");
706 binmode($in) if ($binary);
707 return \*$in if $wantfd;
709 close $in || error("failed to read $file: $!");
713 sub prep_writefile ($$) { #{{{
718 while (length $test) {
719 if (-l "$destdir/$test") {
720 error("cannot write to a symlink ($test)");
722 $test=dirname($test);
725 my $dir=dirname("$destdir/$file");
728 foreach my $s (split(m!/+!, $dir)) {
731 mkdir($d) || error("failed to create directory $d: $!");
739 sub writefile ($$$;$$) { #{{{
740 my $file=shift; # can include subdirs
741 my $destdir=shift; # directory to put file in
746 prep_writefile($file, $destdir);
748 my $newfile="$destdir/$file.ikiwiki-new";
750 error("cannot write to a symlink ($newfile)");
753 my $cleanup = sub { unlink($newfile) };
754 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
755 binmode($out) if ($binary);
757 $writer->(\*$out, $cleanup);
760 print $out $content or error("failed writing to $newfile: $!", $cleanup);
762 close $out || error("failed saving $newfile: $!", $cleanup);
763 rename($newfile, "$destdir/$file") ||
764 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
770 sub will_render ($$;$) { #{{{
775 # Important security check.
776 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
777 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
778 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
781 if (! $clear || $cleared{$page}) {
782 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
785 foreach my $old (@{$renderedfiles{$page}}) {
786 delete $destsources{$old};
788 $renderedfiles{$page}=[$dest];
791 $destsources{$dest}=$page;
796 sub bestlink ($$) { #{{{
801 if ($link=~s/^\/+//) {
809 $l.="/" if length $l;
812 if (exists $links{$l}) {
815 elsif (exists $pagecase{lc $l}) {
816 return $pagecase{lc $l};
818 } while $cwd=~s{/?[^/]+$}{};
820 if (length $config{userdir}) {
821 my $l = "$config{userdir}/".lc($link);
822 if (exists $links{$l}) {
825 elsif (exists $pagecase{lc $l}) {
826 return $pagecase{lc $l};
830 #print STDERR "warning: page $page, broken link: $link\n";
834 sub isinlinableimage ($) { #{{{
837 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
840 sub pagetitle ($;$) { #{{{
845 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
848 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
854 sub titlepage ($) { #{{{
856 # support use w/o %config set
857 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
858 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
862 sub linkpage ($) { #{{{
864 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
865 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
869 sub cgiurl (@) { #{{{
872 return $config{cgiurl}."?".
873 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
876 sub baseurl (;$) { #{{{
879 return "$config{url}/" if ! defined $page;
881 $page=htmlpage($page);
883 $page=~s/[^\/]+\//..\//g;
887 sub abs2rel ($$) { #{{{
888 # Work around very innefficient behavior in File::Spec if abs2rel
889 # is passed two relative paths. It's much faster if paths are
890 # absolute! (Debian bug #376658; fixed in debian unstable now)
895 my $ret=File::Spec->abs2rel($path, $base);
896 $ret=~s/^// if defined $ret;
900 sub displaytime ($;$) { #{{{
903 if (exists $hooks{displaytime}) {
905 run_hooks(displaytime => sub {
906 $ret=shift->($time, $format)
911 return formattime($time, $format);
915 sub formattime ($;$) { #{{{
916 # Plugins can override this function to mark up the time for
920 if (! defined $format) {
921 $format=$config{timeformat};
924 # strftime doesn't know about encodings, so make sure
925 # its output is properly treated as utf8
926 return decode_utf8(POSIX::strftime($format, localtime($time)));
929 sub beautify_urlpath ($) { #{{{
932 if ($config{usedirs}) {
933 $url =~ s!/index.$config{htmlext}$!/!;
936 # Ensure url is not an empty link, and
937 # if it's relative, make that explicit to avoid colon confusion.
945 sub urlto ($$;$) { #{{{
951 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
954 if (! $destsources{$to}) {
959 return $config{url}.beautify_urlpath("/".$to);
962 my $link = abs2rel($to, dirname(htmlpage($from)));
964 return beautify_urlpath($link);
967 sub htmllink ($$$;@) { #{{{
968 my $lpage=shift; # the page doing the linking
969 my $page=shift; # the page that will contain the link (different for inline)
976 if (! $opts{forcesubpage}) {
977 $bestlink=bestlink($lpage, $link);
980 $bestlink="$lpage/".lc($link);
984 if (defined $opts{linktext}) {
985 $linktext=$opts{linktext};
988 $linktext=pagetitle(basename($link));
991 return "<span class=\"selflink\">$linktext</span>"
992 if length $bestlink && $page eq $bestlink &&
993 ! defined $opts{anchor};
995 if (! $destsources{$bestlink}) {
996 $bestlink=htmlpage($bestlink);
998 if (! $destsources{$bestlink}) {
999 return $linktext unless length $config{cgiurl};
1000 return "<span class=\"createlink\"><a href=\"".
1006 "\" rel=\"nofollow\">?</a>$linktext</span>"
1010 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1011 $bestlink=beautify_urlpath($bestlink);
1013 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1014 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1017 if (defined $opts{anchor}) {
1018 $bestlink.="#".$opts{anchor};
1022 if (defined $opts{rel}) {
1023 push @attrs, ' rel="'.$opts{rel}.'"';
1025 if (defined $opts{class}) {
1026 push @attrs, ' class="'.$opts{class}.'"';
1029 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1032 sub userlink ($) { #{{{
1035 my $oiduser=eval { openiduser($user) };
1036 if (defined $oiduser) {
1037 return "<a href=\"$user\">$oiduser</a>";
1040 eval q{use CGI 'escapeHTML'};
1043 return htmllink("", "", escapeHTML(
1044 length $config{userdir} ? $config{userdir}."/".$user : $user
1045 ), noimageinline => 1);
1049 sub htmlize ($$$$) { #{{{
1055 my $oneline = $content !~ /\n/;
1057 if (exists $hooks{htmlize}{$type}) {
1058 $content=$hooks{htmlize}{$type}{call}->(
1060 content => $content,
1064 error("htmlization of $type not supported");
1067 run_hooks(sanitize => sub {
1070 destpage => $destpage,
1071 content => $content,
1076 # hack to get rid of enclosing junk added by markdown
1077 # and other htmlizers
1078 $content=~s/^<p>//i;
1079 $content=~s/<\/p>$//i;
1086 sub linkify ($$$) { #{{{
1091 run_hooks(linkify => sub {
1094 destpage => $destpage,
1095 content => $content,
1103 our $preprocess_preview=0;
1104 sub preprocess ($$$;$$) { #{{{
1105 my $page=shift; # the page the data comes from
1106 my $destpage=shift; # the page the data will appear in (different for inline)
1111 # Using local because it needs to be set within any nested calls
1113 local $preprocess_preview=$preview if defined $preview;
1120 $params="" if ! defined $params;
1122 if (length $escape) {
1123 return "[[$prefix$command $params]]";
1125 elsif (exists $hooks{preprocess}{$command}) {
1126 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1127 # Note: preserve order of params, some plugins may
1128 # consider it significant.
1130 while ($params =~ m{
1131 (?:([-\w]+)=)? # 1: named parameter key?
1133 """(.*?)""" # 2: triple-quoted value
1135 "([^"]+)" # 3: single-quoted value
1137 (\S+) # 4: unquoted value
1139 (?:\s+|$) # delimiter to next param
1149 elsif (defined $3) {
1152 elsif (defined $4) {
1157 push @params, $key, $val;
1160 push @params, $val, '';
1163 if ($preprocessing{$page}++ > 3) {
1164 # Avoid loops of preprocessed pages preprocessing
1165 # other pages that preprocess them, etc.
1166 return "[[!$command <span class=\"error\">".
1167 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1168 $page, $preprocessing{$page}).
1174 $hooks{preprocess}{$command}{call}->(
1177 destpage => $destpage,
1178 preview => $preprocess_preview,
1183 $ret="[[!$command <span class=\"error\">".
1184 gettext("Error").": $@"."</span>]]";
1188 # use void context during scan pass
1190 $hooks{preprocess}{$command}{call}->(
1193 destpage => $destpage,
1194 preview => $preprocess_preview,
1199 $preprocessing{$page}--;
1203 return "[[$prefix$command $params]]";
1208 if ($config{prefix_directives}) {
1211 \[\[(!) # directive open; 2: prefix
1212 ([-\w]+) # 3: command
1213 ( # 4: the parameters..
1214 \s+ # Must have space if parameters present
1216 (?:[-\w]+=)? # named parameter key?
1218 """.*?""" # triple-quoted value
1220 "[^"]+" # single-quoted value
1222 [^\s\]]+ # unquoted value
1224 \s* # whitespace or end
1227 *)? # 0 or more parameters
1228 \]\] # directive closed
1234 \[\[(!?) # directive open; 2: optional prefix
1235 ([-\w]+) # 3: command
1237 ( # 4: the parameters..
1239 (?:[-\w]+=)? # named parameter key?
1241 """.*?""" # triple-quoted value
1243 "[^"]+" # single-quoted value
1245 [^\s\]]+ # unquoted value
1247 \s* # whitespace or end
1250 *) # 0 or more parameters
1251 \]\] # directive closed
1255 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1259 sub filter ($$$) { #{{{
1264 run_hooks(filter => sub {
1265 $content=shift->(page => $page, destpage => $destpage,
1266 content => $content);
1272 sub indexlink () { #{{{
1273 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1278 sub lockwiki (;$) { #{{{
1279 my $wait=@_ ? shift : 1;
1280 # Take an exclusive lock on the wiki to prevent multiple concurrent
1281 # run issues. The lock will be dropped on program exit.
1282 if (! -d $config{wikistatedir}) {
1283 mkdir($config{wikistatedir});
1285 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1286 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1287 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1289 debug("wiki seems to be locked, waiting for lock");
1290 my $wait=600; # arbitrary, but don't hang forever to
1291 # prevent process pileup
1293 return if flock($wikilock, 2 | 4);
1296 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1305 sub unlockwiki () { #{{{
1306 return close($wikilock) if $wikilock;
1312 sub commit_hook_enabled () { #{{{
1313 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1314 error("cannot write to $config{wikistatedir}/commitlock: $!");
1315 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1316 close($commitlock) || error("failed closing commitlock: $!");
1319 close($commitlock) || error("failed closing commitlock: $!");
1323 sub disable_commit_hook () { #{{{
1324 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1325 error("cannot write to $config{wikistatedir}/commitlock: $!");
1326 if (! flock($commitlock, 2)) { # LOCK_EX
1327 error("failed to get commit lock");
1332 sub enable_commit_hook () { #{{{
1333 return close($commitlock) if $commitlock;
1337 sub loadindex () { #{{{
1338 %oldrenderedfiles=%pagectime=();
1339 if (! $config{rebuild}) {
1340 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1341 %destsources=%renderedfiles=%pagecase=%pagestate=();
1344 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1345 if (-e "$config{wikistatedir}/index") {
1346 system("ikiwiki-transition", "indexdb", $config{srcdir});
1347 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1354 my $index=Storable::fd_retrieve($in);
1355 if (! defined $index) {
1360 if (exists $index->{version} && ! ref $index->{version}) {
1361 $pages=$index->{page};
1362 %wikistate=%{$index->{state}};
1369 foreach my $src (keys %$pages) {
1370 my $d=$pages->{$src};
1371 my $page=pagename($src);
1372 $pagectime{$page}=$d->{ctime};
1373 if (! $config{rebuild}) {
1374 $pagesources{$page}=$src;
1375 $pagemtime{$page}=$d->{mtime};
1376 $renderedfiles{$page}=$d->{dest};
1377 if (exists $d->{links} && ref $d->{links}) {
1378 $links{$page}=$d->{links};
1379 $oldlinks{$page}=[@{$d->{links}}];
1381 if (exists $d->{depends}) {
1382 $depends{$page}=$d->{depends};
1384 if (exists $d->{state}) {
1385 $pagestate{$page}=$d->{state};
1388 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1390 foreach my $page (keys %pagesources) {
1391 $pagecase{lc $page}=$page;
1393 foreach my $page (keys %renderedfiles) {
1394 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1399 sub saveindex () { #{{{
1400 run_hooks(savestate => sub { shift->() });
1403 foreach my $type (keys %hooks) {
1404 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1406 my @hookids=keys %hookids;
1408 if (! -d $config{wikistatedir}) {
1409 mkdir($config{wikistatedir});
1411 my $newfile="$config{wikistatedir}/indexdb.new";
1412 my $cleanup = sub { unlink($newfile) };
1413 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1416 foreach my $page (keys %pagemtime) {
1417 next unless $pagemtime{$page};
1418 my $src=$pagesources{$page};
1420 $index{page}{$src}={
1421 ctime => $pagectime{$page},
1422 mtime => $pagemtime{$page},
1423 dest => $renderedfiles{$page},
1424 links => $links{$page},
1427 if (exists $depends{$page}) {
1428 $index{page}{$src}{depends} = $depends{$page};
1431 if (exists $pagestate{$page}) {
1432 foreach my $id (@hookids) {
1433 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1434 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1441 foreach my $id (@hookids) {
1442 foreach my $key (keys %{$wikistate{$id}}) {
1443 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1447 $index{version}="3";
1448 my $ret=Storable::nstore_fd(\%index, $out);
1449 return if ! defined $ret || ! $ret;
1450 close $out || error("failed saving to $newfile: $!", $cleanup);
1451 rename($newfile, "$config{wikistatedir}/indexdb") ||
1452 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1457 sub template_file ($) { #{{{
1460 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1461 return "$dir/$template" if -e "$dir/$template";
1466 sub template_params (@) { #{{{
1467 my $filename=template_file(shift);
1469 if (! defined $filename) {
1470 return if wantarray;
1476 my $text_ref = shift;
1477 ${$text_ref} = decode_utf8(${$text_ref});
1479 filename => $filename,
1480 loop_context_vars => 1,
1481 die_on_bad_params => 0,
1484 return wantarray ? @ret : {@ret};
1487 sub template ($;@) { #{{{
1488 require HTML::Template;
1489 return HTML::Template->new(template_params(@_));
1492 sub misctemplate ($$;@) { #{{{
1496 my $template=template("misc.tmpl");
1499 indexlink => indexlink(),
1500 wikiname => $config{wikiname},
1501 pagebody => $pagebody,
1502 baseurl => baseurl(),
1505 run_hooks(pagetemplate => sub {
1506 shift->(page => "", destpage => "", template => $template);
1508 return $template->output;
1511 sub hook (@) { # {{{
1514 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1515 error 'hook requires type, call, and id parameters';
1518 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1520 $hooks{$param{type}}{$param{id}}=\%param;
1524 sub run_hooks ($$) { # {{{
1525 # Calls the given sub for each hook of the given type,
1526 # passing it the hook function to call.
1530 if (exists $hooks{$type}) {
1532 foreach my $id (keys %{$hooks{$type}}) {
1533 if ($hooks{$type}{$id}{last}) {
1534 push @deferred, $id;
1537 $sub->($hooks{$type}{$id}{call});
1539 foreach my $id (@deferred) {
1540 $sub->($hooks{$type}{$id}{call});
1547 sub rcs_update () { #{{{
1548 $hooks{rcs}{rcs_update}{call}->(@_);
1551 sub rcs_prepedit ($) { #{{{
1552 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1555 sub rcs_commit ($$$;$$) { #{{{
1556 $hooks{rcs}{rcs_commit}{call}->(@_);
1559 sub rcs_commit_staged ($$$) { #{{{
1560 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1563 sub rcs_add ($) { #{{{
1564 $hooks{rcs}{rcs_add}{call}->(@_);
1567 sub rcs_remove ($) { #{{{
1568 $hooks{rcs}{rcs_remove}{call}->(@_);
1571 sub rcs_rename ($$) { #{{{
1572 $hooks{rcs}{rcs_rename}{call}->(@_);
1575 sub rcs_recentchanges ($) { #{{{
1576 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1579 sub rcs_diff ($) { #{{{
1580 $hooks{rcs}{rcs_diff}{call}->(@_);
1583 sub rcs_getctime ($) { #{{{
1584 $hooks{rcs}{rcs_getctime}{call}->(@_);
1587 sub globlist_to_pagespec ($) { #{{{
1588 my @globlist=split(' ', shift);
1591 foreach my $glob (@globlist) {
1592 if ($glob=~/^!(.*)/) {
1600 my $spec=join(' or ', @spec);
1602 my $skip=join(' and ', @skip);
1604 $spec="$skip and ($spec)";
1613 sub is_globlist ($) { #{{{
1615 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1618 sub safequote ($) { #{{{
1624 sub add_depends ($$) { #{{{
1628 return unless pagespec_valid($pagespec);
1630 if (! exists $depends{$page}) {
1631 $depends{$page}=$pagespec;
1634 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1640 sub file_pruned ($$) { #{{{
1642 my $file=File::Spec->canonpath(shift);
1643 my $base=File::Spec->canonpath(shift);
1644 $file =~ s#^\Q$base\E/+##;
1646 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1647 return $file =~ m/$regexp/ && $file ne $base;
1651 # Only use gettext in the rare cases it's needed.
1652 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1653 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1654 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1655 if (! $gettext_obj) {
1656 $gettext_obj=eval q{
1657 use Locale::gettext q{textdomain};
1658 Locale::gettext->domain('ikiwiki')
1666 return $gettext_obj->get(shift);
1673 sub yesno ($) { #{{{
1676 return (defined $val && lc($val) eq gettext("yes"));
1679 sub pagespec_merge ($$) { #{{{
1683 return $a if $a eq $b;
1685 # Support for old-style GlobLists.
1686 if (is_globlist($a)) {
1687 $a=globlist_to_pagespec($a);
1689 if (is_globlist($b)) {
1690 $b=globlist_to_pagespec($b);
1693 return "($a) or ($b)";
1696 sub pagespec_translate ($) { #{{{
1699 # Support for old-style GlobLists.
1700 if (is_globlist($spec)) {
1701 $spec=globlist_to_pagespec($spec);
1704 # Convert spec to perl code.
1707 \s* # ignore whitespace
1708 ( # 1: match a single word
1715 \w+\([^\)]*\) # command(params)
1717 [^\s()]+ # any other text
1719 \s* # ignore whitespace
1722 if (lc $word eq 'and') {
1725 elsif (lc $word eq 'or') {
1728 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1731 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1732 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1733 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1740 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1744 if (! length $code) {
1749 return eval 'sub { my $page=shift; '.$code.' }';
1752 sub pagespec_match ($$;@) { #{{{
1757 # Backwards compatability with old calling convention.
1759 unshift @params, 'location';
1762 my $sub=pagespec_translate($spec);
1763 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1764 return $sub->($page, @params);
1767 sub pagespec_valid ($) { #{{{
1770 my $sub=pagespec_translate($spec);
1774 sub glob2re ($) { #{{{
1775 my $re=quotemeta(shift);
1781 package IkiWiki::FailReason;
1784 '""' => sub { ${$_[0]} },
1786 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1793 return bless \$value, $class;
1796 package IkiWiki::SuccessReason;
1799 '""' => sub { ${$_[0]} },
1801 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1808 return bless \$value, $class;
1811 package IkiWiki::PageSpec;
1813 sub match_glob ($$;@) { #{{{
1818 my $from=exists $params{location} ? $params{location} : '';
1821 if ($glob =~ m!^\./!) {
1822 $from=~s#/?[^/]+$##;
1824 $glob="$from/$glob" if length $from;
1827 my $regexp=IkiWiki::glob2re($glob);
1828 if ($page=~/^$regexp$/i) {
1829 if (! IkiWiki::isinternal($page) || $params{internal}) {
1830 return IkiWiki::SuccessReason->new("$glob matches $page");
1833 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1837 return IkiWiki::FailReason->new("$glob does not match $page");
1841 sub match_internal ($$;@) { #{{{
1842 return match_glob($_[0], $_[1], @_, internal => 1)
1845 sub match_link ($$;@) { #{{{
1850 my $from=exists $params{location} ? $params{location} : '';
1853 if ($link =~ m!^\.! && defined $from) {
1854 $from=~s#/?[^/]+$##;
1856 $link="$from/$link" if length $from;
1859 my $links = $IkiWiki::links{$page};
1860 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1861 my $bestlink = IkiWiki::bestlink($from, $link);
1862 foreach my $p (@{$links}) {
1863 if (length $bestlink) {
1864 return IkiWiki::SuccessReason->new("$page links to $link")
1865 if $bestlink eq IkiWiki::bestlink($page, $p);
1868 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1869 if match_glob($p, $link, %params);
1872 return IkiWiki::FailReason->new("$page does not link to $link");
1875 sub match_backlink ($$;@) { #{{{
1876 return match_link($_[1], $_[0], @_);
1879 sub match_created_before ($$;@) { #{{{
1883 if (exists $IkiWiki::pagectime{$testpage}) {
1884 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1885 return IkiWiki::SuccessReason->new("$page created before $testpage");
1888 return IkiWiki::FailReason->new("$page not created before $testpage");
1892 return IkiWiki::FailReason->new("$testpage has no ctime");
1896 sub match_created_after ($$;@) { #{{{
1900 if (exists $IkiWiki::pagectime{$testpage}) {
1901 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1902 return IkiWiki::SuccessReason->new("$page created after $testpage");
1905 return IkiWiki::FailReason->new("$page not created after $testpage");
1909 return IkiWiki::FailReason->new("$testpage has no ctime");
1913 sub match_creation_day ($$;@) { #{{{
1914 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1915 return IkiWiki::SuccessReason->new('creation_day matched');
1918 return IkiWiki::FailReason->new('creation_day did not match');
1922 sub match_creation_month ($$;@) { #{{{
1923 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1924 return IkiWiki::SuccessReason->new('creation_month matched');
1927 return IkiWiki::FailReason->new('creation_month did not match');
1931 sub match_creation_year ($$;@) { #{{{
1932 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1933 return IkiWiki::SuccessReason->new('creation_year matched');
1936 return IkiWiki::FailReason->new('creation_year did not match');
1940 sub match_user ($$;@) { #{{{
1945 if (! exists $params{user}) {
1946 return IkiWiki::FailReason->new("no user specified");
1949 if (defined $params{user} && lc $params{user} eq lc $user) {
1950 return IkiWiki::SuccessReason->new("user is $user");
1952 elsif (! defined $params{user}) {
1953 return IkiWiki::FailReason->new("not logged in");
1956 return IkiWiki::FailReason->new("user is $params{user}, not $user");
1960 sub match_admin ($$;@) { #{{{
1965 if (! exists $params{user}) {
1966 return IkiWiki::FailReason->new("no user specified");
1969 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
1970 return IkiWiki::SuccessReason->new("user is an admin");
1972 elsif (! defined $params{user}) {
1973 return IkiWiki::FailReason->new("not logged in");
1976 return IkiWiki::FailReason->new("user is not an admin");
1980 sub match_ip ($$;@) { #{{{
1985 if (! exists $params{ip}) {
1986 return IkiWiki::FailReason->new("no IP specified");
1989 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
1990 return IkiWiki::SuccessReason->new("IP is $ip");
1993 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");