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 close $in || error("failed to read $file: $!");
728 sub prep_writefile ($$) { #{{{
733 while (length $test) {
734 if (-l "$destdir/$test") {
735 error("cannot write to a symlink ($test)");
737 $test=dirname($test);
740 my $dir=dirname("$destdir/$file");
743 foreach my $s (split(m!/+!, $dir)) {
746 mkdir($d) || error("failed to create directory $d: $!");
754 sub writefile ($$$;$$) { #{{{
755 my $file=shift; # can include subdirs
756 my $destdir=shift; # directory to put file in
761 prep_writefile($file, $destdir);
763 my $newfile="$destdir/$file.ikiwiki-new";
765 error("cannot write to a symlink ($newfile)");
768 my $cleanup = sub { unlink($newfile) };
769 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
770 binmode($out) if ($binary);
772 $writer->(\*$out, $cleanup);
775 print $out $content or error("failed writing to $newfile: $!", $cleanup);
777 close $out || error("failed saving $newfile: $!", $cleanup);
778 rename($newfile, "$destdir/$file") ||
779 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
785 sub will_render ($$;$) { #{{{
790 # Important security check.
791 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
792 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
793 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
796 if (! $clear || $cleared{$page}) {
797 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
800 foreach my $old (@{$renderedfiles{$page}}) {
801 delete $destsources{$old};
803 $renderedfiles{$page}=[$dest];
806 $destsources{$dest}=$page;
811 sub bestlink ($$) { #{{{
816 if ($link=~s/^\/+//) {
824 $l.="/" if length $l;
827 if (exists $links{$l}) {
830 elsif (exists $pagecase{lc $l}) {
831 return $pagecase{lc $l};
833 } while $cwd=~s{/?[^/]+$}{};
835 if (length $config{userdir}) {
836 my $l = "$config{userdir}/".lc($link);
837 if (exists $links{$l}) {
840 elsif (exists $pagecase{lc $l}) {
841 return $pagecase{lc $l};
845 #print STDERR "warning: page $page, broken link: $link\n";
849 sub isinlinableimage ($) { #{{{
852 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
855 sub pagetitle ($;$) { #{{{
860 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
863 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
869 sub titlepage ($) { #{{{
871 # support use w/o %config set
872 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
873 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
877 sub linkpage ($) { #{{{
879 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
880 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
884 sub cgiurl (@) { #{{{
887 return $config{cgiurl}."?".
888 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
891 sub baseurl (;$) { #{{{
894 return "$config{url}/" if ! defined $page;
896 $page=htmlpage($page);
898 $page=~s/[^\/]+\//..\//g;
902 sub abs2rel ($$) { #{{{
903 # Work around very innefficient behavior in File::Spec if abs2rel
904 # is passed two relative paths. It's much faster if paths are
905 # absolute! (Debian bug #376658; fixed in debian unstable now)
910 my $ret=File::Spec->abs2rel($path, $base);
911 $ret=~s/^// if defined $ret;
915 sub displaytime ($;$) { #{{{
916 # Plugins can override this function to mark up the time to
918 return '<span class="date">'.formattime(@_).'</span>';
921 sub formattime ($;$) { #{{{
922 # Plugins can override this function to format the time.
925 if (! defined $format) {
926 $format=$config{timeformat};
929 # strftime doesn't know about encodings, so make sure
930 # its output is properly treated as utf8
931 return decode_utf8(POSIX::strftime($format, localtime($time)));
934 sub beautify_urlpath ($) { #{{{
937 if ($config{usedirs}) {
938 $url =~ s!/index.$config{htmlext}$!/!;
941 # Ensure url is not an empty link, and
942 # if it's relative, make that explicit to avoid colon confusion.
950 sub urlto ($$;$) { #{{{
956 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
959 if (! $destsources{$to}) {
964 return $config{url}.beautify_urlpath("/".$to);
967 my $link = abs2rel($to, dirname(htmlpage($from)));
969 return beautify_urlpath($link);
972 sub htmllink ($$$;@) { #{{{
973 my $lpage=shift; # the page doing the linking
974 my $page=shift; # the page that will contain the link (different for inline)
981 if (! $opts{forcesubpage}) {
982 $bestlink=bestlink($lpage, $link);
985 $bestlink="$lpage/".lc($link);
989 if (defined $opts{linktext}) {
990 $linktext=$opts{linktext};
993 $linktext=pagetitle(basename($link));
996 return "<span class=\"selflink\">$linktext</span>"
997 if length $bestlink && $page eq $bestlink &&
998 ! defined $opts{anchor};
1000 if (! $destsources{$bestlink}) {
1001 $bestlink=htmlpage($bestlink);
1003 if (! $destsources{$bestlink}) {
1004 return $linktext unless length $config{cgiurl};
1005 return "<span class=\"createlink\"><a href=\"".
1011 "\" rel=\"nofollow\">?</a>$linktext</span>"
1015 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1016 $bestlink=beautify_urlpath($bestlink);
1018 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1019 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1022 if (defined $opts{anchor}) {
1023 $bestlink.="#".$opts{anchor};
1027 if (defined $opts{rel}) {
1028 push @attrs, ' rel="'.$opts{rel}.'"';
1030 if (defined $opts{class}) {
1031 push @attrs, ' class="'.$opts{class}.'"';
1034 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1037 sub userlink ($) { #{{{
1040 my $oiduser=eval { openiduser($user) };
1041 if (defined $oiduser) {
1042 return "<a href=\"$user\">$oiduser</a>";
1045 eval q{use CGI 'escapeHTML'};
1048 return htmllink("", "", escapeHTML(
1049 length $config{userdir} ? $config{userdir}."/".$user : $user
1050 ), noimageinline => 1);
1054 sub htmlize ($$$$) { #{{{
1060 my $oneline = $content !~ /\n/;
1062 if (exists $hooks{htmlize}{$type}) {
1063 $content=$hooks{htmlize}{$type}{call}->(
1065 content => $content,
1069 error("htmlization of $type not supported");
1072 run_hooks(sanitize => sub {
1075 destpage => $destpage,
1076 content => $content,
1081 # hack to get rid of enclosing junk added by markdown
1082 # and other htmlizers
1083 $content=~s/^<p>//i;
1084 $content=~s/<\/p>$//i;
1091 sub linkify ($$$) { #{{{
1096 run_hooks(linkify => sub {
1099 destpage => $destpage,
1100 content => $content,
1108 our $preprocess_preview=0;
1109 sub preprocess ($$$;$$) { #{{{
1110 my $page=shift; # the page the data comes from
1111 my $destpage=shift; # the page the data will appear in (different for inline)
1116 # Using local because it needs to be set within any nested calls
1118 local $preprocess_preview=$preview if defined $preview;
1125 $params="" if ! defined $params;
1127 if (length $escape) {
1128 return "[[$prefix$command $params]]";
1130 elsif (exists $hooks{preprocess}{$command}) {
1131 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1132 # Note: preserve order of params, some plugins may
1133 # consider it significant.
1135 while ($params =~ m{
1136 (?:([-\w]+)=)? # 1: named parameter key?
1138 """(.*?)""" # 2: triple-quoted value
1140 "([^"]+)" # 3: single-quoted value
1142 (\S+) # 4: unquoted value
1144 (?:\s+|$) # delimiter to next param
1154 elsif (defined $3) {
1157 elsif (defined $4) {
1162 push @params, $key, $val;
1165 push @params, $val, '';
1168 if ($preprocessing{$page}++ > 3) {
1169 # Avoid loops of preprocessed pages preprocessing
1170 # other pages that preprocess them, etc.
1171 return "[[!$command <span class=\"error\">".
1172 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1173 $page, $preprocessing{$page}).
1179 $hooks{preprocess}{$command}{call}->(
1182 destpage => $destpage,
1183 preview => $preprocess_preview,
1188 $ret="[[!$command <span class=\"error\">".
1189 gettext("Error").": $@"."</span>]]";
1193 # use void context during scan pass
1195 $hooks{preprocess}{$command}{call}->(
1198 destpage => $destpage,
1199 preview => $preprocess_preview,
1204 $preprocessing{$page}--;
1208 return "[[$prefix$command $params]]";
1213 if ($config{prefix_directives}) {
1216 \[\[(!) # directive open; 2: prefix
1217 ([-\w]+) # 3: command
1218 ( # 4: the parameters..
1219 \s+ # Must have space if parameters present
1221 (?:[-\w]+=)? # named parameter key?
1223 """.*?""" # triple-quoted value
1225 "[^"]+" # single-quoted value
1227 [^\s\]]+ # unquoted value
1229 \s* # whitespace or end
1232 *)? # 0 or more parameters
1233 \]\] # directive closed
1239 \[\[(!?) # directive open; 2: optional prefix
1240 ([-\w]+) # 3: command
1242 ( # 4: the parameters..
1244 (?:[-\w]+=)? # named parameter key?
1246 """.*?""" # triple-quoted value
1248 "[^"]+" # single-quoted value
1250 [^\s\]]+ # unquoted value
1252 \s* # whitespace or end
1255 *) # 0 or more parameters
1256 \]\] # directive closed
1260 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1264 sub filter ($$$) { #{{{
1269 run_hooks(filter => sub {
1270 $content=shift->(page => $page, destpage => $destpage,
1271 content => $content);
1277 sub indexlink () { #{{{
1278 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1283 sub lockwiki (;$) { #{{{
1284 my $wait=@_ ? shift : 1;
1285 # Take an exclusive lock on the wiki to prevent multiple concurrent
1286 # run issues. The lock will be dropped on program exit.
1287 if (! -d $config{wikistatedir}) {
1288 mkdir($config{wikistatedir});
1290 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1291 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1292 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1294 debug("wiki seems to be locked, waiting for lock");
1295 my $wait=600; # arbitrary, but don't hang forever to
1296 # prevent process pileup
1298 return if flock($wikilock, 2 | 4);
1301 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1310 sub unlockwiki () { #{{{
1311 return close($wikilock) if $wikilock;
1317 sub commit_hook_enabled () { #{{{
1318 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1319 error("cannot write to $config{wikistatedir}/commitlock: $!");
1320 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1321 close($commitlock) || error("failed closing commitlock: $!");
1324 close($commitlock) || error("failed closing commitlock: $!");
1328 sub disable_commit_hook () { #{{{
1329 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1330 error("cannot write to $config{wikistatedir}/commitlock: $!");
1331 if (! flock($commitlock, 2)) { # LOCK_EX
1332 error("failed to get commit lock");
1337 sub enable_commit_hook () { #{{{
1338 return close($commitlock) if $commitlock;
1342 sub loadindex () { #{{{
1343 %oldrenderedfiles=%pagectime=();
1344 if (! $config{rebuild}) {
1345 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1346 %destsources=%renderedfiles=%pagecase=%pagestate=();
1349 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1350 if (-e "$config{wikistatedir}/index") {
1351 system("ikiwiki-transition", "indexdb", $config{srcdir});
1352 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1359 my $index=Storable::fd_retrieve($in);
1360 if (! defined $index) {
1365 if (exists $index->{version} && ! ref $index->{version}) {
1366 $pages=$index->{page};
1367 %wikistate=%{$index->{state}};
1374 foreach my $src (keys %$pages) {
1375 my $d=$pages->{$src};
1376 my $page=pagename($src);
1377 $pagectime{$page}=$d->{ctime};
1378 if (! $config{rebuild}) {
1379 $pagesources{$page}=$src;
1380 $pagemtime{$page}=$d->{mtime};
1381 $renderedfiles{$page}=$d->{dest};
1382 if (exists $d->{links} && ref $d->{links}) {
1383 $links{$page}=$d->{links};
1384 $oldlinks{$page}=[@{$d->{links}}];
1386 if (exists $d->{depends}) {
1387 $depends{$page}=$d->{depends};
1389 if (exists $d->{state}) {
1390 $pagestate{$page}=$d->{state};
1393 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1395 foreach my $page (keys %pagesources) {
1396 $pagecase{lc $page}=$page;
1398 foreach my $page (keys %renderedfiles) {
1399 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1404 sub saveindex () { #{{{
1405 run_hooks(savestate => sub { shift->() });
1408 foreach my $type (keys %hooks) {
1409 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1411 my @hookids=keys %hookids;
1413 if (! -d $config{wikistatedir}) {
1414 mkdir($config{wikistatedir});
1416 my $newfile="$config{wikistatedir}/indexdb.new";
1417 my $cleanup = sub { unlink($newfile) };
1418 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1421 foreach my $page (keys %pagemtime) {
1422 next unless $pagemtime{$page};
1423 my $src=$pagesources{$page};
1425 $index{page}{$src}={
1426 ctime => $pagectime{$page},
1427 mtime => $pagemtime{$page},
1428 dest => $renderedfiles{$page},
1429 links => $links{$page},
1432 if (exists $depends{$page}) {
1433 $index{page}{$src}{depends} = $depends{$page};
1436 if (exists $pagestate{$page}) {
1437 foreach my $id (@hookids) {
1438 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1439 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1446 foreach my $id (@hookids) {
1447 foreach my $key (keys %{$wikistate{$id}}) {
1448 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1452 $index{version}="3";
1453 my $ret=Storable::nstore_fd(\%index, $out);
1454 return if ! defined $ret || ! $ret;
1455 close $out || error("failed saving to $newfile: $!", $cleanup);
1456 rename($newfile, "$config{wikistatedir}/indexdb") ||
1457 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1462 sub template_file ($) { #{{{
1465 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1466 return "$dir/$template" if -e "$dir/$template";
1471 sub template_params (@) { #{{{
1472 my $filename=template_file(shift);
1474 if (! defined $filename) {
1475 return if wantarray;
1481 my $text_ref = shift;
1482 ${$text_ref} = decode_utf8(${$text_ref});
1484 filename => $filename,
1485 loop_context_vars => 1,
1486 die_on_bad_params => 0,
1489 return wantarray ? @ret : {@ret};
1492 sub template ($;@) { #{{{
1493 require HTML::Template;
1494 return HTML::Template->new(template_params(@_));
1497 sub misctemplate ($$;@) { #{{{
1501 my $template=template("misc.tmpl");
1504 indexlink => indexlink(),
1505 wikiname => $config{wikiname},
1506 pagebody => $pagebody,
1507 baseurl => baseurl(),
1510 run_hooks(pagetemplate => sub {
1511 shift->(page => "", destpage => "", template => $template);
1513 return $template->output;
1516 sub hook (@) { # {{{
1519 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1520 error 'hook requires type, call, and id parameters';
1523 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1525 $hooks{$param{type}}{$param{id}}=\%param;
1529 sub run_hooks ($$) { # {{{
1530 # Calls the given sub for each hook of the given type,
1531 # passing it the hook function to call.
1535 if (exists $hooks{$type}) {
1537 foreach my $id (keys %{$hooks{$type}}) {
1538 if ($hooks{$type}{$id}{last}) {
1539 push @deferred, $id;
1542 $sub->($hooks{$type}{$id}{call});
1544 foreach my $id (@deferred) {
1545 $sub->($hooks{$type}{$id}{call});
1552 sub rcs_update () { #{{{
1553 $hooks{rcs}{rcs_update}{call}->(@_);
1556 sub rcs_prepedit ($) { #{{{
1557 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1560 sub rcs_commit ($$$;$$) { #{{{
1561 $hooks{rcs}{rcs_commit}{call}->(@_);
1564 sub rcs_commit_staged ($$$) { #{{{
1565 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1568 sub rcs_add ($) { #{{{
1569 $hooks{rcs}{rcs_add}{call}->(@_);
1572 sub rcs_remove ($) { #{{{
1573 $hooks{rcs}{rcs_remove}{call}->(@_);
1576 sub rcs_rename ($$) { #{{{
1577 $hooks{rcs}{rcs_rename}{call}->(@_);
1580 sub rcs_recentchanges ($) { #{{{
1581 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1584 sub rcs_diff ($) { #{{{
1585 $hooks{rcs}{rcs_diff}{call}->(@_);
1588 sub rcs_getctime ($) { #{{{
1589 $hooks{rcs}{rcs_getctime}{call}->(@_);
1592 sub rcs_receive () { #{{{
1593 $hooks{rcs}{rcs_receive}{call}->();
1596 sub globlist_to_pagespec ($) { #{{{
1597 my @globlist=split(' ', shift);
1600 foreach my $glob (@globlist) {
1601 if ($glob=~/^!(.*)/) {
1609 my $spec=join(' or ', @spec);
1611 my $skip=join(' and ', @skip);
1613 $spec="$skip and ($spec)";
1622 sub is_globlist ($) { #{{{
1624 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1627 sub safequote ($) { #{{{
1633 sub add_depends ($$) { #{{{
1637 return unless pagespec_valid($pagespec);
1639 if (! exists $depends{$page}) {
1640 $depends{$page}=$pagespec;
1643 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1649 sub file_pruned ($$) { #{{{
1651 my $file=File::Spec->canonpath(shift);
1652 my $base=File::Spec->canonpath(shift);
1653 $file =~ s#^\Q$base\E/+##;
1655 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1656 return $file =~ m/$regexp/ && $file ne $base;
1660 # Only use gettext in the rare cases it's needed.
1661 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1662 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1663 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1664 if (! $gettext_obj) {
1665 $gettext_obj=eval q{
1666 use Locale::gettext q{textdomain};
1667 Locale::gettext->domain('ikiwiki')
1675 return $gettext_obj->get(shift);
1682 sub yesno ($) { #{{{
1685 return (defined $val && lc($val) eq gettext("yes"));
1689 # Injects a new function into the symbol table to replace an
1690 # exported function.
1693 # This is deep ugly perl foo, beware.
1696 if (! defined $params{parent}) {
1697 $params{parent}='::';
1698 $params{old}=\&{$params{name}};
1699 $params{name}=~s/.*:://;
1701 my $parent=$params{parent};
1702 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1703 $ns = $params{parent} . $ns;
1704 inject(%params, parent => $ns) unless $ns eq '::main::';
1705 *{$ns . $params{name}} = $params{call}
1706 if exists ${$ns}{$params{name}} &&
1707 \&{${$ns}{$params{name}}} == $params{old};
1713 sub pagespec_merge ($$) { #{{{
1717 return $a if $a eq $b;
1719 # Support for old-style GlobLists.
1720 if (is_globlist($a)) {
1721 $a=globlist_to_pagespec($a);
1723 if (is_globlist($b)) {
1724 $b=globlist_to_pagespec($b);
1727 return "($a) or ($b)";
1730 sub pagespec_translate ($) { #{{{
1733 # Support for old-style GlobLists.
1734 if (is_globlist($spec)) {
1735 $spec=globlist_to_pagespec($spec);
1738 # Convert spec to perl code.
1741 \s* # ignore whitespace
1742 ( # 1: match a single word
1749 \w+\([^\)]*\) # command(params)
1751 [^\s()]+ # any other text
1753 \s* # ignore whitespace
1756 if (lc $word eq 'and') {
1759 elsif (lc $word eq 'or') {
1762 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1765 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1766 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1767 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1774 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1778 if (! length $code) {
1783 return eval 'sub { my $page=shift; '.$code.' }';
1786 sub pagespec_match ($$;@) { #{{{
1791 # Backwards compatability with old calling convention.
1793 unshift @params, 'location';
1796 my $sub=pagespec_translate($spec);
1797 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1798 return $sub->($page, @params);
1801 sub pagespec_valid ($) { #{{{
1804 my $sub=pagespec_translate($spec);
1808 sub glob2re ($) { #{{{
1809 my $re=quotemeta(shift);
1815 package IkiWiki::FailReason;
1818 '""' => sub { ${$_[0]} },
1820 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1827 return bless \$value, $class;
1830 package IkiWiki::SuccessReason;
1833 '""' => sub { ${$_[0]} },
1835 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1842 return bless \$value, $class;
1845 package IkiWiki::PageSpec;
1847 sub match_glob ($$;@) { #{{{
1852 my $from=exists $params{location} ? $params{location} : '';
1855 if ($glob =~ m!^\./!) {
1856 $from=~s#/?[^/]+$##;
1858 $glob="$from/$glob" if length $from;
1861 my $regexp=IkiWiki::glob2re($glob);
1862 if ($page=~/^$regexp$/i) {
1863 if (! IkiWiki::isinternal($page) || $params{internal}) {
1864 return IkiWiki::SuccessReason->new("$glob matches $page");
1867 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1871 return IkiWiki::FailReason->new("$glob does not match $page");
1875 sub match_internal ($$;@) { #{{{
1876 return match_glob($_[0], $_[1], @_, internal => 1)
1879 sub match_link ($$;@) { #{{{
1884 my $from=exists $params{location} ? $params{location} : '';
1887 if ($link =~ m!^\.! && defined $from) {
1888 $from=~s#/?[^/]+$##;
1890 $link="$from/$link" if length $from;
1893 my $links = $IkiWiki::links{$page};
1894 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1895 my $bestlink = IkiWiki::bestlink($from, $link);
1896 foreach my $p (@{$links}) {
1897 if (length $bestlink) {
1898 return IkiWiki::SuccessReason->new("$page links to $link")
1899 if $bestlink eq IkiWiki::bestlink($page, $p);
1902 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1903 if match_glob($p, $link, %params);
1906 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1907 if match_glob($p, $link, %params);
1910 return IkiWiki::FailReason->new("$page does not link to $link");
1913 sub match_backlink ($$;@) { #{{{
1914 return match_link($_[1], $_[0], @_);
1917 sub match_created_before ($$;@) { #{{{
1921 if (exists $IkiWiki::pagectime{$testpage}) {
1922 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1923 return IkiWiki::SuccessReason->new("$page created before $testpage");
1926 return IkiWiki::FailReason->new("$page not created before $testpage");
1930 return IkiWiki::FailReason->new("$testpage has no ctime");
1934 sub match_created_after ($$;@) { #{{{
1938 if (exists $IkiWiki::pagectime{$testpage}) {
1939 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1940 return IkiWiki::SuccessReason->new("$page created after $testpage");
1943 return IkiWiki::FailReason->new("$page not created after $testpage");
1947 return IkiWiki::FailReason->new("$testpage has no ctime");
1951 sub match_creation_day ($$;@) { #{{{
1952 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1953 return IkiWiki::SuccessReason->new('creation_day matched');
1956 return IkiWiki::FailReason->new('creation_day did not match');
1960 sub match_creation_month ($$;@) { #{{{
1961 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1962 return IkiWiki::SuccessReason->new('creation_month matched');
1965 return IkiWiki::FailReason->new('creation_month did not match');
1969 sub match_creation_year ($$;@) { #{{{
1970 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1971 return IkiWiki::SuccessReason->new('creation_year matched');
1974 return IkiWiki::FailReason->new('creation_year did not match');
1978 sub match_user ($$;@) { #{{{
1983 if (! exists $params{user}) {
1984 return IkiWiki::FailReason->new("no user specified");
1987 if (defined $params{user} && lc $params{user} eq lc $user) {
1988 return IkiWiki::SuccessReason->new("user is $user");
1990 elsif (! defined $params{user}) {
1991 return IkiWiki::FailReason->new("not logged in");
1994 return IkiWiki::FailReason->new("user is $params{user}, not $user");
1998 sub match_admin ($$;@) { #{{{
2003 if (! exists $params{user}) {
2004 return IkiWiki::FailReason->new("no user specified");
2007 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2008 return IkiWiki::SuccessReason->new("user is an admin");
2010 elsif (! defined $params{user}) {
2011 return IkiWiki::FailReason->new("not logged in");
2014 return IkiWiki::FailReason->new("user is not an admin");
2018 sub match_ip ($$;@) { #{{{
2023 if (! exists $params{ip}) {
2024 return IkiWiki::FailReason->new("no IP specified");
2027 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2028 return IkiWiki::SuccessReason->new("IP is $ip");
2031 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");