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};
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error template htmlpage deptype
21 add_depends pagespec_match pagespec_match_list bestlink
22 htmllink readfile writefile pagetype srcfile pagename
23 displaytime will_render gettext ngettext urlto targetpage
24 add_underlay pagetitle titlepage linkpage newpagefile
26 %config %links %pagestate %wikistate %renderedfiles
27 %pagesources %destsources);
28 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
29 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
30 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
32 # Page dependency types.
33 our $DEPEND_CONTENT=1;
34 our $DEPEND_PRESENCE=2;
40 memoize("pagespec_translate");
41 memoize("template_file");
47 description => "name of the wiki",
54 example => 'me@example.com',
55 description => "contact email for wiki",
62 description => "users who are wiki admins",
69 description => "users who are banned from the wiki",
76 example => "$ENV{HOME}/wiki",
77 description => "where the source of the wiki is located",
84 example => "/var/www/wiki",
85 description => "where to build the wiki",
92 example => "http://example.com/wiki",
93 description => "base url to the wiki",
100 example => "http://example.com/wiki/ikiwiki.cgi",
101 description => "url to the ikiwiki.cgi",
108 example => "/var/www/wiki/ikiwiki.cgi",
109 description => "filename of cgi wrapper to generate",
116 description => "mode for cgi_wrapper (can safely be made suid)",
123 description => "rcs backend to use",
124 safe => 0, # don't allow overriding
129 default => [qw{mdwn link inline meta htmlscrubber passwordauth
130 openid signinedit lockedit conditional
131 recentchanges parentlinks editpage}],
132 description => "plugins to enable by default",
139 description => "plugins to add to the default configuration",
146 description => "plugins to disable",
152 default => "$installdir/share/ikiwiki/templates",
153 description => "location of template files",
161 description => "additional directories containing template files",
167 default => "$installdir/share/ikiwiki/basewiki",
168 description => "base wiki source location",
175 default => "$installdir/share/ikiwiki",
176 description => "parent directory containing additional underlays",
183 description => "wrappers to generate",
190 description => "additional underlays to use",
197 description => "display verbose messages?",
204 description => "log to syslog?",
211 description => "create output files named page/index.html?",
212 safe => 0, # changing requires manual transition
215 prefix_directives => {
218 description => "use '!'-prefixed preprocessor directives?",
219 safe => 0, # changing requires manual transition
225 description => "use page/index.mdwn source files",
232 description => "enable Discussion pages?",
238 default => gettext("Discussion"),
239 description => "name of Discussion pages",
246 description => "only send cookies over SSL connections?",
254 description => "extension to use for new pages",
255 safe => 0, # not sanitized
261 description => "extension to use for html files",
262 safe => 0, # not sanitized
268 description => "strftime format string to display date",
276 example => "en_US.UTF-8",
277 description => "UTF-8 locale to use",
286 description => "put user pages below specified page",
293 description => "how many backlinks to show before hiding excess (0 to show all)",
300 description => "attempt to hardlink source files? (optimisation for large files)",
302 safe => 0, # paranoia
308 description => "force ikiwiki to use a particular umask",
310 safe => 0, # paranoia
315 example => "ikiwiki",
316 description => "group for wrappers to run in",
318 safe => 0, # paranoia
324 example => "$ENV{HOME}/.ikiwiki/",
325 description => "extra library and plugin directory",
327 safe => 0, # directory
333 description => "environment variables",
334 safe => 0, # paranoia
341 description => "regexp of source files to ignore",
346 wiki_file_prune_regexps => {
348 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
349 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
350 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
351 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
352 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
353 description => "regexps of source files to ignore",
359 description => "specifies the characters that are allowed in source filenames",
360 default => "-[:alnum:]+/.:_",
364 wiki_file_regexp => {
366 description => "regexp of legal source files",
370 web_commit_regexp => {
372 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
373 description => "regexp to parse web commits from logs",
380 description => "run as a cgi",
384 cgi_disable_uploads => {
387 description => "whether CGI should accept file uploads",
394 description => "run as a post-commit hook",
401 description => "running in rebuild mode",
408 description => "running in setup mode",
415 description => "running in clean mode",
422 description => "running in refresh mode",
429 description => "running in receive test mode",
436 description => "running in getctime mode",
443 description => "running in w3mmode",
450 description => "path to the .ikiwiki directory holding ikiwiki state",
457 description => "path to setup file",
461 allow_symlinks_before_srcdir => {
464 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
470 sub defaultconfig () {
473 foreach my $key (keys %s) {
474 push @ret, $key, $s{$key}->{default};
481 # locale stuff; avoid LC_ALL since it overrides everything
482 if (defined $ENV{LC_ALL}) {
483 $ENV{LANG} = $ENV{LC_ALL};
486 if (defined $config{locale}) {
487 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
488 $ENV{LANG}=$config{locale};
493 if (! defined $config{wiki_file_regexp}) {
494 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
497 if (ref $config{ENV} eq 'HASH') {
498 foreach my $val (keys %{$config{ENV}}) {
499 $ENV{$val}=$config{ENV}{$val};
503 if ($config{w3mmode}) {
504 eval q{use Cwd q{abs_path}};
506 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
507 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
508 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
509 unless $config{cgiurl} =~ m!file:///!;
510 $config{url}="file://".$config{destdir};
513 if ($config{cgi} && ! length $config{url}) {
514 error(gettext("Must specify url to wiki with --url when using --cgi"));
517 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
518 unless exists $config{wikistatedir} && defined $config{wikistatedir};
520 if (defined $config{umask}) {
521 umask(possibly_foolish_untaint($config{umask}));
524 run_hooks(checkconfig => sub { shift->() });
532 foreach my $dir (@INC, $config{libdir}) {
533 next unless defined $dir && length $dir;
534 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
535 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
539 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
540 next unless defined $dir && length $dir;
541 foreach my $file (glob("$dir/plugins/*")) {
542 $ret{basename($file)}=1 if -x $file;
550 if (defined $config{libdir} && length $config{libdir}) {
551 unshift @INC, possibly_foolish_untaint($config{libdir});
554 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
559 if (exists $hooks{rcs}) {
560 error(gettext("cannot use multiple rcs plugins"));
562 loadplugin($config{rcs});
564 if (! exists $hooks{rcs}) {
568 run_hooks(getopt => sub { shift->() });
569 if (grep /^-/, @ARGV) {
570 print STDERR "Unknown option (or missing parameter): $_\n"
571 foreach grep /^-/, @ARGV;
581 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
583 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
584 "$installdir/lib/ikiwiki") {
585 if (defined $dir && -x "$dir/plugins/$plugin") {
586 eval { require IkiWiki::Plugin::external };
589 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
591 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
592 $loaded_plugins{$plugin}=1;
597 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
600 error("Failed to load plugin $mod: $@");
602 $loaded_plugins{$plugin}=1;
609 log_message('err' => $message) if $config{syslog};
610 if (defined $cleaner) {
617 return unless $config{verbose};
618 return log_message(debug => @_);
622 sub log_message ($$) {
625 if ($config{syslog}) {
628 Sys::Syslog::setlogsock('unix');
629 Sys::Syslog::openlog('ikiwiki', '', 'user');
633 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
636 elsif (! $config{cgi}) {
640 return print STDERR "@_\n";
644 sub possibly_foolish_untaint ($) {
646 my ($untainted)=$tainted=~/(.*)/s;
666 return exists $pagesources{$page} &&
667 $pagesources{$page} =~ /\._([^.]+)$/;
673 if ($file =~ /\.([^.]+)$/) {
674 return $1 if exists $hooks{htmlize}{$1};
676 my $base=basename($file);
677 if (exists $hooks{htmlize}{$base} &&
678 $hooks{htmlize}{$base}{noextension}) {
689 if (exists $pagename_cache{$file}) {
690 return $pagename_cache{$file};
693 my $type=pagetype($file);
695 $page=~s/\Q.$type\E*$//
696 if defined $type && !$hooks{htmlize}{$type}{keepextension}
697 && !$hooks{htmlize}{$type}{noextension};
698 if ($config{indexpages} && $page=~/(.*)\/index$/) {
702 $pagename_cache{$file} = $page;
706 sub newpagefile ($$) {
710 if (! $config{indexpages} || $page eq 'index') {
711 return $page.".".$type;
714 return $page."/index.".$type;
718 sub targetpage ($$;$) {
723 if (defined $filename) {
724 return $page."/".$filename.".".$ext;
726 elsif (! $config{usedirs} || $page eq 'index') {
727 return $page.".".$ext;
730 return $page."/index.".$ext;
737 return targetpage($page, $config{htmlext});
744 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
745 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
746 return "$dir/$file", stat(_) if -e "$dir/$file";
748 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
753 return (srcfile_stat(@_))[0];
756 sub add_underlay ($) {
760 $dir="$config{underlaydirbase}/$dir";
763 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
764 unshift @{$config{underlaydirs}}, $dir;
770 sub readfile ($;$$) {
776 error("cannot read a symlink ($file)");
780 open (my $in, "<", $file) || error("failed to read $file: $!");
781 binmode($in) if ($binary);
782 return \*$in if $wantfd;
784 # check for invalid utf-8, and toss it back to avoid crashes
785 if (! utf8::valid($ret)) {
786 $ret=encode_utf8($ret);
788 close $in || error("failed to read $file: $!");
792 sub prep_writefile ($$) {
797 while (length $test) {
798 if (-l "$destdir/$test") {
799 error("cannot write to a symlink ($test)");
801 $test=dirname($test);
804 my $dir=dirname("$destdir/$file");
807 foreach my $s (split(m!/+!, $dir)) {
810 mkdir($d) || error("failed to create directory $d: $!");
818 sub writefile ($$$;$$) {
819 my $file=shift; # can include subdirs
820 my $destdir=shift; # directory to put file in
825 prep_writefile($file, $destdir);
827 my $newfile="$destdir/$file.ikiwiki-new";
829 error("cannot write to a symlink ($newfile)");
832 my $cleanup = sub { unlink($newfile) };
833 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
834 binmode($out) if ($binary);
836 $writer->(\*$out, $cleanup);
839 print $out $content or error("failed writing to $newfile: $!", $cleanup);
841 close $out || error("failed saving $newfile: $!", $cleanup);
842 rename($newfile, "$destdir/$file") ||
843 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
849 sub will_render ($$;$) {
854 # Important security check.
855 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
856 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
857 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
860 if (! $clear || $cleared{$page}) {
861 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
864 foreach my $old (@{$renderedfiles{$page}}) {
865 delete $destsources{$old};
867 $renderedfiles{$page}=[$dest];
870 $destsources{$dest}=$page;
880 if ($link=~s/^\/+//) {
888 $l.="/" if length $l;
891 if (exists $pagesources{$l}) {
894 elsif (exists $pagecase{lc $l}) {
895 return $pagecase{lc $l};
897 } while $cwd=~s{/?[^/]+$}{};
899 if (length $config{userdir}) {
900 my $l = "$config{userdir}/".lc($link);
901 if (exists $pagesources{$l}) {
904 elsif (exists $pagecase{lc $l}) {
905 return $pagecase{lc $l};
909 #print STDERR "warning: page $page, broken link: $link\n";
913 sub isinlinableimage ($) {
916 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
919 sub pagetitle ($;$) {
924 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
927 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
935 # support use w/o %config set
936 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
937 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
943 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
944 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
951 my $cgiurl=$config{cgiurl};
952 if (exists $params{cgiurl}) {
953 $cgiurl=$params{cgiurl};
954 delete $params{cgiurl};
957 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
963 return "$config{url}/" if ! defined $page;
965 $page=htmlpage($page);
967 $page=~s/[^\/]+\//..\//g;
972 # Work around very innefficient behavior in File::Spec if abs2rel
973 # is passed two relative paths. It's much faster if paths are
974 # absolute! (Debian bug #376658; fixed in debian unstable now)
979 my $ret=File::Spec->abs2rel($path, $base);
980 $ret=~s/^// if defined $ret;
984 sub displaytime ($;$) {
985 # Plugins can override this function to mark up the time to
987 return '<span class="date">'.formattime(@_).'</span>';
990 sub formattime ($;$) {
991 # Plugins can override this function to format the time.
994 if (! defined $format) {
995 $format=$config{timeformat};
998 # strftime doesn't know about encodings, so make sure
999 # its output is properly treated as utf8
1000 return decode_utf8(POSIX::strftime($format, localtime($time)));
1003 sub beautify_urlpath ($) {
1006 # Ensure url is not an empty link, and if necessary,
1007 # add ./ to avoid colon confusion.
1008 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1012 if ($config{usedirs}) {
1013 $url =~ s!/index.$config{htmlext}$!/!;
1025 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1028 if (! $destsources{$to}) {
1033 return $config{url}.beautify_urlpath("/".$to);
1036 my $link = abs2rel($to, dirname(htmlpage($from)));
1038 return beautify_urlpath($link);
1041 sub htmllink ($$$;@) {
1042 my $lpage=shift; # the page doing the linking
1043 my $page=shift; # the page that will contain the link (different for inline)
1050 if (! $opts{forcesubpage}) {
1051 $bestlink=bestlink($lpage, $link);
1054 $bestlink="$lpage/".lc($link);
1058 if (defined $opts{linktext}) {
1059 $linktext=$opts{linktext};
1062 $linktext=pagetitle(basename($link));
1065 return "<span class=\"selflink\">$linktext</span>"
1066 if length $bestlink && $page eq $bestlink &&
1067 ! defined $opts{anchor};
1069 if (! $destsources{$bestlink}) {
1070 $bestlink=htmlpage($bestlink);
1072 if (! $destsources{$bestlink}) {
1073 return $linktext unless length $config{cgiurl};
1074 return "<span class=\"createlink\"><a href=\"".
1080 "\" rel=\"nofollow\">?</a>$linktext</span>"
1084 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1085 $bestlink=beautify_urlpath($bestlink);
1087 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1088 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1091 if (defined $opts{anchor}) {
1092 $bestlink.="#".$opts{anchor};
1096 foreach my $attr (qw{rel class title}) {
1097 if (defined $opts{$attr}) {
1098 push @attrs, " $attr=\"$opts{$attr}\"";
1102 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1107 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1110 sub openiduser ($) {
1113 if ($user =~ m!^https?://! &&
1114 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1117 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1118 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1121 # backcompat with old version
1122 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1123 $display=$oid->display;
1126 # Convert "user.somehost.com" to "user [somehost.com]"
1127 # (also "user.somehost.co.uk")
1128 if ($display !~ /\[/) {
1129 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1131 # Convert "http://somehost.com/user" to "user [somehost.com]".
1132 # (also "https://somehost.com/user/")
1133 if ($display !~ /\[/) {
1134 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1136 $display=~s!^https?://!!; # make sure this is removed
1137 eval q{use CGI 'escapeHTML'};
1139 return escapeHTML($display);
1144 sub htmlize ($$$$) {
1150 my $oneline = $content !~ /\n/;
1152 if (exists $hooks{htmlize}{$type}) {
1153 $content=$hooks{htmlize}{$type}{call}->(
1155 content => $content,
1159 error("htmlization of $type not supported");
1162 run_hooks(sanitize => sub {
1165 destpage => $destpage,
1166 content => $content,
1171 # hack to get rid of enclosing junk added by markdown
1172 # and other htmlizers
1173 $content=~s/^<p>//i;
1174 $content=~s/<\/p>$//i;
1186 run_hooks(linkify => sub {
1189 destpage => $destpage,
1190 content => $content,
1198 our $preprocess_preview=0;
1199 sub preprocess ($$$;$$) {
1200 my $page=shift; # the page the data comes from
1201 my $destpage=shift; # the page the data will appear in (different for inline)
1206 # Using local because it needs to be set within any nested calls
1208 local $preprocess_preview=$preview if defined $preview;
1215 $params="" if ! defined $params;
1217 if (length $escape) {
1218 return "[[$prefix$command $params]]";
1220 elsif (exists $hooks{preprocess}{$command}) {
1221 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1222 # Note: preserve order of params, some plugins may
1223 # consider it significant.
1225 while ($params =~ m{
1226 (?:([-\w]+)=)? # 1: named parameter key?
1228 """(.*?)""" # 2: triple-quoted value
1230 "([^"]*?)" # 3: single-quoted value
1232 (\S+) # 4: unquoted value
1234 (?:\s+|$) # delimiter to next param
1244 elsif (defined $3) {
1247 elsif (defined $4) {
1252 push @params, $key, $val;
1255 push @params, $val, '';
1258 if ($preprocessing{$page}++ > 3) {
1259 # Avoid loops of preprocessed pages preprocessing
1260 # other pages that preprocess them, etc.
1261 return "[[!$command <span class=\"error\">".
1262 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1263 $page, $preprocessing{$page}).
1269 $hooks{preprocess}{$command}{call}->(
1272 destpage => $destpage,
1273 preview => $preprocess_preview,
1279 $ret="[[!$command <span class=\"error\">".
1280 gettext("Error").": $error"."</span>]]";
1284 # use void context during scan pass
1286 $hooks{preprocess}{$command}{call}->(
1289 destpage => $destpage,
1290 preview => $preprocess_preview,
1295 $preprocessing{$page}--;
1299 return "[[$prefix$command $params]]";
1304 if ($config{prefix_directives}) {
1307 \[\[(!) # directive open; 2: prefix
1308 ([-\w]+) # 3: command
1309 ( # 4: the parameters..
1310 \s+ # Must have space if parameters present
1312 (?:[-\w]+=)? # named parameter key?
1314 """.*?""" # triple-quoted value
1316 "[^"]*?" # single-quoted value
1318 [^"\s\]]+ # unquoted value
1320 \s* # whitespace or end
1323 *)? # 0 or more parameters
1324 \]\] # directive closed
1330 \[\[(!?) # directive open; 2: optional prefix
1331 ([-\w]+) # 3: command
1333 ( # 4: the parameters..
1335 (?:[-\w]+=)? # named parameter key?
1337 """.*?""" # triple-quoted value
1339 "[^"]*?" # single-quoted value
1341 [^"\s\]]+ # unquoted value
1343 \s* # whitespace or end
1346 *) # 0 or more parameters
1347 \]\] # directive closed
1351 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1360 run_hooks(filter => sub {
1361 $content=shift->(page => $page, destpage => $destpage,
1362 content => $content);
1369 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1372 sub check_canedit ($$$;$) {
1379 run_hooks(canedit => sub {
1380 return if defined $canedit;
1381 my $ret=shift->($page, $q, $session);
1386 elsif (ref $ret eq 'CODE') {
1387 $ret->() unless $nonfatal;
1390 elsif (defined $ret) {
1391 error($ret) unless $nonfatal;
1396 return defined $canedit ? $canedit : 1;
1399 sub check_content (@) {
1402 return 1 if ! exists $hooks{checkcontent}; # optimisation
1404 if (exists $pagesources{$params{page}}) {
1406 my %old=map { $_ => 1 }
1407 split("\n", readfile(srcfile($pagesources{$params{page}})));
1408 foreach my $line (split("\n", $params{content})) {
1409 push @diff, $line if ! exists $old{$line};
1411 $params{diff}=join("\n", @diff);
1415 run_hooks(checkcontent => sub {
1416 return if defined $ok;
1417 my $ret=shift->(%params);
1422 elsif (ref $ret eq 'CODE') {
1423 $ret->() unless $params{nonfatal};
1426 elsif (defined $ret) {
1427 error($ret) unless $params{nonfatal};
1433 return defined $ok ? $ok : 1;
1439 # Take an exclusive lock on the wiki to prevent multiple concurrent
1440 # run issues. The lock will be dropped on program exit.
1441 if (! -d $config{wikistatedir}) {
1442 mkdir($config{wikistatedir});
1444 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1445 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1446 if (! flock($wikilock, 2)) { # LOCK_EX
1447 error("failed to get lock");
1453 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1454 return close($wikilock) if $wikilock;
1460 sub commit_hook_enabled () {
1461 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1462 error("cannot write to $config{wikistatedir}/commitlock: $!");
1463 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1464 close($commitlock) || error("failed closing commitlock: $!");
1467 close($commitlock) || error("failed closing commitlock: $!");
1471 sub disable_commit_hook () {
1472 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1473 error("cannot write to $config{wikistatedir}/commitlock: $!");
1474 if (! flock($commitlock, 2)) { # LOCK_EX
1475 error("failed to get commit lock");
1480 sub enable_commit_hook () {
1481 return close($commitlock) if $commitlock;
1486 %oldrenderedfiles=%pagectime=();
1487 if (! $config{rebuild}) {
1488 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1489 %destsources=%renderedfiles=%pagecase=%pagestate=
1493 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1494 if (-e "$config{wikistatedir}/index") {
1495 system("ikiwiki-transition", "indexdb", $config{srcdir});
1496 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1503 my $index=Storable::fd_retrieve($in);
1504 if (! defined $index) {
1509 if (exists $index->{version} && ! ref $index->{version}) {
1510 $pages=$index->{page};
1511 %wikistate=%{$index->{state}};
1518 foreach my $src (keys %$pages) {
1519 my $d=$pages->{$src};
1520 my $page=pagename($src);
1521 $pagectime{$page}=$d->{ctime};
1522 if (! $config{rebuild}) {
1523 $pagesources{$page}=$src;
1524 $pagemtime{$page}=$d->{mtime};
1525 $renderedfiles{$page}=$d->{dest};
1526 if (exists $d->{links} && ref $d->{links}) {
1527 $links{$page}=$d->{links};
1528 $oldlinks{$page}=[@{$d->{links}}];
1530 if (ref $d->{depends_simple} eq 'ARRAY') {
1532 $depends_simple{$page}={
1533 map { $_ => 1 } @{$d->{depends_simple}}
1536 elsif (exists $d->{depends_simple}) {
1537 $depends_simple{$page}=$d->{depends_simple};
1539 if (exists $d->{dependslist}) {
1542 map { $_ => $DEPEND_CONTENT }
1543 @{$d->{dependslist}}
1546 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1548 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1550 elsif (exists $d->{depends}) {
1551 $depends{$page}=$d->{depends};
1553 if (exists $d->{state}) {
1554 $pagestate{$page}=$d->{state};
1557 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1559 foreach my $page (keys %pagesources) {
1560 $pagecase{lc $page}=$page;
1562 foreach my $page (keys %renderedfiles) {
1563 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1569 run_hooks(savestate => sub { shift->() });
1572 foreach my $type (keys %hooks) {
1573 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1575 my @hookids=keys %hookids;
1577 if (! -d $config{wikistatedir}) {
1578 mkdir($config{wikistatedir});
1580 my $newfile="$config{wikistatedir}/indexdb.new";
1581 my $cleanup = sub { unlink($newfile) };
1582 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1585 foreach my $page (keys %pagemtime) {
1586 next unless $pagemtime{$page};
1587 my $src=$pagesources{$page};
1589 $index{page}{$src}={
1590 ctime => $pagectime{$page},
1591 mtime => $pagemtime{$page},
1592 dest => $renderedfiles{$page},
1593 links => $links{$page},
1596 if (exists $depends{$page}) {
1597 $index{page}{$src}{depends} = $depends{$page};
1600 if (exists $depends_simple{$page}) {
1601 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1604 if (exists $pagestate{$page}) {
1605 foreach my $id (@hookids) {
1606 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1607 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1614 foreach my $id (@hookids) {
1615 foreach my $key (keys %{$wikistate{$id}}) {
1616 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1620 $index{version}="3";
1621 my $ret=Storable::nstore_fd(\%index, $out);
1622 return if ! defined $ret || ! $ret;
1623 close $out || error("failed saving to $newfile: $!", $cleanup);
1624 rename($newfile, "$config{wikistatedir}/indexdb") ||
1625 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1630 sub template_file ($) {
1633 foreach my $dir ($config{templatedir}, @{$config{templatedirs}},
1634 "$installdir/share/ikiwiki/templates") {
1635 return "$dir/$template" if -e "$dir/$template";
1640 sub template_params (@) {
1641 my $filename=template_file(shift);
1643 if (! defined $filename) {
1644 return if wantarray;
1650 my $text_ref = shift;
1651 ${$text_ref} = decode_utf8(${$text_ref});
1653 filename => $filename,
1654 loop_context_vars => 1,
1655 die_on_bad_params => 0,
1658 return wantarray ? @ret : {@ret};
1661 sub template ($;@) {
1662 require HTML::Template;
1663 return HTML::Template->new(template_params(@_));
1666 sub misctemplate ($$;@) {
1670 my $template=template("misc.tmpl");
1673 indexlink => indexlink(),
1674 wikiname => $config{wikiname},
1675 pagebody => $pagebody,
1676 baseurl => baseurl(),
1679 run_hooks(pagetemplate => sub {
1680 shift->(page => "", destpage => "", template => $template);
1682 return $template->output;
1688 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1689 error 'hook requires type, call, and id parameters';
1692 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1694 $hooks{$param{type}}{$param{id}}=\%param;
1698 sub run_hooks ($$) {
1699 # Calls the given sub for each hook of the given type,
1700 # passing it the hook function to call.
1704 if (exists $hooks{$type}) {
1705 my (@first, @middle, @last);
1706 foreach my $id (keys %{$hooks{$type}}) {
1707 if ($hooks{$type}{$id}{first}) {
1710 elsif ($hooks{$type}{$id}{last}) {
1717 foreach my $id (@first, @middle, @last) {
1718 $sub->($hooks{$type}{$id}{call});
1726 $hooks{rcs}{rcs_update}{call}->(@_);
1729 sub rcs_prepedit ($) {
1730 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1733 sub rcs_commit ($$$;$$) {
1734 $hooks{rcs}{rcs_commit}{call}->(@_);
1737 sub rcs_commit_staged ($$$) {
1738 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1742 $hooks{rcs}{rcs_add}{call}->(@_);
1745 sub rcs_remove ($) {
1746 $hooks{rcs}{rcs_remove}{call}->(@_);
1749 sub rcs_rename ($$) {
1750 $hooks{rcs}{rcs_rename}{call}->(@_);
1753 sub rcs_recentchanges ($) {
1754 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1758 $hooks{rcs}{rcs_diff}{call}->(@_);
1761 sub rcs_getctime ($) {
1762 $hooks{rcs}{rcs_getctime}{call}->(@_);
1765 sub rcs_receive () {
1766 $hooks{rcs}{rcs_receive}{call}->();
1769 sub add_depends ($$;$) {
1772 my $deptype=shift || $DEPEND_CONTENT;
1774 # Is the pagespec a simple page name?
1775 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1776 $pagespec !~ /[\s*?()!]/) {
1777 $depends_simple{$page}{lc $pagespec} |= $deptype;
1781 # Add explicit dependencies for influences.
1782 my $sub=pagespec_translate($pagespec);
1784 foreach my $p (keys %pagesources) {
1785 my $r=$sub->($p, location => $page);
1786 my $i=$r->influences;
1787 foreach my $k (keys %$i) {
1788 $depends_simple{$page}{lc $k} |= $i->{$k};
1790 last if $r->influences_static;
1793 $depends{$page}{$pagespec} |= $deptype;
1799 foreach my $type (@_) {
1800 if ($type eq 'presence') {
1801 $deptype |= $DEPEND_PRESENCE;
1803 elsif ($type eq 'links') {
1804 $deptype |= $DEPEND_LINKS;
1806 elsif ($type eq 'content') {
1807 $deptype |= $DEPEND_CONTENT;
1813 sub file_pruned ($;$) {
1817 $file=File::Spec->canonpath($file);
1818 my $base=File::Spec->canonpath(shift);
1819 return if $file eq $base;
1820 $file =~ s#^\Q$base\E/+##;
1823 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1824 return $file =~ m/$regexp/;
1827 sub define_gettext () {
1828 # If translation is needed, redefine the gettext function to do it.
1829 # Otherwise, it becomes a quick no-op.
1832 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1833 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1834 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1836 $gettext_obj=eval q{
1837 use Locale::gettext q{textdomain};
1838 Locale::gettext->domain('ikiwiki')
1843 no warnings 'redefine';
1845 $getobj->() if $getobj;
1847 $gettext_obj->get(shift);
1854 $getobj->() if $getobj;
1856 $gettext_obj->nget(@_);
1859 return ($_[2] == 1 ? $_[0] : $_[1])
1877 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1881 # Injects a new function into the symbol table to replace an
1882 # exported function.
1885 # This is deep ugly perl foo, beware.
1888 if (! defined $params{parent}) {
1889 $params{parent}='::';
1890 $params{old}=\&{$params{name}};
1891 $params{name}=~s/.*:://;
1893 my $parent=$params{parent};
1894 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1895 $ns = $params{parent} . $ns;
1896 inject(%params, parent => $ns) unless $ns eq '::main::';
1897 *{$ns . $params{name}} = $params{call}
1898 if exists ${$ns}{$params{name}} &&
1899 \&{${$ns}{$params{name}}} == $params{old};
1909 push @{$links{$page}}, $link
1910 unless grep { $_ eq $link } @{$links{$page}};
1913 sub pagespec_translate ($) {
1916 # Convert spec to perl code.
1920 \s* # ignore whitespace
1921 ( # 1: match a single word
1928 \w+\([^\)]*\) # command(params)
1930 [^\s()]+ # any other text
1932 \s* # ignore whitespace
1935 if (lc $word eq 'and') {
1938 elsif (lc $word eq 'or') {
1941 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1944 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1945 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1947 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
1950 push @data, qq{unknown function in pagespec "$word"};
1951 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
1956 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
1960 if (! length $code) {
1961 $code="IkiWiki::FailReason->new('empty pagespec')";
1965 return eval 'sub { my $page=shift; '.$code.' }';
1968 sub pagespec_match ($$;@) {
1973 # Backwards compatability with old calling convention.
1975 unshift @params, 'location';
1978 my $sub=pagespec_translate($spec);
1979 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
1980 if $@ || ! defined $sub;
1981 return $sub->($page, @params);
1984 sub pagespec_match_list ($$;@) {
1989 # Backwards compatability with old calling convention.
1991 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
1992 $params{list}=$page;
1993 $page=$params{location}; # ugh!
1996 my $sub=pagespec_translate($pagespec);
1997 error "syntax error in pagespec \"$pagespec\""
1998 if $@ || ! defined $sub;
2001 if (exists $params{list}) {
2002 @candidates=exists $params{filter}
2003 ? grep { ! $params{filter}->($_) } @{$params{list}}
2007 @candidates=exists $params{filter}
2008 ? grep { ! $params{filter}->($_) } keys %pagesources
2009 : keys %pagesources;
2012 if (defined $params{sort}) {
2014 if ($params{sort} eq 'title') {
2015 $f=sub { pagetitle(basename($a)) cmp pagetitle(basename($b)) };
2017 elsif ($params{sort} eq 'title_natural') {
2018 eval q{use Sort::Naturally};
2020 error(gettext("Sort::Naturally needed for title_natural sort"));
2022 $f=sub { Sort::Naturally::ncmp(pagetitle(basename($a)), pagetitle(basename($b))) };
2024 elsif ($params{sort} eq 'mtime') {
2025 $f=sub { $pagemtime{$b} <=> $pagemtime{$a} };
2027 elsif ($params{sort} eq 'age') {
2028 $f=sub { $pagectime{$b} <=> $pagectime{$a} };
2031 error sprintf(gettext("unknown sort type %s"), $params{sort});
2033 @candidates = sort { &$f } @candidates;
2036 @candidates=reverse(@candidates) if $params{reverse};
2038 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2040 # clear params, remainder is passed to pagespec
2041 my $num=$params{num};
2042 delete @params{qw{num deptype reverse sort filter list}};
2047 my $accum=IkiWiki::SuccessReason->new();
2048 foreach my $p (@candidates) {
2049 my $r=$sub->($p, %params, location => $page);
2050 error(sprintf(gettext("cannot match pages: %s"), $r))
2051 if $r->isa("IkiWiki::ErrorReason");
2055 last if defined $num && ++$count == $num;
2059 # Add simple dependencies for accumulated influences.
2060 my $i=$accum->influences;
2061 foreach my $k (keys %$i) {
2062 $depends_simple{$page}{lc $k} |= $i->{$k};
2068 sub pagespec_valid ($) {
2071 my $sub=pagespec_translate($spec);
2076 my $re=quotemeta(shift);
2082 package IkiWiki::FailReason;
2085 '""' => sub { $_[0][0] },
2087 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2088 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2089 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2093 our @ISA = 'IkiWiki::SuccessReason';
2095 package IkiWiki::SuccessReason;
2098 '""' => sub { $_[0][0] },
2100 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2101 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2102 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2109 return bless [$value, {@_}], $class;
2114 $this->[1]={@_} if @_;
2115 my %i=%{$this->[1]};
2120 sub influences_static {
2121 return ! $_[0][1]->{""};
2124 sub merge_influences {
2129 if (! $anded || (($this || %{$this->[1]}) &&
2130 ($other || %{$other->[1]}))) {
2131 foreach my $influence (keys %{$other->[1]}) {
2132 $this->[1]{$influence} |= $other->[1]{$influence};
2141 package IkiWiki::ErrorReason;
2143 our @ISA = 'IkiWiki::FailReason';
2145 package IkiWiki::PageSpec;
2151 if ($path =~ m!^\./!) {
2152 $from=~s#/?[^/]+$## if defined $from;
2154 $path="$from/$path" if length $from;
2160 sub match_glob ($$;@) {
2165 $glob=derel($glob, $params{location});
2167 my $regexp=IkiWiki::glob2re($glob);
2168 if ($page=~/^$regexp$/i) {
2169 if (! IkiWiki::isinternal($page) || $params{internal}) {
2170 return IkiWiki::SuccessReason->new("$glob matches $page");
2173 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2177 return IkiWiki::FailReason->new("$glob does not match $page");
2181 sub match_internal ($$;@) {
2182 return match_glob($_[0], $_[1], @_, internal => 1)
2185 sub match_link ($$;@) {
2190 $link=derel($link, $params{location});
2191 my $from=exists $params{location} ? $params{location} : '';
2193 my $links = $IkiWiki::links{$page};
2194 return IkiWiki::FailReason->new("$page has no links", "" => 1)
2195 unless $links && @{$links};
2196 my $bestlink = IkiWiki::bestlink($from, $link);
2197 foreach my $p (@{$links}) {
2198 if (length $bestlink) {
2199 return IkiWiki::SuccessReason->new("$page links to $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2200 if $bestlink eq IkiWiki::bestlink($page, $p);
2203 return IkiWiki::SuccessReason->new("$page links to page $p matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2204 if match_glob($p, $link, %params);
2205 my ($p_rel)=$p=~/^\/?(.*)/;
2207 return IkiWiki::SuccessReason->new("$page links to page $p_rel matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2208 if match_glob($p_rel, $link, %params);
2211 return IkiWiki::FailReason->new("$page does not link to $link", "" => 1);
2214 sub match_backlink ($$;@) {
2215 my $ret=match_link($_[1], $_[0], @_);
2216 $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2220 sub match_created_before ($$;@) {
2225 $testpage=derel($testpage, $params{location});
2227 if (exists $IkiWiki::pagectime{$testpage}) {
2228 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2229 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2232 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2236 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2240 sub match_created_after ($$;@) {
2245 $testpage=derel($testpage, $params{location});
2247 if (exists $IkiWiki::pagectime{$testpage}) {
2248 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2249 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2252 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2256 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2260 sub match_creation_day ($$;@) {
2261 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2262 return IkiWiki::SuccessReason->new('creation_day matched');
2265 return IkiWiki::FailReason->new('creation_day did not match');
2269 sub match_creation_month ($$;@) {
2270 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2271 return IkiWiki::SuccessReason->new('creation_month matched');
2274 return IkiWiki::FailReason->new('creation_month did not match');
2278 sub match_creation_year ($$;@) {
2279 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2280 return IkiWiki::SuccessReason->new('creation_year matched');
2283 return IkiWiki::FailReason->new('creation_year did not match');
2287 sub match_user ($$;@) {
2292 my $regexp=IkiWiki::glob2re($user);
2294 if (! exists $params{user}) {
2295 return IkiWiki::ErrorReason->new("no user specified");
2298 if (defined $params{user} && $params{user}=~/^$regexp$/i) {
2299 return IkiWiki::SuccessReason->new("user is $user");
2301 elsif (! defined $params{user}) {
2302 return IkiWiki::FailReason->new("not logged in");
2305 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2309 sub match_admin ($$;@) {
2314 if (! exists $params{user}) {
2315 return IkiWiki::ErrorReason->new("no user specified");
2318 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2319 return IkiWiki::SuccessReason->new("user is an admin");
2321 elsif (! defined $params{user}) {
2322 return IkiWiki::FailReason->new("not logged in");
2325 return IkiWiki::FailReason->new("user is not an admin");
2329 sub match_ip ($$;@) {
2334 if (! exists $params{ip}) {
2335 return IkiWiki::ErrorReason->new("no IP specified");
2338 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2339 return IkiWiki::SuccessReason->new("IP is $ip");
2342 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");