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
340 example => '^\.htaccess$',
341 description => "regexp of normally excluded files to include",
349 example => '^(*\.private|Makefile)$',
350 description => "regexp of files that should be skipped",
355 wiki_file_prune_regexps => {
357 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
358 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
359 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
360 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
361 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
362 description => "regexps of source files to ignore",
368 description => "specifies the characters that are allowed in source filenames",
369 default => "-[:alnum:]+/.:_",
373 wiki_file_regexp => {
375 description => "regexp of legal source files",
379 web_commit_regexp => {
381 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
382 description => "regexp to parse web commits from logs",
389 description => "run as a cgi",
393 cgi_disable_uploads => {
396 description => "whether CGI should accept file uploads",
403 description => "run as a post-commit hook",
410 description => "running in rebuild mode",
417 description => "running in setup mode",
424 description => "running in clean mode",
431 description => "running in refresh mode",
438 description => "running in receive test mode",
445 description => "running in getctime mode",
452 description => "running in w3mmode",
459 description => "path to the .ikiwiki directory holding ikiwiki state",
466 description => "path to setup file",
470 allow_symlinks_before_srcdir => {
473 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
479 sub defaultconfig () {
482 foreach my $key (keys %s) {
483 push @ret, $key, $s{$key}->{default};
490 # locale stuff; avoid LC_ALL since it overrides everything
491 if (defined $ENV{LC_ALL}) {
492 $ENV{LANG} = $ENV{LC_ALL};
495 if (defined $config{locale}) {
496 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
497 $ENV{LANG}=$config{locale};
502 if (! defined $config{wiki_file_regexp}) {
503 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
506 if (ref $config{ENV} eq 'HASH') {
507 foreach my $val (keys %{$config{ENV}}) {
508 $ENV{$val}=$config{ENV}{$val};
512 if ($config{w3mmode}) {
513 eval q{use Cwd q{abs_path}};
515 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
516 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
517 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
518 unless $config{cgiurl} =~ m!file:///!;
519 $config{url}="file://".$config{destdir};
522 if ($config{cgi} && ! length $config{url}) {
523 error(gettext("Must specify url to wiki with --url when using --cgi"));
526 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
527 unless exists $config{wikistatedir} && defined $config{wikistatedir};
529 if (defined $config{umask}) {
530 umask(possibly_foolish_untaint($config{umask}));
533 run_hooks(checkconfig => sub { shift->() });
541 foreach my $dir (@INC, $config{libdir}) {
542 next unless defined $dir && length $dir;
543 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
544 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
548 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
549 next unless defined $dir && length $dir;
550 foreach my $file (glob("$dir/plugins/*")) {
551 $ret{basename($file)}=1 if -x $file;
559 if (defined $config{libdir} && length $config{libdir}) {
560 unshift @INC, possibly_foolish_untaint($config{libdir});
563 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
568 if (exists $hooks{rcs}) {
569 error(gettext("cannot use multiple rcs plugins"));
571 loadplugin($config{rcs});
573 if (! exists $hooks{rcs}) {
577 run_hooks(getopt => sub { shift->() });
578 if (grep /^-/, @ARGV) {
579 print STDERR "Unknown option (or missing parameter): $_\n"
580 foreach grep /^-/, @ARGV;
590 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
592 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
593 "$installdir/lib/ikiwiki") {
594 if (defined $dir && -x "$dir/plugins/$plugin") {
595 eval { require IkiWiki::Plugin::external };
598 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
600 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
601 $loaded_plugins{$plugin}=1;
606 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
609 error("Failed to load plugin $mod: $@");
611 $loaded_plugins{$plugin}=1;
618 log_message('err' => $message) if $config{syslog};
619 if (defined $cleaner) {
626 return unless $config{verbose};
627 return log_message(debug => @_);
631 sub log_message ($$) {
634 if ($config{syslog}) {
637 Sys::Syslog::setlogsock('unix');
638 Sys::Syslog::openlog('ikiwiki', '', 'user');
642 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
645 elsif (! $config{cgi}) {
649 return print STDERR "@_\n";
653 sub possibly_foolish_untaint ($) {
655 my ($untainted)=$tainted=~/(.*)/s;
675 return exists $pagesources{$page} &&
676 $pagesources{$page} =~ /\._([^.]+)$/;
682 if ($file =~ /\.([^.]+)$/) {
683 return $1 if exists $hooks{htmlize}{$1};
685 my $base=basename($file);
686 if (exists $hooks{htmlize}{$base} &&
687 $hooks{htmlize}{$base}{noextension}) {
698 if (exists $pagename_cache{$file}) {
699 return $pagename_cache{$file};
702 my $type=pagetype($file);
704 $page=~s/\Q.$type\E*$//
705 if defined $type && !$hooks{htmlize}{$type}{keepextension}
706 && !$hooks{htmlize}{$type}{noextension};
707 if ($config{indexpages} && $page=~/(.*)\/index$/) {
711 $pagename_cache{$file} = $page;
715 sub newpagefile ($$) {
719 if (! $config{indexpages} || $page eq 'index') {
720 return $page.".".$type;
723 return $page."/index.".$type;
727 sub targetpage ($$;$) {
732 if (defined $filename) {
733 return $page."/".$filename.".".$ext;
735 elsif (! $config{usedirs} || $page eq 'index') {
736 return $page.".".$ext;
739 return $page."/index.".$ext;
746 return targetpage($page, $config{htmlext});
753 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
754 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
755 return "$dir/$file", stat(_) if -e "$dir/$file";
757 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
762 return (srcfile_stat(@_))[0];
765 sub add_underlay ($) {
769 $dir="$config{underlaydirbase}/$dir";
772 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
773 unshift @{$config{underlaydirs}}, $dir;
779 sub readfile ($;$$) {
785 error("cannot read a symlink ($file)");
789 open (my $in, "<", $file) || error("failed to read $file: $!");
790 binmode($in) if ($binary);
791 return \*$in if $wantfd;
793 # check for invalid utf-8, and toss it back to avoid crashes
794 if (! utf8::valid($ret)) {
795 $ret=encode_utf8($ret);
797 close $in || error("failed to read $file: $!");
801 sub prep_writefile ($$) {
806 while (length $test) {
807 if (-l "$destdir/$test") {
808 error("cannot write to a symlink ($test)");
810 $test=dirname($test);
813 my $dir=dirname("$destdir/$file");
816 foreach my $s (split(m!/+!, $dir)) {
819 mkdir($d) || error("failed to create directory $d: $!");
827 sub writefile ($$$;$$) {
828 my $file=shift; # can include subdirs
829 my $destdir=shift; # directory to put file in
834 prep_writefile($file, $destdir);
836 my $newfile="$destdir/$file.ikiwiki-new";
838 error("cannot write to a symlink ($newfile)");
841 my $cleanup = sub { unlink($newfile) };
842 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
843 binmode($out) if ($binary);
845 $writer->(\*$out, $cleanup);
848 print $out $content or error("failed writing to $newfile: $!", $cleanup);
850 close $out || error("failed saving $newfile: $!", $cleanup);
851 rename($newfile, "$destdir/$file") ||
852 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
858 sub will_render ($$;$) {
863 # Important security check.
864 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
865 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
866 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
869 if (! $clear || $cleared{$page}) {
870 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
873 foreach my $old (@{$renderedfiles{$page}}) {
874 delete $destsources{$old};
876 $renderedfiles{$page}=[$dest];
879 $destsources{$dest}=$page;
889 if ($link=~s/^\/+//) {
897 $l.="/" if length $l;
900 if (exists $pagesources{$l}) {
903 elsif (exists $pagecase{lc $l}) {
904 return $pagecase{lc $l};
906 } while $cwd=~s{/?[^/]+$}{};
908 if (length $config{userdir}) {
909 my $l = "$config{userdir}/".lc($link);
910 if (exists $pagesources{$l}) {
913 elsif (exists $pagecase{lc $l}) {
914 return $pagecase{lc $l};
918 #print STDERR "warning: page $page, broken link: $link\n";
922 sub isinlinableimage ($) {
925 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
928 sub pagetitle ($;$) {
933 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
936 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
944 # support use w/o %config set
945 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
946 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
952 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
953 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
960 my $cgiurl=$config{cgiurl};
961 if (exists $params{cgiurl}) {
962 $cgiurl=$params{cgiurl};
963 delete $params{cgiurl};
966 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
972 return "$config{url}/" if ! defined $page;
974 $page=htmlpage($page);
976 $page=~s/[^\/]+\//..\//g;
981 # Work around very innefficient behavior in File::Spec if abs2rel
982 # is passed two relative paths. It's much faster if paths are
983 # absolute! (Debian bug #376658; fixed in debian unstable now)
988 my $ret=File::Spec->abs2rel($path, $base);
989 $ret=~s/^// if defined $ret;
993 sub displaytime ($;$) {
994 # Plugins can override this function to mark up the time to
996 return '<span class="date">'.formattime(@_).'</span>';
999 sub formattime ($;$) {
1000 # Plugins can override this function to format the time.
1003 if (! defined $format) {
1004 $format=$config{timeformat};
1007 # strftime doesn't know about encodings, so make sure
1008 # its output is properly treated as utf8
1009 return decode_utf8(POSIX::strftime($format, localtime($time)));
1012 sub beautify_urlpath ($) {
1015 # Ensure url is not an empty link, and if necessary,
1016 # add ./ to avoid colon confusion.
1017 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1021 if ($config{usedirs}) {
1022 $url =~ s!/index.$config{htmlext}$!/!;
1034 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1037 if (! $destsources{$to}) {
1042 return $config{url}.beautify_urlpath("/".$to);
1045 my $link = abs2rel($to, dirname(htmlpage($from)));
1047 return beautify_urlpath($link);
1050 sub htmllink ($$$;@) {
1051 my $lpage=shift; # the page doing the linking
1052 my $page=shift; # the page that will contain the link (different for inline)
1059 if (! $opts{forcesubpage}) {
1060 $bestlink=bestlink($lpage, $link);
1063 $bestlink="$lpage/".lc($link);
1067 if (defined $opts{linktext}) {
1068 $linktext=$opts{linktext};
1071 $linktext=pagetitle(basename($link));
1074 return "<span class=\"selflink\">$linktext</span>"
1075 if length $bestlink && $page eq $bestlink &&
1076 ! defined $opts{anchor};
1078 if (! $destsources{$bestlink}) {
1079 $bestlink=htmlpage($bestlink);
1081 if (! $destsources{$bestlink}) {
1082 return $linktext unless length $config{cgiurl};
1083 return "<span class=\"createlink\"><a href=\"".
1089 "\" rel=\"nofollow\">?</a>$linktext</span>"
1093 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1094 $bestlink=beautify_urlpath($bestlink);
1096 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1097 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1100 if (defined $opts{anchor}) {
1101 $bestlink.="#".$opts{anchor};
1105 foreach my $attr (qw{rel class title}) {
1106 if (defined $opts{$attr}) {
1107 push @attrs, " $attr=\"$opts{$attr}\"";
1111 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1116 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1119 sub openiduser ($) {
1122 if ($user =~ m!^https?://! &&
1123 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1126 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1127 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1130 # backcompat with old version
1131 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1132 $display=$oid->display;
1135 # Convert "user.somehost.com" to "user [somehost.com]"
1136 # (also "user.somehost.co.uk")
1137 if ($display !~ /\[/) {
1138 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1140 # Convert "http://somehost.com/user" to "user [somehost.com]".
1141 # (also "https://somehost.com/user/")
1142 if ($display !~ /\[/) {
1143 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1145 $display=~s!^https?://!!; # make sure this is removed
1146 eval q{use CGI 'escapeHTML'};
1148 return escapeHTML($display);
1153 sub htmlize ($$$$) {
1159 my $oneline = $content !~ /\n/;
1161 if (exists $hooks{htmlize}{$type}) {
1162 $content=$hooks{htmlize}{$type}{call}->(
1164 content => $content,
1168 error("htmlization of $type not supported");
1171 run_hooks(sanitize => sub {
1174 destpage => $destpage,
1175 content => $content,
1180 # hack to get rid of enclosing junk added by markdown
1181 # and other htmlizers
1182 $content=~s/^<p>//i;
1183 $content=~s/<\/p>$//i;
1195 run_hooks(linkify => sub {
1198 destpage => $destpage,
1199 content => $content,
1207 our $preprocess_preview=0;
1208 sub preprocess ($$$;$$) {
1209 my $page=shift; # the page the data comes from
1210 my $destpage=shift; # the page the data will appear in (different for inline)
1215 # Using local because it needs to be set within any nested calls
1217 local $preprocess_preview=$preview if defined $preview;
1224 $params="" if ! defined $params;
1226 if (length $escape) {
1227 return "[[$prefix$command $params]]";
1229 elsif (exists $hooks{preprocess}{$command}) {
1230 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1231 # Note: preserve order of params, some plugins may
1232 # consider it significant.
1234 while ($params =~ m{
1235 (?:([-\w]+)=)? # 1: named parameter key?
1237 """(.*?)""" # 2: triple-quoted value
1239 "([^"]*?)" # 3: single-quoted value
1241 (\S+) # 4: unquoted value
1243 (?:\s+|$) # delimiter to next param
1253 elsif (defined $3) {
1256 elsif (defined $4) {
1261 push @params, $key, $val;
1264 push @params, $val, '';
1267 if ($preprocessing{$page}++ > 3) {
1268 # Avoid loops of preprocessed pages preprocessing
1269 # other pages that preprocess them, etc.
1270 return "[[!$command <span class=\"error\">".
1271 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1272 $page, $preprocessing{$page}).
1278 $hooks{preprocess}{$command}{call}->(
1281 destpage => $destpage,
1282 preview => $preprocess_preview,
1288 $ret="[[!$command <span class=\"error\">".
1289 gettext("Error").": $error"."</span>]]";
1293 # use void context during scan pass
1295 $hooks{preprocess}{$command}{call}->(
1298 destpage => $destpage,
1299 preview => $preprocess_preview,
1304 $preprocessing{$page}--;
1308 return "[[$prefix$command $params]]";
1313 if ($config{prefix_directives}) {
1316 \[\[(!) # directive open; 2: prefix
1317 ([-\w]+) # 3: command
1318 ( # 4: the parameters..
1319 \s+ # Must have space if parameters present
1321 (?:[-\w]+=)? # named parameter key?
1323 """.*?""" # triple-quoted value
1325 "[^"]*?" # single-quoted value
1327 [^"\s\]]+ # unquoted value
1329 \s* # whitespace or end
1332 *)? # 0 or more parameters
1333 \]\] # directive closed
1339 \[\[(!?) # directive open; 2: optional prefix
1340 ([-\w]+) # 3: command
1342 ( # 4: the parameters..
1344 (?:[-\w]+=)? # named parameter key?
1346 """.*?""" # triple-quoted value
1348 "[^"]*?" # single-quoted value
1350 [^"\s\]]+ # unquoted value
1352 \s* # whitespace or end
1355 *) # 0 or more parameters
1356 \]\] # directive closed
1360 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1369 run_hooks(filter => sub {
1370 $content=shift->(page => $page, destpage => $destpage,
1371 content => $content);
1378 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1381 sub check_canedit ($$$;$) {
1388 run_hooks(canedit => sub {
1389 return if defined $canedit;
1390 my $ret=shift->($page, $q, $session);
1395 elsif (ref $ret eq 'CODE') {
1396 $ret->() unless $nonfatal;
1399 elsif (defined $ret) {
1400 error($ret) unless $nonfatal;
1405 return defined $canedit ? $canedit : 1;
1408 sub check_content (@) {
1411 return 1 if ! exists $hooks{checkcontent}; # optimisation
1413 if (exists $pagesources{$params{page}}) {
1415 my %old=map { $_ => 1 }
1416 split("\n", readfile(srcfile($pagesources{$params{page}})));
1417 foreach my $line (split("\n", $params{content})) {
1418 push @diff, $line if ! exists $old{$line};
1420 $params{diff}=join("\n", @diff);
1424 run_hooks(checkcontent => sub {
1425 return if defined $ok;
1426 my $ret=shift->(%params);
1431 elsif (ref $ret eq 'CODE') {
1432 $ret->() unless $params{nonfatal};
1435 elsif (defined $ret) {
1436 error($ret) unless $params{nonfatal};
1442 return defined $ok ? $ok : 1;
1448 # Take an exclusive lock on the wiki to prevent multiple concurrent
1449 # run issues. The lock will be dropped on program exit.
1450 if (! -d $config{wikistatedir}) {
1451 mkdir($config{wikistatedir});
1453 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1454 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1455 if (! flock($wikilock, 2)) { # LOCK_EX
1456 error("failed to get lock");
1462 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1463 return close($wikilock) if $wikilock;
1469 sub commit_hook_enabled () {
1470 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1471 error("cannot write to $config{wikistatedir}/commitlock: $!");
1472 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1473 close($commitlock) || error("failed closing commitlock: $!");
1476 close($commitlock) || error("failed closing commitlock: $!");
1480 sub disable_commit_hook () {
1481 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1482 error("cannot write to $config{wikistatedir}/commitlock: $!");
1483 if (! flock($commitlock, 2)) { # LOCK_EX
1484 error("failed to get commit lock");
1489 sub enable_commit_hook () {
1490 return close($commitlock) if $commitlock;
1495 %oldrenderedfiles=%pagectime=();
1496 if (! $config{rebuild}) {
1497 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1498 %destsources=%renderedfiles=%pagecase=%pagestate=
1502 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1503 if (-e "$config{wikistatedir}/index") {
1504 system("ikiwiki-transition", "indexdb", $config{srcdir});
1505 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1512 my $index=Storable::fd_retrieve($in);
1513 if (! defined $index) {
1518 if (exists $index->{version} && ! ref $index->{version}) {
1519 $pages=$index->{page};
1520 %wikistate=%{$index->{state}};
1527 foreach my $src (keys %$pages) {
1528 my $d=$pages->{$src};
1529 my $page=pagename($src);
1530 $pagectime{$page}=$d->{ctime};
1531 if (! $config{rebuild}) {
1532 $pagesources{$page}=$src;
1533 $pagemtime{$page}=$d->{mtime};
1534 $renderedfiles{$page}=$d->{dest};
1535 if (exists $d->{links} && ref $d->{links}) {
1536 $links{$page}=$d->{links};
1537 $oldlinks{$page}=[@{$d->{links}}];
1539 if (ref $d->{depends_simple} eq 'ARRAY') {
1541 $depends_simple{$page}={
1542 map { $_ => 1 } @{$d->{depends_simple}}
1545 elsif (exists $d->{depends_simple}) {
1546 $depends_simple{$page}=$d->{depends_simple};
1548 if (exists $d->{dependslist}) {
1551 map { $_ => $DEPEND_CONTENT }
1552 @{$d->{dependslist}}
1555 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1557 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1559 elsif (exists $d->{depends}) {
1560 $depends{$page}=$d->{depends};
1562 if (exists $d->{state}) {
1563 $pagestate{$page}=$d->{state};
1566 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1568 foreach my $page (keys %pagesources) {
1569 $pagecase{lc $page}=$page;
1571 foreach my $page (keys %renderedfiles) {
1572 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1578 run_hooks(savestate => sub { shift->() });
1581 foreach my $type (keys %hooks) {
1582 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1584 my @hookids=keys %hookids;
1586 if (! -d $config{wikistatedir}) {
1587 mkdir($config{wikistatedir});
1589 my $newfile="$config{wikistatedir}/indexdb.new";
1590 my $cleanup = sub { unlink($newfile) };
1591 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1594 foreach my $page (keys %pagemtime) {
1595 next unless $pagemtime{$page};
1596 my $src=$pagesources{$page};
1598 $index{page}{$src}={
1599 ctime => $pagectime{$page},
1600 mtime => $pagemtime{$page},
1601 dest => $renderedfiles{$page},
1602 links => $links{$page},
1605 if (exists $depends{$page}) {
1606 $index{page}{$src}{depends} = $depends{$page};
1609 if (exists $depends_simple{$page}) {
1610 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1613 if (exists $pagestate{$page}) {
1614 foreach my $id (@hookids) {
1615 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1616 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1623 foreach my $id (@hookids) {
1624 foreach my $key (keys %{$wikistate{$id}}) {
1625 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1629 $index{version}="3";
1630 my $ret=Storable::nstore_fd(\%index, $out);
1631 return if ! defined $ret || ! $ret;
1632 close $out || error("failed saving to $newfile: $!", $cleanup);
1633 rename($newfile, "$config{wikistatedir}/indexdb") ||
1634 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1639 sub template_file ($) {
1642 foreach my $dir ($config{templatedir}, @{$config{templatedirs}},
1643 "$installdir/share/ikiwiki/templates") {
1644 return "$dir/$template" if -e "$dir/$template";
1649 sub template_params (@) {
1650 my $filename=template_file(shift);
1652 if (! defined $filename) {
1653 return if wantarray;
1659 my $text_ref = shift;
1660 ${$text_ref} = decode_utf8(${$text_ref});
1662 filename => $filename,
1663 loop_context_vars => 1,
1664 die_on_bad_params => 0,
1667 return wantarray ? @ret : {@ret};
1670 sub template ($;@) {
1671 require HTML::Template;
1672 return HTML::Template->new(template_params(@_));
1675 sub misctemplate ($$;@) {
1679 my $template=template("misc.tmpl");
1682 indexlink => indexlink(),
1683 wikiname => $config{wikiname},
1684 pagebody => $pagebody,
1685 baseurl => baseurl(),
1688 run_hooks(pagetemplate => sub {
1689 shift->(page => "", destpage => "", template => $template);
1691 return $template->output;
1697 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1698 error 'hook requires type, call, and id parameters';
1701 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1703 $hooks{$param{type}}{$param{id}}=\%param;
1707 sub run_hooks ($$) {
1708 # Calls the given sub for each hook of the given type,
1709 # passing it the hook function to call.
1713 if (exists $hooks{$type}) {
1714 my (@first, @middle, @last);
1715 foreach my $id (keys %{$hooks{$type}}) {
1716 if ($hooks{$type}{$id}{first}) {
1719 elsif ($hooks{$type}{$id}{last}) {
1726 foreach my $id (@first, @middle, @last) {
1727 $sub->($hooks{$type}{$id}{call});
1735 $hooks{rcs}{rcs_update}{call}->(@_);
1738 sub rcs_prepedit ($) {
1739 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1742 sub rcs_commit ($$$;$$) {
1743 $hooks{rcs}{rcs_commit}{call}->(@_);
1746 sub rcs_commit_staged ($$$) {
1747 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1751 $hooks{rcs}{rcs_add}{call}->(@_);
1754 sub rcs_remove ($) {
1755 $hooks{rcs}{rcs_remove}{call}->(@_);
1758 sub rcs_rename ($$) {
1759 $hooks{rcs}{rcs_rename}{call}->(@_);
1762 sub rcs_recentchanges ($) {
1763 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1767 $hooks{rcs}{rcs_diff}{call}->(@_);
1770 sub rcs_getctime ($) {
1771 $hooks{rcs}{rcs_getctime}{call}->(@_);
1774 sub rcs_receive () {
1775 $hooks{rcs}{rcs_receive}{call}->();
1778 sub add_depends ($$;$) {
1781 my $deptype=shift || $DEPEND_CONTENT;
1783 # Is the pagespec a simple page name?
1784 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1785 $pagespec !~ /[\s*?()!]/) {
1786 $depends_simple{$page}{lc $pagespec} |= $deptype;
1790 # Add explicit dependencies for influences.
1791 my $sub=pagespec_translate($pagespec);
1793 foreach my $p (keys %pagesources) {
1794 my $r=$sub->($p, location => $page);
1795 my $i=$r->influences;
1796 foreach my $k (keys %$i) {
1797 $depends_simple{$page}{lc $k} |= $i->{$k};
1799 last if $r->influences_static;
1802 $depends{$page}{$pagespec} |= $deptype;
1808 foreach my $type (@_) {
1809 if ($type eq 'presence') {
1810 $deptype |= $DEPEND_PRESENCE;
1812 elsif ($type eq 'links') {
1813 $deptype |= $DEPEND_LINKS;
1815 elsif ($type eq 'content') {
1816 $deptype |= $DEPEND_CONTENT;
1822 my $file_prune_regexp;
1823 sub file_pruned ($;$) {
1827 $file=File::Spec->canonpath($file);
1828 my $base=File::Spec->canonpath(shift);
1829 return if $file eq $base;
1830 $file =~ s#^\Q$base\E/+##;
1833 if (defined $config{include} && length $config{include}) {
1834 return 0 if $file =~ m/$config{include}/;
1837 if (! defined $file_prune_regexp) {
1838 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1839 $file_prune_regexp=qr/$file_prune_regexp/;
1841 return $file =~ m/$file_prune_regexp/;
1844 sub define_gettext () {
1845 # If translation is needed, redefine the gettext function to do it.
1846 # Otherwise, it becomes a quick no-op.
1849 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1850 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1851 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1853 $gettext_obj=eval q{
1854 use Locale::gettext q{textdomain};
1855 Locale::gettext->domain('ikiwiki')
1860 no warnings 'redefine';
1862 $getobj->() if $getobj;
1864 $gettext_obj->get(shift);
1871 $getobj->() if $getobj;
1873 $gettext_obj->nget(@_);
1876 return ($_[2] == 1 ? $_[0] : $_[1])
1894 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1898 # Injects a new function into the symbol table to replace an
1899 # exported function.
1902 # This is deep ugly perl foo, beware.
1905 if (! defined $params{parent}) {
1906 $params{parent}='::';
1907 $params{old}=\&{$params{name}};
1908 $params{name}=~s/.*:://;
1910 my $parent=$params{parent};
1911 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1912 $ns = $params{parent} . $ns;
1913 inject(%params, parent => $ns) unless $ns eq '::main::';
1914 *{$ns . $params{name}} = $params{call}
1915 if exists ${$ns}{$params{name}} &&
1916 \&{${$ns}{$params{name}}} == $params{old};
1926 push @{$links{$page}}, $link
1927 unless grep { $_ eq $link } @{$links{$page}};
1930 sub pagespec_translate ($) {
1933 # Convert spec to perl code.
1937 \s* # ignore whitespace
1938 ( # 1: match a single word
1945 \w+\([^\)]*\) # command(params)
1947 [^\s()]+ # any other text
1949 \s* # ignore whitespace
1952 if (lc $word eq 'and') {
1955 elsif (lc $word eq 'or') {
1958 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1961 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1962 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1964 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
1967 push @data, qq{unknown function in pagespec "$word"};
1968 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
1973 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
1977 if (! length $code) {
1978 $code="IkiWiki::FailReason->new('empty pagespec')";
1982 return eval 'sub { my $page=shift; '.$code.' }';
1985 sub pagespec_match ($$;@) {
1990 # Backwards compatability with old calling convention.
1992 unshift @params, 'location';
1995 my $sub=pagespec_translate($spec);
1996 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
1997 if $@ || ! defined $sub;
1998 return $sub->($page, @params);
2001 sub pagespec_match_list ($$;@) {
2006 # Backwards compatability with old calling convention.
2008 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2009 $params{list}=$page;
2010 $page=$params{location}; # ugh!
2013 my $sub=pagespec_translate($pagespec);
2014 error "syntax error in pagespec \"$pagespec\""
2015 if $@ || ! defined $sub;
2018 if (exists $params{list}) {
2019 @candidates=exists $params{filter}
2020 ? grep { ! $params{filter}->($_) } @{$params{list}}
2024 @candidates=exists $params{filter}
2025 ? grep { ! $params{filter}->($_) } keys %pagesources
2026 : keys %pagesources;
2029 if (defined $params{sort}) {
2031 if ($params{sort} eq 'title') {
2032 $f=sub { pagetitle(basename($a)) cmp pagetitle(basename($b)) };
2034 elsif ($params{sort} eq 'title_natural') {
2035 eval q{use Sort::Naturally};
2037 error(gettext("Sort::Naturally needed for title_natural sort"));
2039 $f=sub { Sort::Naturally::ncmp(pagetitle(basename($a)), pagetitle(basename($b))) };
2041 elsif ($params{sort} eq 'mtime') {
2042 $f=sub { $pagemtime{$b} <=> $pagemtime{$a} };
2044 elsif ($params{sort} eq 'age') {
2045 $f=sub { $pagectime{$b} <=> $pagectime{$a} };
2048 error sprintf(gettext("unknown sort type %s"), $params{sort});
2050 @candidates = sort { &$f } @candidates;
2053 @candidates=reverse(@candidates) if $params{reverse};
2055 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2057 # clear params, remainder is passed to pagespec
2058 my $num=$params{num};
2059 delete @params{qw{num deptype reverse sort filter list}};
2064 my $accum=IkiWiki::SuccessReason->new();
2065 foreach my $p (@candidates) {
2066 my $r=$sub->($p, %params, location => $page);
2067 error(sprintf(gettext("cannot match pages: %s"), $r))
2068 if $r->isa("IkiWiki::ErrorReason");
2072 last if defined $num && ++$count == $num;
2076 # Add simple dependencies for accumulated influences.
2077 my $i=$accum->influences;
2078 foreach my $k (keys %$i) {
2079 $depends_simple{$page}{lc $k} |= $i->{$k};
2085 sub pagespec_valid ($) {
2088 my $sub=pagespec_translate($spec);
2093 my $re=quotemeta(shift);
2099 package IkiWiki::FailReason;
2102 '""' => sub { $_[0][0] },
2104 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2105 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2106 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2110 our @ISA = 'IkiWiki::SuccessReason';
2112 package IkiWiki::SuccessReason;
2115 '""' => sub { $_[0][0] },
2117 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2118 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2119 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2126 return bless [$value, {@_}], $class;
2131 $this->[1]={@_} if @_;
2132 my %i=%{$this->[1]};
2137 sub influences_static {
2138 return ! $_[0][1]->{""};
2141 sub merge_influences {
2146 if (! $anded || (($this || %{$this->[1]}) &&
2147 ($other || %{$other->[1]}))) {
2148 foreach my $influence (keys %{$other->[1]}) {
2149 $this->[1]{$influence} |= $other->[1]{$influence};
2158 package IkiWiki::ErrorReason;
2160 our @ISA = 'IkiWiki::FailReason';
2162 package IkiWiki::PageSpec;
2168 if ($path =~ m!^\./!) {
2169 $from=~s#/?[^/]+$## if defined $from;
2171 $path="$from/$path" if length $from;
2177 sub match_glob ($$;@) {
2182 $glob=derel($glob, $params{location});
2184 my $regexp=IkiWiki::glob2re($glob);
2185 if ($page=~/^$regexp$/i) {
2186 if (! IkiWiki::isinternal($page) || $params{internal}) {
2187 return IkiWiki::SuccessReason->new("$glob matches $page");
2190 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2194 return IkiWiki::FailReason->new("$glob does not match $page");
2198 sub match_internal ($$;@) {
2199 return match_glob($_[0], $_[1], @_, internal => 1)
2202 sub match_link ($$;@) {
2207 $link=derel($link, $params{location});
2208 my $from=exists $params{location} ? $params{location} : '';
2210 my $links = $IkiWiki::links{$page};
2211 return IkiWiki::FailReason->new("$page has no links", "" => 1)
2212 unless $links && @{$links};
2213 my $bestlink = IkiWiki::bestlink($from, $link);
2214 foreach my $p (@{$links}) {
2215 if (length $bestlink) {
2216 return IkiWiki::SuccessReason->new("$page links to $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2217 if $bestlink eq IkiWiki::bestlink($page, $p);
2220 return IkiWiki::SuccessReason->new("$page links to page $p matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2221 if match_glob($p, $link, %params);
2222 my ($p_rel)=$p=~/^\/?(.*)/;
2224 return IkiWiki::SuccessReason->new("$page links to page $p_rel matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2225 if match_glob($p_rel, $link, %params);
2228 return IkiWiki::FailReason->new("$page does not link to $link", "" => 1);
2231 sub match_backlink ($$;@) {
2232 my $ret=match_link($_[1], $_[0], @_);
2233 $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2237 sub match_created_before ($$;@) {
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 before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2249 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2253 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2257 sub match_created_after ($$;@) {
2262 $testpage=derel($testpage, $params{location});
2264 if (exists $IkiWiki::pagectime{$testpage}) {
2265 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2266 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2269 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2273 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2277 sub match_creation_day ($$;@) {
2278 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2279 return IkiWiki::SuccessReason->new('creation_day matched');
2282 return IkiWiki::FailReason->new('creation_day did not match');
2286 sub match_creation_month ($$;@) {
2287 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2288 return IkiWiki::SuccessReason->new('creation_month matched');
2291 return IkiWiki::FailReason->new('creation_month did not match');
2295 sub match_creation_year ($$;@) {
2296 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2297 return IkiWiki::SuccessReason->new('creation_year matched');
2300 return IkiWiki::FailReason->new('creation_year did not match');
2304 sub match_user ($$;@) {
2309 my $regexp=IkiWiki::glob2re($user);
2311 if (! exists $params{user}) {
2312 return IkiWiki::ErrorReason->new("no user specified");
2315 if (defined $params{user} && $params{user}=~/^$regexp$/i) {
2316 return IkiWiki::SuccessReason->new("user is $user");
2318 elsif (! defined $params{user}) {
2319 return IkiWiki::FailReason->new("not logged in");
2322 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2326 sub match_admin ($$;@) {
2331 if (! exists $params{user}) {
2332 return IkiWiki::ErrorReason->new("no user specified");
2335 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2336 return IkiWiki::SuccessReason->new("user is an admin");
2338 elsif (! defined $params{user}) {
2339 return IkiWiki::FailReason->new("not logged in");
2342 return IkiWiki::FailReason->new("user is not an admin");
2346 sub match_ip ($$;@) {
2351 if (! exists $params{ip}) {
2352 return IkiWiki::ErrorReason->new("no IP specified");
2355 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2356 return IkiWiki::SuccessReason->new("IP is $ip");
2359 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");