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 %depends_simple %hooks
17 %forcerebuild %loaded_plugins @autofiles %dellinks
20 use Exporter q{import};
21 our @EXPORT = qw(hook debug error template htmlpage deptype
22 add_depends pagespec_match pagespec_match_list bestlink
23 htmllink readfile writefile pagetype srcfile pagename
24 displaytime will_render gettext urlto targetpage
25 add_underlay pagetitle titlepage linkpage newpagefile
26 inject add_link add_autofile
27 %config %links %pagestate %wikistate %renderedfiles
28 %pagesources %destsources);
29 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
30 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
31 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
33 # Page dependency types.
34 our $DEPEND_CONTENT=1;
35 our $DEPEND_PRESENCE=2;
41 memoize("pagespec_translate");
42 memoize("template_file");
48 description => "name of the wiki",
55 example => 'me@example.com',
56 description => "contact email for wiki",
63 description => "users who are wiki admins",
70 description => "users who are banned from the wiki",
77 example => "$ENV{HOME}/wiki",
78 description => "where the source of the wiki is located",
85 example => "/var/www/wiki",
86 description => "where to build the wiki",
93 example => "http://example.com/wiki",
94 description => "base url to the wiki",
101 example => "http://example.com/wiki/ikiwiki.cgi",
102 description => "url to the ikiwiki.cgi",
109 example => "/var/www/wiki/ikiwiki.cgi",
110 description => "filename of cgi wrapper to generate",
117 description => "mode for cgi_wrapper (can safely be made suid)",
124 description => "rcs backend to use",
125 safe => 0, # don't allow overriding
130 default => [qw{mdwn link inline meta htmlscrubber passwordauth
131 openid signinedit lockedit conditional
132 recentchanges parentlinks editpage}],
133 description => "plugins to enable by default",
140 description => "plugins to add to the default configuration",
147 description => "plugins to disable",
153 default => "$installdir/share/ikiwiki/templates",
154 description => "location of template files",
162 description => "additional directories containing template files",
168 default => "$installdir/share/ikiwiki/basewiki",
169 description => "base wiki source location",
176 default => "$installdir/share/ikiwiki",
177 description => "parent directory containing additional underlays",
184 description => "wrappers to generate",
191 description => "additional underlays to use",
198 description => "display verbose messages?",
205 description => "log to syslog?",
212 description => "create output files named page/index.html?",
213 safe => 0, # changing requires manual transition
216 prefix_directives => {
219 description => "use '!'-prefixed preprocessor directives?",
220 safe => 0, # changing requires manual transition
226 description => "use page/index.mdwn source files",
233 description => "enable Discussion pages?",
239 default => gettext("Discussion"),
240 description => "name of Discussion pages",
247 description => "only send cookies over SSL connections?",
255 description => "extension to use for new pages",
256 safe => 0, # not sanitized
262 description => "extension to use for html files",
263 safe => 0, # not sanitized
269 description => "strftime format string to display date",
277 example => "en_US.UTF-8",
278 description => "UTF-8 locale to use",
287 description => "put user pages below specified page",
294 description => "how many backlinks to show before hiding excess (0 to show all)",
301 description => "attempt to hardlink source files? (optimisation for large files)",
303 safe => 0, # paranoia
309 description => "force ikiwiki to use a particular umask",
311 safe => 0, # paranoia
316 example => "ikiwiki",
317 description => "group for wrappers to run in",
319 safe => 0, # paranoia
325 example => "$ENV{HOME}/.ikiwiki/",
326 description => "extra library and plugin directory",
328 safe => 0, # directory
334 description => "environment variables",
335 safe => 0, # paranoia
342 description => "regexp of source files to ignore",
347 wiki_file_prune_regexps => {
349 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
350 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
351 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
352 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
353 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
354 description => "regexps of source files to ignore",
360 description => "specifies the characters that are allowed in source filenames",
361 default => "-[:alnum:]+/.:_",
365 wiki_file_regexp => {
367 description => "regexp of legal source files",
371 web_commit_regexp => {
373 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
374 description => "regexp to parse web commits from logs",
381 description => "run as a cgi",
385 cgi_disable_uploads => {
388 description => "whether CGI should accept file uploads",
395 description => "run as a post-commit hook",
402 description => "running in rebuild mode",
409 description => "running in setup mode",
416 description => "running in refresh mode",
423 description => "running in receive test mode",
430 description => "running in getctime mode",
437 description => "running in w3mmode",
444 description => "path to the .ikiwiki directory holding ikiwiki state",
451 description => "path to setup file",
455 allow_symlinks_before_srcdir => {
458 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
464 sub defaultconfig () {
467 foreach my $key (keys %s) {
468 push @ret, $key, $s{$key}->{default};
475 # locale stuff; avoid LC_ALL since it overrides everything
476 if (defined $ENV{LC_ALL}) {
477 $ENV{LANG} = $ENV{LC_ALL};
480 if (defined $config{locale}) {
481 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
482 $ENV{LANG}=$config{locale};
487 if (! defined $config{wiki_file_regexp}) {
488 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
491 if (ref $config{ENV} eq 'HASH') {
492 foreach my $val (keys %{$config{ENV}}) {
493 $ENV{$val}=$config{ENV}{$val};
497 if ($config{w3mmode}) {
498 eval q{use Cwd q{abs_path}};
500 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
501 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
502 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
503 unless $config{cgiurl} =~ m!file:///!;
504 $config{url}="file://".$config{destdir};
507 if ($config{cgi} && ! length $config{url}) {
508 error(gettext("Must specify url to wiki with --url when using --cgi"));
511 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
512 unless exists $config{wikistatedir} && defined $config{wikistatedir};
514 if (defined $config{umask}) {
515 umask(possibly_foolish_untaint($config{umask}));
518 run_hooks(checkconfig => sub { shift->() });
526 foreach my $dir (@INC, $config{libdir}) {
527 next unless defined $dir && length $dir;
528 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
529 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
533 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
534 next unless defined $dir && length $dir;
535 foreach my $file (glob("$dir/plugins/*")) {
536 $ret{basename($file)}=1 if -x $file;
544 if (defined $config{libdir} && length $config{libdir}) {
545 unshift @INC, possibly_foolish_untaint($config{libdir});
548 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
553 if (exists $hooks{rcs}) {
554 error(gettext("cannot use multiple rcs plugins"));
556 loadplugin($config{rcs});
558 if (! exists $hooks{rcs}) {
562 run_hooks(getopt => sub { shift->() });
563 if (grep /^-/, @ARGV) {
564 print STDERR "Unknown option (or missing parameter): $_\n"
565 foreach grep /^-/, @ARGV;
575 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
577 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
578 "$installdir/lib/ikiwiki") {
579 if (defined $dir && -x "$dir/plugins/$plugin") {
580 eval { require IkiWiki::Plugin::external };
583 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
585 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
586 $loaded_plugins{$plugin}=1;
591 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
594 error("Failed to load plugin $mod: $@");
596 $loaded_plugins{$plugin}=1;
603 log_message('err' => $message) if $config{syslog};
604 if (defined $cleaner) {
611 return unless $config{verbose};
612 return log_message(debug => @_);
616 sub log_message ($$) {
619 if ($config{syslog}) {
622 Sys::Syslog::setlogsock('unix');
623 Sys::Syslog::openlog('ikiwiki', '', 'user');
627 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
630 elsif (! $config{cgi}) {
634 return print STDERR "@_\n";
638 sub possibly_foolish_untaint ($) {
640 my ($untainted)=$tainted=~/(.*)/s;
660 return exists $pagesources{$page} &&
661 $pagesources{$page} =~ /\._([^.]+)$/;
667 if ($file =~ /\.([^.]+)$/) {
668 return $1 if exists $hooks{htmlize}{$1};
670 my $base=basename($file);
671 if (exists $hooks{htmlize}{$base} &&
672 $hooks{htmlize}{$base}{noextension}) {
683 if (exists $pagename_cache{$file}) {
684 return $pagename_cache{$file};
687 my $type=pagetype($file);
689 $page=~s/\Q.$type\E*$//
690 if defined $type && !$hooks{htmlize}{$type}{keepextension}
691 && !$hooks{htmlize}{$type}{noextension};
692 if ($config{indexpages} && $page=~/(.*)\/index$/) {
696 $pagename_cache{$file} = $page;
700 sub newpagefile ($$) {
704 if (! $config{indexpages} || $page eq 'index') {
705 return $page.".".$type;
708 return $page."/index.".$type;
712 sub targetpage ($$;$) {
717 if (defined $filename) {
718 return $page."/".$filename.".".$ext;
720 elsif (! $config{usedirs} || $page eq 'index') {
721 return $page.".".$ext;
724 return $page."/index.".$ext;
731 return targetpage($page, $config{htmlext});
738 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
739 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
740 return "$dir/$file", stat(_) if -e "$dir/$file";
742 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
747 return (srcfile_stat(@_))[0];
750 sub add_underlay ($) {
754 $dir="$config{underlaydirbase}/$dir";
757 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
758 unshift @{$config{underlaydirs}}, $dir;
764 sub readfile ($;$$) {
770 error("cannot read a symlink ($file)");
774 open (my $in, "<", $file) || error("failed to read $file: $!");
775 binmode($in) if ($binary);
776 return \*$in if $wantfd;
778 # check for invalid utf-8, and toss it back to avoid crashes
779 if (! utf8::valid($ret)) {
780 $ret=encode_utf8($ret);
782 close $in || error("failed to read $file: $!");
786 sub prep_writefile ($$) {
791 while (length $test) {
792 if (-l "$destdir/$test") {
793 error("cannot write to a symlink ($test)");
795 $test=dirname($test);
798 my $dir=dirname("$destdir/$file");
801 foreach my $s (split(m!/+!, $dir)) {
804 mkdir($d) || error("failed to create directory $d: $!");
812 sub writefile ($$$;$$) {
813 my $file=shift; # can include subdirs
814 my $destdir=shift; # directory to put file in
819 prep_writefile($file, $destdir);
821 my $newfile="$destdir/$file.ikiwiki-new";
823 error("cannot write to a symlink ($newfile)");
826 my $cleanup = sub { unlink($newfile) };
827 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
828 binmode($out) if ($binary);
830 $writer->(\*$out, $cleanup);
833 print $out $content or error("failed writing to $newfile: $!", $cleanup);
835 close $out || error("failed saving $newfile: $!", $cleanup);
836 rename($newfile, "$destdir/$file") ||
837 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
843 sub will_render ($$;$) {
848 # Important security check.
849 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
850 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
851 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
854 if (! $clear || $cleared{$page}) {
855 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
858 foreach my $old (@{$renderedfiles{$page}}) {
859 delete $destsources{$old};
861 $renderedfiles{$page}=[$dest];
864 $destsources{$dest}=$page;
874 if ($link=~s/^\/+//) {
882 $l.="/" if length $l;
885 if (exists $pagesources{$l}) {
888 elsif (exists $pagecase{lc $l}) {
889 return $pagecase{lc $l};
891 } while $cwd=~s{/?[^/]+$}{};
893 if (length $config{userdir}) {
894 my $l = "$config{userdir}/".lc($link);
895 if (exists $pagesources{$l}) {
898 elsif (exists $pagecase{lc $l}) {
899 return $pagecase{lc $l};
903 #print STDERR "warning: page $page, broken link: $link\n";
907 sub isinlinableimage ($) {
910 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
913 sub pagetitle ($;$) {
918 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
921 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
929 # support use w/o %config set
930 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
931 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
937 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
938 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
945 return $config{cgiurl}."?".
946 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
952 return "$config{url}/" if ! defined $page;
954 $page=htmlpage($page);
956 $page=~s/[^\/]+\//..\//g;
961 # Work around very innefficient behavior in File::Spec if abs2rel
962 # is passed two relative paths. It's much faster if paths are
963 # absolute! (Debian bug #376658; fixed in debian unstable now)
968 my $ret=File::Spec->abs2rel($path, $base);
969 $ret=~s/^// if defined $ret;
973 sub displaytime ($;$) {
974 # Plugins can override this function to mark up the time to
976 return '<span class="date">'.formattime(@_).'</span>';
979 sub formattime ($;$) {
980 # Plugins can override this function to format the time.
983 if (! defined $format) {
984 $format=$config{timeformat};
987 # strftime doesn't know about encodings, so make sure
988 # its output is properly treated as utf8
989 return decode_utf8(POSIX::strftime($format, localtime($time)));
992 sub beautify_urlpath ($) {
995 # Ensure url is not an empty link, and if necessary,
996 # add ./ to avoid colon confusion.
997 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1001 if ($config{usedirs}) {
1002 $url =~ s!/index.$config{htmlext}$!/!;
1014 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1017 if (! $destsources{$to}) {
1022 return $config{url}.beautify_urlpath("/".$to);
1025 my $link = abs2rel($to, dirname(htmlpage($from)));
1027 return beautify_urlpath($link);
1030 sub htmllink ($$$;@) {
1031 my $lpage=shift; # the page doing the linking
1032 my $page=shift; # the page that will contain the link (different for inline)
1039 if (! $opts{forcesubpage}) {
1040 $bestlink=bestlink($lpage, $link);
1043 $bestlink="$lpage/".lc($link);
1047 if (defined $opts{linktext}) {
1048 $linktext=$opts{linktext};
1051 $linktext=pagetitle(basename($link));
1054 return "<span class=\"selflink\">$linktext</span>"
1055 if length $bestlink && $page eq $bestlink &&
1056 ! defined $opts{anchor};
1058 if (! $destsources{$bestlink}) {
1059 $bestlink=htmlpage($bestlink);
1061 if (! $destsources{$bestlink}) {
1062 return $linktext unless length $config{cgiurl};
1063 return "<span class=\"createlink\"><a href=\"".
1069 "\" rel=\"nofollow\">?</a>$linktext</span>"
1073 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1074 $bestlink=beautify_urlpath($bestlink);
1076 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1077 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1080 if (defined $opts{anchor}) {
1081 $bestlink.="#".$opts{anchor};
1085 foreach my $attr (qw{rel class title}) {
1086 if (defined $opts{$attr}) {
1087 push @attrs, " $attr=\"$opts{$attr}\"";
1091 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1094 sub openiduser ($) {
1097 if ($user =~ m!^https?://! &&
1098 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1101 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1102 # this works in at least 2.x
1103 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1106 # this only works in 1.x
1107 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1108 $display=$oid->display;
1111 # Convert "user.somehost.com" to "user [somehost.com]"
1112 # (also "user.somehost.co.uk")
1113 if ($display !~ /\[/) {
1114 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1116 # Convert "http://somehost.com/user" to "user [somehost.com]".
1117 # (also "https://somehost.com/user/")
1118 if ($display !~ /\[/) {
1119 $display=~s/^https?:\/\/(.+)\/([^\/]+)\/?$/$2 [$1]/;
1121 $display=~s!^https?://!!; # make sure this is removed
1122 eval q{use CGI 'escapeHTML'};
1124 return escapeHTML($display);
1132 my $oiduser=eval { openiduser($user) };
1133 if (defined $oiduser) {
1134 return "<a href=\"$user\">$oiduser</a>";
1137 eval q{use CGI 'escapeHTML'};
1140 return htmllink("", "", escapeHTML(
1141 length $config{userdir} ? $config{userdir}."/".$user : $user
1142 ), noimageinline => 1);
1146 sub htmlize ($$$$) {
1152 my $oneline = $content !~ /\n/;
1154 if (exists $hooks{htmlize}{$type}) {
1155 $content=$hooks{htmlize}{$type}{call}->(
1157 content => $content,
1161 error("htmlization of $type not supported");
1164 run_hooks(sanitize => sub {
1167 destpage => $destpage,
1168 content => $content,
1173 # hack to get rid of enclosing junk added by markdown
1174 # and other htmlizers
1175 $content=~s/^<p>//i;
1176 $content=~s/<\/p>$//i;
1188 run_hooks(linkify => sub {
1191 destpage => $destpage,
1192 content => $content,
1200 our $preprocess_preview=0;
1201 sub preprocess ($$$;$$) {
1202 my $page=shift; # the page the data comes from
1203 my $destpage=shift; # the page the data will appear in (different for inline)
1208 # Using local because it needs to be set within any nested calls
1210 local $preprocess_preview=$preview if defined $preview;
1217 $params="" if ! defined $params;
1219 if (length $escape) {
1220 return "[[$prefix$command $params]]";
1222 elsif (exists $hooks{preprocess}{$command}) {
1223 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1224 # Note: preserve order of params, some plugins may
1225 # consider it significant.
1227 while ($params =~ m{
1228 (?:([-\w]+)=)? # 1: named parameter key?
1230 """(.*?)""" # 2: triple-quoted value
1232 "([^"]+)" # 3: single-quoted value
1234 (\S+) # 4: unquoted value
1236 (?:\s+|$) # delimiter to next param
1246 elsif (defined $3) {
1249 elsif (defined $4) {
1254 push @params, $key, $val;
1257 push @params, $val, '';
1260 if ($preprocessing{$page}++ > 3) {
1261 # Avoid loops of preprocessed pages preprocessing
1262 # other pages that preprocess them, etc.
1263 return "[[!$command <span class=\"error\">".
1264 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1265 $page, $preprocessing{$page}).
1271 $hooks{preprocess}{$command}{call}->(
1274 destpage => $destpage,
1275 preview => $preprocess_preview,
1281 $ret="[[!$command <span class=\"error\">".
1282 gettext("Error").": $error"."</span>]]";
1286 # use void context during scan pass
1288 $hooks{preprocess}{$command}{call}->(
1291 destpage => $destpage,
1292 preview => $preprocess_preview,
1297 $preprocessing{$page}--;
1301 return "[[$prefix$command $params]]";
1306 if ($config{prefix_directives}) {
1309 \[\[(!) # directive open; 2: prefix
1310 ([-\w]+) # 3: command
1311 ( # 4: the parameters..
1312 \s+ # Must have space if parameters present
1314 (?:[-\w]+=)? # named parameter key?
1316 """.*?""" # triple-quoted value
1318 "[^"]+" # single-quoted value
1320 [^"\s\]]+ # unquoted value
1322 \s* # whitespace or end
1325 *)? # 0 or more parameters
1326 \]\] # directive closed
1332 \[\[(!?) # directive open; 2: optional prefix
1333 ([-\w]+) # 3: command
1335 ( # 4: the parameters..
1337 (?:[-\w]+=)? # named parameter key?
1339 """.*?""" # triple-quoted value
1341 "[^"]+" # single-quoted value
1343 [^"\s\]]+ # unquoted value
1345 \s* # whitespace or end
1348 *) # 0 or more parameters
1349 \]\] # directive closed
1353 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1362 run_hooks(filter => sub {
1363 $content=shift->(page => $page, destpage => $destpage,
1364 content => $content);
1371 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1374 sub check_canedit ($$$;$) {
1381 run_hooks(canedit => sub {
1382 return if defined $canedit;
1383 my $ret=shift->($page, $q, $session);
1388 elsif (ref $ret eq 'CODE') {
1389 $ret->() unless $nonfatal;
1392 elsif (defined $ret) {
1393 error($ret) unless $nonfatal;
1398 return defined $canedit ? $canedit : 1;
1401 sub check_content (@) {
1404 return 1 if ! exists $hooks{checkcontent}; # optimisation
1406 if (exists $pagesources{$params{page}}) {
1408 my %old=map { $_ => 1 }
1409 split("\n", readfile(srcfile($pagesources{$params{page}})));
1410 foreach my $line (split("\n", $params{content})) {
1411 push @diff, $line if ! exists $old{$line};
1413 $params{diff}=join("\n", @diff);
1417 run_hooks(checkcontent => sub {
1418 return if defined $ok;
1419 my $ret=shift->(%params);
1424 elsif (ref $ret eq 'CODE') {
1425 $ret->() unless $params{nonfatal};
1428 elsif (defined $ret) {
1429 error($ret) unless $params{nonfatal};
1435 return defined $ok ? $ok : 1;
1441 # Take an exclusive lock on the wiki to prevent multiple concurrent
1442 # run issues. The lock will be dropped on program exit.
1443 if (! -d $config{wikistatedir}) {
1444 mkdir($config{wikistatedir});
1446 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1447 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1448 if (! flock($wikilock, 2)) { # LOCK_EX
1449 error("failed to get lock");
1455 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1456 return close($wikilock) if $wikilock;
1462 sub commit_hook_enabled () {
1463 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1464 error("cannot write to $config{wikistatedir}/commitlock: $!");
1465 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1466 close($commitlock) || error("failed closing commitlock: $!");
1469 close($commitlock) || error("failed closing commitlock: $!");
1473 sub disable_commit_hook () {
1474 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1475 error("cannot write to $config{wikistatedir}/commitlock: $!");
1476 if (! flock($commitlock, 2)) { # LOCK_EX
1477 error("failed to get commit lock");
1482 sub enable_commit_hook () {
1483 return close($commitlock) if $commitlock;
1488 %oldrenderedfiles=%pagectime=();
1489 if (! $config{rebuild}) {
1490 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1491 %destsources=%renderedfiles=%pagecase=%pagestate=
1495 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1496 if (-e "$config{wikistatedir}/index") {
1497 system("ikiwiki-transition", "indexdb", $config{srcdir});
1498 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1505 my $index=Storable::fd_retrieve($in);
1506 if (! defined $index) {
1511 if (exists $index->{version} && ! ref $index->{version}) {
1512 $pages=$index->{page};
1513 %wikistate=%{$index->{state}};
1520 foreach my $src (keys %$pages) {
1521 my $d=$pages->{$src};
1522 my $page=pagename($src);
1523 $pagectime{$page}=$d->{ctime};
1524 if (! $config{rebuild}) {
1525 $pagesources{$page}=$src;
1526 $pagemtime{$page}=$d->{mtime};
1527 $renderedfiles{$page}=$d->{dest};
1528 if (exists $d->{links} && ref $d->{links}) {
1529 $links{$page}=$d->{links};
1530 $oldlinks{$page}=[@{$d->{links}}];
1532 if (ref $d->{depends_simple} eq 'ARRAY') {
1534 $depends_simple{$page}={
1535 map { $_ => 1 } @{$d->{depends_simple}}
1538 elsif (exists $d->{depends_simple}) {
1539 $depends_simple{$page}=$d->{depends_simple};
1541 if (exists $d->{dependslist}) {
1544 map { $_ => $DEPEND_CONTENT }
1545 @{$d->{dependslist}}
1548 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1550 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1552 elsif (exists $d->{depends}) {
1553 $depends{$page}=$d->{depends};
1555 if (exists $d->{state}) {
1556 $pagestate{$page}=$d->{state};
1559 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1561 foreach my $page (keys %pagesources) {
1562 $pagecase{lc $page}=$page;
1564 foreach my $page (keys %renderedfiles) {
1565 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1571 run_hooks(savestate => sub { shift->() });
1574 foreach my $type (keys %hooks) {
1575 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1577 my @hookids=keys %hookids;
1579 if (! -d $config{wikistatedir}) {
1580 mkdir($config{wikistatedir});
1582 my $newfile="$config{wikistatedir}/indexdb.new";
1583 my $cleanup = sub { unlink($newfile) };
1584 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1587 foreach my $page (keys %pagemtime) {
1588 next unless $pagemtime{$page};
1589 my $src=$pagesources{$page};
1591 $index{page}{$src}={
1592 ctime => $pagectime{$page},
1593 mtime => $pagemtime{$page},
1594 dest => $renderedfiles{$page},
1595 links => $links{$page},
1598 if (exists $depends{$page}) {
1599 $index{page}{$src}{depends} = $depends{$page};
1602 if (exists $depends_simple{$page}) {
1603 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1606 if (exists $pagestate{$page}) {
1607 foreach my $id (@hookids) {
1608 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1609 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1616 foreach my $id (@hookids) {
1617 foreach my $key (keys %{$wikistate{$id}}) {
1618 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1622 $index{version}="3";
1623 my $ret=Storable::nstore_fd(\%index, $out);
1624 return if ! defined $ret || ! $ret;
1625 close $out || error("failed saving to $newfile: $!", $cleanup);
1626 rename($newfile, "$config{wikistatedir}/indexdb") ||
1627 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1632 sub template_file ($) {
1635 foreach my $dir ($config{templatedir}, @{$config{templatedirs}},
1636 "$installdir/share/ikiwiki/templates") {
1637 return "$dir/$template" if -e "$dir/$template";
1642 sub template_params (@) {
1643 my $filename=template_file(shift);
1645 if (! defined $filename) {
1646 return if wantarray;
1652 my $text_ref = shift;
1653 ${$text_ref} = decode_utf8(${$text_ref});
1655 filename => $filename,
1656 loop_context_vars => 1,
1657 die_on_bad_params => 0,
1660 return wantarray ? @ret : {@ret};
1663 sub template ($;@) {
1664 require HTML::Template;
1665 return HTML::Template->new(template_params(@_));
1668 sub misctemplate ($$;@) {
1672 my $template=template("misc.tmpl");
1675 indexlink => indexlink(),
1676 wikiname => $config{wikiname},
1677 pagebody => $pagebody,
1678 baseurl => baseurl(),
1681 run_hooks(pagetemplate => sub {
1682 shift->(page => "", destpage => "", template => $template);
1684 return $template->output;
1690 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1691 error 'hook requires type, call, and id parameters';
1694 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1696 $hooks{$param{type}}{$param{id}}=\%param;
1700 sub run_hooks ($$) {
1701 # Calls the given sub for each hook of the given type,
1702 # passing it the hook function to call.
1706 if (exists $hooks{$type}) {
1707 my (@first, @middle, @last);
1708 foreach my $id (keys %{$hooks{$type}}) {
1709 if ($hooks{$type}{$id}{first}) {
1712 elsif ($hooks{$type}{$id}{last}) {
1719 foreach my $id (@first, @middle, @last) {
1720 $sub->($hooks{$type}{$id}{call});
1728 $hooks{rcs}{rcs_update}{call}->(@_);
1731 sub rcs_prepedit ($) {
1732 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1735 sub rcs_commit ($$$;$$) {
1736 $hooks{rcs}{rcs_commit}{call}->(@_);
1739 sub rcs_commit_staged ($$$) {
1740 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1744 $hooks{rcs}{rcs_add}{call}->(@_);
1747 sub rcs_remove ($) {
1748 $hooks{rcs}{rcs_remove}{call}->(@_);
1751 sub rcs_rename ($$) {
1752 $hooks{rcs}{rcs_rename}{call}->(@_);
1755 sub rcs_recentchanges ($) {
1756 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1760 $hooks{rcs}{rcs_diff}{call}->(@_);
1763 sub rcs_getctime ($) {
1764 $hooks{rcs}{rcs_getctime}{call}->(@_);
1767 sub rcs_receive () {
1768 $hooks{rcs}{rcs_receive}{call}->();
1771 sub add_depends ($$;$) {
1774 my $deptype=shift || $DEPEND_CONTENT;
1776 # Is the pagespec a simple page name?
1777 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1778 $pagespec !~ /[\s*?()!]/) {
1779 $depends_simple{$page}{lc $pagespec} |= $deptype;
1783 # Add explicit dependencies for influences.
1784 my $sub=pagespec_translate($pagespec);
1786 foreach my $p (keys %pagesources) {
1787 my $r=$sub->($p, location => $page);
1788 my $i=$r->influences;
1789 foreach my $k (keys %$i) {
1790 $depends_simple{$page}{lc $k} |= $i->{$k};
1792 last if $r->influences_static;
1795 $depends{$page}{$pagespec} |= $deptype;
1801 foreach my $type (@_) {
1802 if ($type eq 'presence') {
1803 $deptype |= $DEPEND_PRESENCE;
1805 elsif ($type eq 'links') {
1806 $deptype |= $DEPEND_LINKS;
1808 elsif ($type eq 'content') {
1809 $deptype |= $DEPEND_CONTENT;
1815 sub file_pruned ($;$) {
1819 $file=File::Spec->canonpath($file);
1820 my $base=File::Spec->canonpath(shift);
1821 return if $file eq $base;
1822 $file =~ s#^\Q$base\E/+##;
1825 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1826 return $file =~ m/$regexp/;
1829 sub define_gettext () {
1830 # If translation is needed, redefine the gettext function to do it.
1831 # Otherwise, it becomes a quick no-op.
1832 no warnings 'redefine';
1833 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1834 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1835 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1837 my $gettext_obj=eval q{
1838 use Locale::gettext q{textdomain};
1839 Locale::gettext->domain('ikiwiki')
1843 $gettext_obj->get(shift);
1851 *gettext=sub { return shift };
1863 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1867 # Injects a new function into the symbol table to replace an
1868 # exported function.
1871 # This is deep ugly perl foo, beware.
1874 if (! defined $params{parent}) {
1875 $params{parent}='::';
1876 $params{old}=\&{$params{name}};
1877 $params{name}=~s/.*:://;
1879 my $parent=$params{parent};
1880 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1881 $ns = $params{parent} . $ns;
1882 inject(%params, parent => $ns) unless $ns eq '::main::';
1883 *{$ns . $params{name}} = $params{call}
1884 if exists ${$ns}{$params{name}} &&
1885 \&{${$ns}{$params{name}}} == $params{old};
1895 push @{$links{$page}}, $link
1896 unless grep { $_ eq $link } @{$links{$page}};
1899 sub add_autofile ($) {
1901 my ($file,$page) = verify_src_file($addfile,$config{srcdir});
1903 push @autofiles, $file;
1907 sub pagespec_translate ($) {
1910 # Convert spec to perl code.
1914 \s* # ignore whitespace
1915 ( # 1: match a single word
1922 \w+\([^\)]*\) # command(params)
1924 [^\s()]+ # any other text
1926 \s* # ignore whitespace
1929 if (lc $word eq 'and') {
1932 elsif (lc $word eq 'or') {
1935 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1938 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1939 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1941 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
1944 push @data, qq{unknown function in pagespec "$word"};
1945 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
1950 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
1954 if (! length $code) {
1955 $code="IkiWiki::FailReason->new('empty pagespec')";
1959 return eval 'sub { my $page=shift; '.$code.' }';
1962 sub pagespec_match ($$;@) {
1967 # Backwards compatability with old calling convention.
1969 unshift @params, 'location';
1972 my $sub=pagespec_translate($spec);
1973 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
1974 if $@ || ! defined $sub;
1975 return $sub->($page, @params);
1978 sub pagespec_match_list ($$;@) {
1983 # Backwards compatability with old calling convention.
1985 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
1986 $params{list}=$page;
1987 $page=$params{location}; # ugh!
1990 my $sub=pagespec_translate($pagespec);
1991 error "syntax error in pagespec \"$pagespec\""
1992 if $@ || ! defined $sub;
1995 if (exists $params{list}) {
1996 @candidates=exists $params{filter}
1997 ? grep { ! $params{filter}->($_) } @{$params{list}}
2001 @candidates=exists $params{filter}
2002 ? grep { ! $params{filter}->($_) } keys %pagesources
2003 : keys %pagesources;
2006 if (defined $params{sort}) {
2008 if ($params{sort} eq 'title') {
2009 $f=sub { pagetitle(basename($a)) cmp pagetitle(basename($b)) };
2011 elsif ($params{sort} eq 'title_natural') {
2012 eval q{use Sort::Naturally};
2014 error(gettext("Sort::Naturally needed for title_natural sort"));
2016 $f=sub { Sort::Naturally::ncmp(pagetitle(basename($a)), pagetitle(basename($b))) };
2018 elsif ($params{sort} eq 'mtime') {
2019 $f=sub { $pagemtime{$b} <=> $pagemtime{$a} };
2021 elsif ($params{sort} eq 'age') {
2022 $f=sub { $pagectime{$b} <=> $pagectime{$a} };
2025 error sprintf(gettext("unknown sort type %s"), $params{sort});
2027 @candidates = sort { &$f } @candidates;
2030 @candidates=reverse(@candidates) if $params{reverse};
2032 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2034 # clear params, remainder is passed to pagespec
2035 my $num=$params{num};
2036 delete @params{qw{num deptype reverse sort filter list}};
2041 my $accum=IkiWiki::SuccessReason->new();
2042 foreach my $p (@candidates) {
2043 my $r=$sub->($p, %params, location => $page);
2044 error(sprintf(gettext("cannot match pages: %s"), $r))
2045 if $r->isa("IkiWiki::ErrorReason");
2049 last if defined $num && ++$count == $num;
2053 # Add simple dependencies for accumulated influences.
2054 my $i=$accum->influences;
2055 foreach my $k (keys %$i) {
2056 $depends_simple{$page}{lc $k} |= $i->{$k};
2062 sub pagespec_valid ($) {
2065 my $sub=pagespec_translate($spec);
2070 my $re=quotemeta(shift);
2076 package IkiWiki::FailReason;
2079 '""' => sub { $_[0][0] },
2081 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2082 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2083 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2087 our @ISA = 'IkiWiki::SuccessReason';
2089 package IkiWiki::SuccessReason;
2092 '""' => sub { $_[0][0] },
2094 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2095 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2096 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2103 return bless [$value, {@_}], $class;
2108 $this->[1]={@_} if @_;
2109 my %i=%{$this->[1]};
2114 sub influences_static {
2115 return ! $_[0][1]->{""};
2118 sub merge_influences {
2123 if (! $anded || (($this || %{$this->[1]}) &&
2124 ($other || %{$other->[1]}))) {
2125 foreach my $influence (keys %{$other->[1]}) {
2126 $this->[1]{$influence} |= $other->[1]{$influence};
2135 package IkiWiki::ErrorReason;
2137 our @ISA = 'IkiWiki::FailReason';
2139 package IkiWiki::PageSpec;
2145 if ($path =~ m!^\./!) {
2146 $from=~s#/?[^/]+$## if defined $from;
2148 $path="$from/$path" if length $from;
2154 sub match_glob ($$;@) {
2159 $glob=derel($glob, $params{location});
2161 my $regexp=IkiWiki::glob2re($glob);
2162 if ($page=~/^$regexp$/i) {
2163 if (! IkiWiki::isinternal($page) || $params{internal}) {
2164 return IkiWiki::SuccessReason->new("$glob matches $page");
2167 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2171 return IkiWiki::FailReason->new("$glob does not match $page");
2175 sub match_internal ($$;@) {
2176 return match_glob($_[0], $_[1], @_, internal => 1)
2179 sub match_link ($$;@) {
2184 $link=derel($link, $params{location});
2185 my $from=exists $params{location} ? $params{location} : '';
2187 my $links = $IkiWiki::links{$page};
2188 return IkiWiki::FailReason->new("$page has no links", "" => 1)
2189 unless $links && @{$links};
2190 my $bestlink = IkiWiki::bestlink($from, $link);
2191 foreach my $p (@{$links}) {
2192 if (length $bestlink) {
2193 return IkiWiki::SuccessReason->new("$page links to $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2194 if $bestlink eq IkiWiki::bestlink($page, $p);
2197 return IkiWiki::SuccessReason->new("$page links to page $p matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2198 if match_glob($p, $link, %params);
2199 my ($p_rel)=$p=~/^\/?(.*)/;
2201 return IkiWiki::SuccessReason->new("$page links to page $p_rel matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2202 if match_glob($p_rel, $link, %params);
2205 return IkiWiki::FailReason->new("$page does not link to $link", "" => 1);
2208 sub match_backlink ($$;@) {
2209 my $ret=match_link($_[1], $_[0], @_);
2210 $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2214 sub match_created_before ($$;@) {
2219 $testpage=derel($testpage, $params{location});
2221 if (exists $IkiWiki::pagectime{$testpage}) {
2222 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2223 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2226 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2230 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2234 sub match_created_after ($$;@) {
2239 $testpage=derel($testpage, $params{location});
2241 if (exists $IkiWiki::pagectime{$testpage}) {
2242 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2243 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2246 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2250 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2254 sub match_creation_day ($$;@) {
2255 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2256 return IkiWiki::SuccessReason->new('creation_day matched');
2259 return IkiWiki::FailReason->new('creation_day did not match');
2263 sub match_creation_month ($$;@) {
2264 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2265 return IkiWiki::SuccessReason->new('creation_month matched');
2268 return IkiWiki::FailReason->new('creation_month did not match');
2272 sub match_creation_year ($$;@) {
2273 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2274 return IkiWiki::SuccessReason->new('creation_year matched');
2277 return IkiWiki::FailReason->new('creation_year did not match');
2281 sub match_user ($$;@) {
2286 if (! exists $params{user}) {
2287 return IkiWiki::ErrorReason->new("no user specified");
2290 if (defined $params{user} && lc $params{user} eq lc $user) {
2291 return IkiWiki::SuccessReason->new("user is $user");
2293 elsif (! defined $params{user}) {
2294 return IkiWiki::FailReason->new("not logged in");
2297 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2301 sub match_admin ($$;@) {
2306 if (! exists $params{user}) {
2307 return IkiWiki::ErrorReason->new("no user specified");
2310 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2311 return IkiWiki::SuccessReason->new("user is an admin");
2313 elsif (! defined $params{user}) {
2314 return IkiWiki::FailReason->new("not logged in");
2317 return IkiWiki::FailReason->new("user is not an admin");
2321 sub match_ip ($$;@) {
2326 if (! exists $params{ip}) {
2327 return IkiWiki::ErrorReason->new("no IP specified");
2330 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2331 return IkiWiki::SuccessReason->new("IP is $ip");
2334 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");