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
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 if (my @stat=srcfile_stat(@_)) {
753 sub add_underlay ($) {
757 $dir="$config{underlaydirbase}/$dir";
760 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
761 unshift @{$config{underlaydirs}}, $dir;
767 sub readfile ($;$$) {
773 error("cannot read a symlink ($file)");
777 open (my $in, "<", $file) || error("failed to read $file: $!");
778 binmode($in) if ($binary);
779 return \*$in if $wantfd;
781 # check for invalid utf-8, and toss it back to avoid crashes
782 if (! utf8::valid($ret)) {
783 $ret=encode_utf8($ret);
785 close $in || error("failed to read $file: $!");
789 sub prep_writefile ($$) {
794 while (length $test) {
795 if (-l "$destdir/$test") {
796 error("cannot write to a symlink ($test)");
798 $test=dirname($test);
801 my $dir=dirname("$destdir/$file");
804 foreach my $s (split(m!/+!, $dir)) {
807 mkdir($d) || error("failed to create directory $d: $!");
815 sub writefile ($$$;$$) {
816 my $file=shift; # can include subdirs
817 my $destdir=shift; # directory to put file in
822 prep_writefile($file, $destdir);
824 my $newfile="$destdir/$file.ikiwiki-new";
826 error("cannot write to a symlink ($newfile)");
829 my $cleanup = sub { unlink($newfile) };
830 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
831 binmode($out) if ($binary);
833 $writer->(\*$out, $cleanup);
836 print $out $content or error("failed writing to $newfile: $!", $cleanup);
838 close $out || error("failed saving $newfile: $!", $cleanup);
839 rename($newfile, "$destdir/$file") ||
840 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
846 sub will_render ($$;$) {
851 # Important security check.
852 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
853 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
854 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
857 if (! $clear || $cleared{$page}) {
858 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
861 foreach my $old (@{$renderedfiles{$page}}) {
862 delete $destsources{$old};
864 $renderedfiles{$page}=[$dest];
867 $destsources{$dest}=$page;
877 if ($link=~s/^\/+//) {
885 $l.="/" if length $l;
888 if (exists $pagesources{$l}) {
891 elsif (exists $pagecase{lc $l}) {
892 return $pagecase{lc $l};
894 } while $cwd=~s{/?[^/]+$}{};
896 if (length $config{userdir}) {
897 my $l = "$config{userdir}/".lc($link);
898 if (exists $pagesources{$l}) {
901 elsif (exists $pagecase{lc $l}) {
902 return $pagecase{lc $l};
906 #print STDERR "warning: page $page, broken link: $link\n";
910 sub isinlinableimage ($) {
913 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
916 sub pagetitle ($;$) {
921 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
924 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
932 # support use w/o %config set
933 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
934 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
940 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
941 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
948 return $config{cgiurl}."?".
949 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
955 return "$config{url}/" if ! defined $page;
957 $page=htmlpage($page);
959 $page=~s/[^\/]+\//..\//g;
964 # Work around very innefficient behavior in File::Spec if abs2rel
965 # is passed two relative paths. It's much faster if paths are
966 # absolute! (Debian bug #376658; fixed in debian unstable now)
971 my $ret=File::Spec->abs2rel($path, $base);
972 $ret=~s/^// if defined $ret;
976 sub displaytime ($;$) {
977 # Plugins can override this function to mark up the time to
979 return '<span class="date">'.formattime(@_).'</span>';
982 sub formattime ($;$) {
983 # Plugins can override this function to format the time.
986 if (! defined $format) {
987 $format=$config{timeformat};
990 # strftime doesn't know about encodings, so make sure
991 # its output is properly treated as utf8
992 return decode_utf8(POSIX::strftime($format, localtime($time)));
995 sub beautify_urlpath ($) {
998 # Ensure url is not an empty link, and if necessary,
999 # add ./ to avoid colon confusion.
1000 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1004 if ($config{usedirs}) {
1005 $url =~ s!/index.$config{htmlext}$!/!;
1017 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1020 if (! $destsources{$to}) {
1025 return $config{url}.beautify_urlpath("/".$to);
1028 my $link = abs2rel($to, dirname(htmlpage($from)));
1030 return beautify_urlpath($link);
1033 sub htmllink ($$$;@) {
1034 my $lpage=shift; # the page doing the linking
1035 my $page=shift; # the page that will contain the link (different for inline)
1042 if (! $opts{forcesubpage}) {
1043 $bestlink=bestlink($lpage, $link);
1046 $bestlink="$lpage/".lc($link);
1050 if (defined $opts{linktext}) {
1051 $linktext=$opts{linktext};
1054 $linktext=pagetitle(basename($link));
1057 return "<span class=\"selflink\">$linktext</span>"
1058 if length $bestlink && $page eq $bestlink &&
1059 ! defined $opts{anchor};
1061 if (! $destsources{$bestlink}) {
1062 $bestlink=htmlpage($bestlink);
1064 if (! $destsources{$bestlink}) {
1065 return $linktext unless length $config{cgiurl};
1066 return "<span class=\"createlink\"><a href=\"".
1072 "\" rel=\"nofollow\">?</a>$linktext</span>"
1076 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1077 $bestlink=beautify_urlpath($bestlink);
1079 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1080 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1083 if (defined $opts{anchor}) {
1084 $bestlink.="#".$opts{anchor};
1088 foreach my $attr (qw{rel class title}) {
1089 if (defined $opts{$attr}) {
1090 push @attrs, " $attr=\"$opts{$attr}\"";
1094 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1097 sub openiduser ($) {
1100 if ($user =~ m!^https?://! &&
1101 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1104 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1105 # this works in at least 2.x
1106 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1109 # this only works in 1.x
1110 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1111 $display=$oid->display;
1114 # Convert "user.somehost.com" to "user [somehost.com]"
1115 # (also "user.somehost.co.uk")
1116 if ($display !~ /\[/) {
1117 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1119 # Convert "http://somehost.com/user" to "user [somehost.com]".
1120 # (also "https://somehost.com/user/")
1121 if ($display !~ /\[/) {
1122 $display=~s/^https?:\/\/(.+)\/([^\/]+)\/?$/$2 [$1]/;
1124 $display=~s!^https?://!!; # make sure this is removed
1125 eval q{use CGI 'escapeHTML'};
1127 return escapeHTML($display);
1135 my $oiduser=eval { openiduser($user) };
1136 if (defined $oiduser) {
1137 return "<a href=\"$user\">$oiduser</a>";
1140 eval q{use CGI 'escapeHTML'};
1143 return htmllink("", "", escapeHTML(
1144 length $config{userdir} ? $config{userdir}."/".$user : $user
1145 ), noimageinline => 1);
1149 sub htmlize ($$$$) {
1155 my $oneline = $content !~ /\n/;
1157 if (exists $hooks{htmlize}{$type}) {
1158 $content=$hooks{htmlize}{$type}{call}->(
1160 content => $content,
1164 error("htmlization of $type not supported");
1167 run_hooks(sanitize => sub {
1170 destpage => $destpage,
1171 content => $content,
1176 # hack to get rid of enclosing junk added by markdown
1177 # and other htmlizers
1178 $content=~s/^<p>//i;
1179 $content=~s/<\/p>$//i;
1191 run_hooks(linkify => sub {
1194 destpage => $destpage,
1195 content => $content,
1203 our $preprocess_preview=0;
1204 sub preprocess ($$$;$$) {
1205 my $page=shift; # the page the data comes from
1206 my $destpage=shift; # the page the data will appear in (different for inline)
1211 # Using local because it needs to be set within any nested calls
1213 local $preprocess_preview=$preview if defined $preview;
1220 $params="" if ! defined $params;
1222 if (length $escape) {
1223 return "[[$prefix$command $params]]";
1225 elsif (exists $hooks{preprocess}{$command}) {
1226 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1227 # Note: preserve order of params, some plugins may
1228 # consider it significant.
1230 while ($params =~ m{
1231 (?:([-\w]+)=)? # 1: named parameter key?
1233 """(.*?)""" # 2: triple-quoted value
1235 "([^"]+)" # 3: single-quoted value
1237 (\S+) # 4: unquoted value
1239 (?:\s+|$) # delimiter to next param
1249 elsif (defined $3) {
1252 elsif (defined $4) {
1257 push @params, $key, $val;
1260 push @params, $val, '';
1263 if ($preprocessing{$page}++ > 3) {
1264 # Avoid loops of preprocessed pages preprocessing
1265 # other pages that preprocess them, etc.
1266 return "[[!$command <span class=\"error\">".
1267 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1268 $page, $preprocessing{$page}).
1274 $hooks{preprocess}{$command}{call}->(
1277 destpage => $destpage,
1278 preview => $preprocess_preview,
1284 $ret="[[!$command <span class=\"error\">".
1285 gettext("Error").": $error"."</span>]]";
1289 # use void context during scan pass
1291 $hooks{preprocess}{$command}{call}->(
1294 destpage => $destpage,
1295 preview => $preprocess_preview,
1300 $preprocessing{$page}--;
1304 return "[[$prefix$command $params]]";
1309 if ($config{prefix_directives}) {
1312 \[\[(!) # directive open; 2: prefix
1313 ([-\w]+) # 3: command
1314 ( # 4: the parameters..
1315 \s+ # Must have space if parameters present
1317 (?:[-\w]+=)? # named parameter key?
1319 """.*?""" # triple-quoted value
1321 "[^"]+" # single-quoted value
1323 [^"\s\]]+ # unquoted value
1325 \s* # whitespace or end
1328 *)? # 0 or more parameters
1329 \]\] # directive closed
1335 \[\[(!?) # directive open; 2: optional prefix
1336 ([-\w]+) # 3: command
1338 ( # 4: the parameters..
1340 (?:[-\w]+=)? # named parameter key?
1342 """.*?""" # triple-quoted value
1344 "[^"]+" # single-quoted value
1346 [^"\s\]]+ # unquoted value
1348 \s* # whitespace or end
1351 *) # 0 or more parameters
1352 \]\] # directive closed
1356 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1365 run_hooks(filter => sub {
1366 $content=shift->(page => $page, destpage => $destpage,
1367 content => $content);
1374 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1377 sub check_canedit ($$$;$) {
1384 run_hooks(canedit => sub {
1385 return if defined $canedit;
1386 my $ret=shift->($page, $q, $session);
1391 elsif (ref $ret eq 'CODE') {
1392 $ret->() unless $nonfatal;
1395 elsif (defined $ret) {
1396 error($ret) unless $nonfatal;
1401 return defined $canedit ? $canedit : 1;
1404 sub check_content (@) {
1407 return 1 if ! exists $hooks{checkcontent}; # optimisation
1409 if (exists $pagesources{$params{page}}) {
1411 my %old=map { $_ => 1 }
1412 split("\n", readfile(srcfile($pagesources{$params{page}})));
1413 foreach my $line (split("\n", $params{content})) {
1414 push @diff, $line if ! exists $old{$line};
1416 $params{diff}=join("\n", @diff);
1420 run_hooks(checkcontent => sub {
1421 return if defined $ok;
1422 my $ret=shift->(%params);
1427 elsif (ref $ret eq 'CODE') {
1428 $ret->() unless $params{nonfatal};
1431 elsif (defined $ret) {
1432 error($ret) unless $params{nonfatal};
1438 return defined $ok ? $ok : 1;
1444 # Take an exclusive lock on the wiki to prevent multiple concurrent
1445 # run issues. The lock will be dropped on program exit.
1446 if (! -d $config{wikistatedir}) {
1447 mkdir($config{wikistatedir});
1449 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1450 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1451 if (! flock($wikilock, 2)) { # LOCK_EX
1452 error("failed to get lock");
1458 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1459 return close($wikilock) if $wikilock;
1465 sub commit_hook_enabled () {
1466 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1467 error("cannot write to $config{wikistatedir}/commitlock: $!");
1468 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1469 close($commitlock) || error("failed closing commitlock: $!");
1472 close($commitlock) || error("failed closing commitlock: $!");
1476 sub disable_commit_hook () {
1477 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1478 error("cannot write to $config{wikistatedir}/commitlock: $!");
1479 if (! flock($commitlock, 2)) { # LOCK_EX
1480 error("failed to get commit lock");
1485 sub enable_commit_hook () {
1486 return close($commitlock) if $commitlock;
1491 %oldrenderedfiles=%pagectime=();
1492 if (! $config{rebuild}) {
1493 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1494 %destsources=%renderedfiles=%pagecase=%pagestate=
1498 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1499 if (-e "$config{wikistatedir}/index") {
1500 system("ikiwiki-transition", "indexdb", $config{srcdir});
1501 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1508 my $index=Storable::fd_retrieve($in);
1509 if (! defined $index) {
1514 if (exists $index->{version} && ! ref $index->{version}) {
1515 $pages=$index->{page};
1516 %wikistate=%{$index->{state}};
1523 foreach my $src (keys %$pages) {
1524 my $d=$pages->{$src};
1525 my $page=pagename($src);
1526 $pagectime{$page}=$d->{ctime};
1527 if (! $config{rebuild}) {
1528 $pagesources{$page}=$src;
1529 $pagemtime{$page}=$d->{mtime};
1530 $renderedfiles{$page}=$d->{dest};
1531 if (exists $d->{links} && ref $d->{links}) {
1532 $links{$page}=$d->{links};
1533 $oldlinks{$page}=[@{$d->{links}}];
1535 if (ref $d->{depends_simple} eq 'ARRAY') {
1537 $depends_simple{$page}={
1538 map { $_ => 1 } @{$d->{depends_simple}}
1541 elsif (exists $d->{depends_simple}) {
1542 $depends_simple{$page}=$d->{depends_simple};
1544 if (exists $d->{dependslist}) {
1547 map { $_ => $DEPEND_CONTENT }
1548 @{$d->{dependslist}}
1551 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1553 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1555 elsif (exists $d->{depends}) {
1556 $depends{$page}=$d->{depends};
1558 if (exists $d->{state}) {
1559 $pagestate{$page}=$d->{state};
1562 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1564 foreach my $page (keys %pagesources) {
1565 $pagecase{lc $page}=$page;
1567 foreach my $page (keys %renderedfiles) {
1568 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1574 run_hooks(savestate => sub { shift->() });
1577 foreach my $type (keys %hooks) {
1578 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1580 my @hookids=keys %hookids;
1582 if (! -d $config{wikistatedir}) {
1583 mkdir($config{wikistatedir});
1585 my $newfile="$config{wikistatedir}/indexdb.new";
1586 my $cleanup = sub { unlink($newfile) };
1587 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1590 foreach my $page (keys %pagemtime) {
1591 next unless $pagemtime{$page};
1592 my $src=$pagesources{$page};
1594 $index{page}{$src}={
1595 ctime => $pagectime{$page},
1596 mtime => $pagemtime{$page},
1597 dest => $renderedfiles{$page},
1598 links => $links{$page},
1601 if (exists $depends{$page}) {
1602 $index{page}{$src}{depends} = $depends{$page};
1605 if (exists $depends_simple{$page}) {
1606 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1609 if (exists $pagestate{$page}) {
1610 foreach my $id (@hookids) {
1611 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1612 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1619 foreach my $id (@hookids) {
1620 foreach my $key (keys %{$wikistate{$id}}) {
1621 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1625 $index{version}="3";
1626 my $ret=Storable::nstore_fd(\%index, $out);
1627 return if ! defined $ret || ! $ret;
1628 close $out || error("failed saving to $newfile: $!", $cleanup);
1629 rename($newfile, "$config{wikistatedir}/indexdb") ||
1630 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1635 sub template_file ($) {
1638 foreach my $dir ($config{templatedir}, @{$config{templatedirs}},
1639 "$installdir/share/ikiwiki/templates") {
1640 return "$dir/$template" if -e "$dir/$template";
1645 sub template_params (@) {
1646 my $filename=template_file(shift);
1648 if (! defined $filename) {
1649 return if wantarray;
1655 my $text_ref = shift;
1656 ${$text_ref} = decode_utf8(${$text_ref});
1658 filename => $filename,
1659 loop_context_vars => 1,
1660 die_on_bad_params => 0,
1663 return wantarray ? @ret : {@ret};
1666 sub template ($;@) {
1667 require HTML::Template;
1668 return HTML::Template->new(template_params(@_));
1671 sub misctemplate ($$;@) {
1675 my $template=template("misc.tmpl");
1678 indexlink => indexlink(),
1679 wikiname => $config{wikiname},
1680 pagebody => $pagebody,
1681 baseurl => baseurl(),
1684 run_hooks(pagetemplate => sub {
1685 shift->(page => "", destpage => "", template => $template);
1687 return $template->output;
1693 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1694 error 'hook requires type, call, and id parameters';
1697 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1699 $hooks{$param{type}}{$param{id}}=\%param;
1703 sub run_hooks ($$) {
1704 # Calls the given sub for each hook of the given type,
1705 # passing it the hook function to call.
1709 if (exists $hooks{$type}) {
1710 my (@first, @middle, @last);
1711 foreach my $id (keys %{$hooks{$type}}) {
1712 if ($hooks{$type}{$id}{first}) {
1715 elsif ($hooks{$type}{$id}{last}) {
1722 foreach my $id (@first, @middle, @last) {
1723 $sub->($hooks{$type}{$id}{call});
1731 $hooks{rcs}{rcs_update}{call}->(@_);
1734 sub rcs_prepedit ($) {
1735 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1738 sub rcs_commit ($$$;$$) {
1739 $hooks{rcs}{rcs_commit}{call}->(@_);
1742 sub rcs_commit_staged ($$$) {
1743 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1747 $hooks{rcs}{rcs_add}{call}->(@_);
1750 sub rcs_remove ($) {
1751 $hooks{rcs}{rcs_remove}{call}->(@_);
1754 sub rcs_rename ($$) {
1755 $hooks{rcs}{rcs_rename}{call}->(@_);
1758 sub rcs_recentchanges ($) {
1759 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1763 $hooks{rcs}{rcs_diff}{call}->(@_);
1766 sub rcs_getctime ($) {
1767 $hooks{rcs}{rcs_getctime}{call}->(@_);
1770 sub rcs_receive () {
1771 $hooks{rcs}{rcs_receive}{call}->();
1774 sub add_depends ($$;$) {
1777 my $deptype=shift || $DEPEND_CONTENT;
1779 # Is the pagespec a simple page name?
1780 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1781 $pagespec !~ /[\s*?()!]/) {
1782 $depends_simple{$page}{lc $pagespec} |= $deptype;
1786 # Add explicit dependencies for influences.
1787 my $sub=pagespec_translate($pagespec);
1789 foreach my $p (keys %pagesources) {
1790 my $r=$sub->($p, location => $page);
1791 my $i=$r->influences;
1792 foreach my $k (keys %$i) {
1793 $depends_simple{$page}{lc $k} |= $i->{$k};
1795 last if $r->influences_static;
1798 $depends{$page}{$pagespec} |= $deptype;
1804 foreach my $type (@_) {
1805 if ($type eq 'presence') {
1806 $deptype |= $DEPEND_PRESENCE;
1808 elsif ($type eq 'links') {
1809 $deptype |= $DEPEND_LINKS;
1811 elsif ($type eq 'content') {
1812 $deptype |= $DEPEND_CONTENT;
1818 sub file_pruned ($;$) {
1822 $file=File::Spec->canonpath($file);
1823 my $base=File::Spec->canonpath(shift);
1824 return if $file eq $base;
1825 $file =~ s#^\Q$base\E/+##;
1828 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1829 return $file =~ m/$regexp/;
1832 sub define_gettext () {
1833 # If translation is needed, redefine the gettext function to do it.
1834 # Otherwise, it becomes a quick no-op.
1835 no warnings 'redefine';
1836 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1837 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1838 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1840 my $gettext_obj=eval q{
1841 use Locale::gettext q{textdomain};
1842 Locale::gettext->domain('ikiwiki')
1846 $gettext_obj->get(shift);
1854 *gettext=sub { return shift };
1866 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1870 # Injects a new function into the symbol table to replace an
1871 # exported function.
1874 # This is deep ugly perl foo, beware.
1877 if (! defined $params{parent}) {
1878 $params{parent}='::';
1879 $params{old}=\&{$params{name}};
1880 $params{name}=~s/.*:://;
1882 my $parent=$params{parent};
1883 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1884 $ns = $params{parent} . $ns;
1885 inject(%params, parent => $ns) unless $ns eq '::main::';
1886 *{$ns . $params{name}} = $params{call}
1887 if exists ${$ns}{$params{name}} &&
1888 \&{${$ns}{$params{name}}} == $params{old};
1898 push @{$links{$page}}, $link
1899 unless grep { $_ eq $link } @{$links{$page}};
1902 sub add_autofile ($) {
1904 my ($file,$page) = verify_src_file($addfile,$config{srcdir});
1906 push @autofiles, $file;
1910 sub pagespec_translate ($) {
1913 # Convert spec to perl code.
1917 \s* # ignore whitespace
1918 ( # 1: match a single word
1925 \w+\([^\)]*\) # command(params)
1927 [^\s()]+ # any other text
1929 \s* # ignore whitespace
1932 if (lc $word eq 'and') {
1935 elsif (lc $word eq 'or') {
1938 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1941 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1942 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1944 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
1947 push @data, qq{unknown function in pagespec "$word"};
1948 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
1953 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
1957 if (! length $code) {
1958 $code="IkiWiki::FailReason->new('empty pagespec')";
1962 return eval 'sub { my $page=shift; '.$code.' }';
1965 sub pagespec_match ($$;@) {
1970 # Backwards compatability with old calling convention.
1972 unshift @params, 'location';
1975 my $sub=pagespec_translate($spec);
1976 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
1977 if $@ || ! defined $sub;
1978 return $sub->($page, @params);
1981 sub pagespec_match_list ($$;@) {
1986 # Backwards compatability with old calling convention.
1988 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
1989 $params{list}=$page;
1990 $page=$params{location}; # ugh!
1993 my $sub=pagespec_translate($pagespec);
1994 error "syntax error in pagespec \"$pagespec\""
1995 if $@ || ! defined $sub;
1998 if (exists $params{list}) {
1999 @candidates=exists $params{filter}
2000 ? grep { ! $params{filter}->($_) } @{$params{list}}
2004 @candidates=exists $params{filter}
2005 ? grep { ! $params{filter}->($_) } keys %pagesources
2006 : keys %pagesources;
2009 if (defined $params{sort}) {
2011 if ($params{sort} eq 'title') {
2012 $f=sub { pagetitle(basename($a)) cmp pagetitle(basename($b)) };
2014 elsif ($params{sort} eq 'title_natural') {
2015 eval q{use Sort::Naturally};
2017 error(gettext("Sort::Naturally needed for title_natural sort"));
2019 $f=sub { Sort::Naturally::ncmp(pagetitle(basename($a)), pagetitle(basename($b))) };
2021 elsif ($params{sort} eq 'mtime') {
2022 $f=sub { $pagemtime{$b} <=> $pagemtime{$a} };
2024 elsif ($params{sort} eq 'age') {
2025 $f=sub { $pagectime{$b} <=> $pagectime{$a} };
2028 error sprintf(gettext("unknown sort type %s"), $params{sort});
2030 @candidates = sort { &$f } @candidates;
2033 @candidates=reverse(@candidates) if $params{reverse};
2035 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2037 # clear params, remainder is passed to pagespec
2038 my $num=$params{num};
2039 delete @params{qw{num deptype reverse sort filter list}};
2044 my $accum=IkiWiki::SuccessReason->new();
2045 foreach my $p (@candidates) {
2046 my $r=$sub->($p, %params, location => $page);
2047 error(sprintf(gettext("cannot match pages: %s"), $r))
2048 if $r->isa("IkiWiki::ErrorReason");
2052 last if defined $num && ++$count == $num;
2056 # Add simple dependencies for accumulated influences.
2057 my $i=$accum->influences;
2058 foreach my $k (keys %$i) {
2059 $depends_simple{$page}{lc $k} |= $i->{$k};
2065 sub pagespec_valid ($) {
2068 my $sub=pagespec_translate($spec);
2073 my $re=quotemeta(shift);
2079 package IkiWiki::FailReason;
2082 '""' => sub { $_[0][0] },
2084 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2085 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2086 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2090 our @ISA = 'IkiWiki::SuccessReason';
2092 package IkiWiki::SuccessReason;
2095 '""' => sub { $_[0][0] },
2097 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2098 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2099 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2106 return bless [$value, {@_}], $class;
2111 $this->[1]={@_} if @_;
2112 my %i=%{$this->[1]};
2117 sub influences_static {
2118 return ! $_[0][1]->{""};
2121 sub merge_influences {
2126 if (! $anded || (($this || %{$this->[1]}) &&
2127 ($other || %{$other->[1]}))) {
2128 foreach my $influence (keys %{$other->[1]}) {
2129 $this->[1]{$influence} |= $other->[1]{$influence};
2138 package IkiWiki::ErrorReason;
2140 our @ISA = 'IkiWiki::FailReason';
2142 package IkiWiki::PageSpec;
2148 if ($path =~ m!^\./!) {
2149 $from=~s#/?[^/]+$## if defined $from;
2151 $path="$from/$path" if length $from;
2157 sub match_glob ($$;@) {
2162 $glob=derel($glob, $params{location});
2164 my $regexp=IkiWiki::glob2re($glob);
2165 if ($page=~/^$regexp$/i) {
2166 if (! IkiWiki::isinternal($page) || $params{internal}) {
2167 return IkiWiki::SuccessReason->new("$glob matches $page");
2170 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2174 return IkiWiki::FailReason->new("$glob does not match $page");
2178 sub match_internal ($$;@) {
2179 return match_glob($_[0], $_[1], @_, internal => 1)
2182 sub match_link ($$;@) {
2187 $link=derel($link, $params{location});
2188 my $from=exists $params{location} ? $params{location} : '';
2190 my $links = $IkiWiki::links{$page};
2191 return IkiWiki::FailReason->new("$page has no links", "" => 1)
2192 unless $links && @{$links};
2193 my $bestlink = IkiWiki::bestlink($from, $link);
2194 foreach my $p (@{$links}) {
2195 if (length $bestlink) {
2196 return IkiWiki::SuccessReason->new("$page links to $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2197 if $bestlink eq IkiWiki::bestlink($page, $p);
2200 return IkiWiki::SuccessReason->new("$page links to page $p matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2201 if match_glob($p, $link, %params);
2202 my ($p_rel)=$p=~/^\/?(.*)/;
2204 return IkiWiki::SuccessReason->new("$page links to page $p_rel matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2205 if match_glob($p_rel, $link, %params);
2208 return IkiWiki::FailReason->new("$page does not link to $link", "" => 1);
2211 sub match_backlink ($$;@) {
2212 my $ret=match_link($_[1], $_[0], @_);
2213 $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2217 sub match_created_before ($$;@) {
2222 $testpage=derel($testpage, $params{location});
2224 if (exists $IkiWiki::pagectime{$testpage}) {
2225 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2226 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2229 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2233 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2237 sub match_created_after ($$;@) {
2242 $testpage=derel($testpage, $params{location});
2244 if (exists $IkiWiki::pagectime{$testpage}) {
2245 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2246 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2249 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2253 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2257 sub match_creation_day ($$;@) {
2258 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2259 return IkiWiki::SuccessReason->new('creation_day matched');
2262 return IkiWiki::FailReason->new('creation_day did not match');
2266 sub match_creation_month ($$;@) {
2267 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2268 return IkiWiki::SuccessReason->new('creation_month matched');
2271 return IkiWiki::FailReason->new('creation_month did not match');
2275 sub match_creation_year ($$;@) {
2276 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2277 return IkiWiki::SuccessReason->new('creation_year matched');
2280 return IkiWiki::FailReason->new('creation_year did not match');
2284 sub match_user ($$;@) {
2289 if (! exists $params{user}) {
2290 return IkiWiki::ErrorReason->new("no user specified");
2293 if (defined $params{user} && lc $params{user} eq lc $user) {
2294 return IkiWiki::SuccessReason->new("user is $user");
2296 elsif (! defined $params{user}) {
2297 return IkiWiki::FailReason->new("not logged in");
2300 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2304 sub match_admin ($$;@) {
2309 if (! exists $params{user}) {
2310 return IkiWiki::ErrorReason->new("no user specified");
2313 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2314 return IkiWiki::SuccessReason->new("user is an admin");
2316 elsif (! defined $params{user}) {
2317 return IkiWiki::FailReason->new("not logged in");
2320 return IkiWiki::FailReason->new("user is not an admin");
2324 sub match_ip ($$;@) {
2329 if (! exists $params{ip}) {
2330 return IkiWiki::ErrorReason->new("no IP specified");
2333 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2334 return IkiWiki::SuccessReason->new("IP is $ip");
2337 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");