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 add_depends pagespec_match
21 pagespec_match_list bestlink htmllink readfile writefile
22 pagetype srcfile pagename displaytime will_render gettext urlto
23 targetpage add_underlay pagetitle titlepage linkpage
24 newpagefile inject add_link
25 %config %links %pagestate %wikistate %renderedfiles
26 %pagesources %destsources);
27 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
28 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
29 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
34 memoize("pagespec_translate");
35 memoize("file_pruned");
36 memoize("template_file");
42 description => "name of the wiki",
49 example => 'me@example.com',
50 description => "contact email for wiki",
57 description => "users who are wiki admins",
64 description => "users who are banned from the wiki",
71 example => "$ENV{HOME}/wiki",
72 description => "where the source of the wiki is located",
79 example => "/var/www/wiki",
80 description => "where to build the wiki",
87 example => "http://example.com/wiki",
88 description => "base url to the wiki",
95 example => "http://example.com/wiki/ikiwiki.cgi",
96 description => "url to the ikiwiki.cgi",
103 example => "/var/www/wiki/ikiwiki.cgi",
104 description => "filename of cgi wrapper to generate",
111 description => "mode for cgi_wrapper (can safely be made suid)",
118 description => "rcs backend to use",
119 safe => 0, # don't allow overriding
124 default => [qw{mdwn link inline meta htmlscrubber passwordauth
125 openid signinedit lockedit conditional
126 recentchanges parentlinks editpage}],
127 description => "plugins to enable by default",
134 description => "plugins to add to the default configuration",
141 description => "plugins to disable",
147 default => "$installdir/share/ikiwiki/templates",
148 description => "location of template files",
156 description => "additional directories containing template files",
162 default => "$installdir/share/ikiwiki/basewiki",
163 description => "base wiki source location",
170 default => "$installdir/share/ikiwiki",
171 description => "parent directory containing additional underlays",
178 description => "wrappers to generate",
185 description => "additional underlays to use",
192 description => "display verbose messages?",
199 description => "log to syslog?",
206 description => "create output files named page/index.html?",
207 safe => 0, # changing requires manual transition
210 prefix_directives => {
213 description => "use '!'-prefixed preprocessor directives?",
214 safe => 0, # changing requires manual transition
220 description => "use page/index.mdwn source files",
227 description => "enable Discussion pages?",
233 default => gettext("Discussion"),
234 description => "name of Discussion pages",
241 description => "only send cookies over SSL connections?",
249 description => "extension to use for new pages",
250 safe => 0, # not sanitized
256 description => "extension to use for html files",
257 safe => 0, # not sanitized
263 description => "strftime format string to display date",
271 example => "en_US.UTF-8",
272 description => "UTF-8 locale to use",
281 description => "put user pages below specified page",
288 description => "how many backlinks to show before hiding excess (0 to show all)",
295 description => "attempt to hardlink source files? (optimisation for large files)",
297 safe => 0, # paranoia
303 description => "force ikiwiki to use a particular umask",
305 safe => 0, # paranoia
310 example => "ikiwiki",
311 description => "group for wrappers to run in",
313 safe => 0, # paranoia
319 example => "$ENV{HOME}/.ikiwiki/",
320 description => "extra library and plugin directory",
322 safe => 0, # directory
328 description => "environment variables",
329 safe => 0, # paranoia
336 description => "regexp of source files to ignore",
341 wiki_file_prune_regexps => {
343 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
344 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
345 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
346 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
347 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
348 description => "regexps of source files to ignore",
354 description => "specifies the characters that are allowed in source filenames",
355 default => "-[:alnum:]+/.:_",
359 wiki_file_regexp => {
361 description => "regexp of legal source files",
365 web_commit_regexp => {
367 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
368 description => "regexp to parse web commits from logs",
375 description => "run as a cgi",
379 cgi_disable_uploads => {
382 description => "whether CGI should accept file uploads",
389 description => "run as a post-commit hook",
396 description => "running in rebuild mode",
403 description => "running in setup mode",
410 description => "running in refresh mode",
417 description => "running in receive test mode",
424 description => "running in getctime mode",
431 description => "running in w3mmode",
438 description => "path to the .ikiwiki directory holding ikiwiki state",
445 description => "path to setup file",
449 allow_symlinks_before_srcdir => {
452 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
458 sub defaultconfig () {
461 foreach my $key (keys %s) {
462 push @ret, $key, $s{$key}->{default};
469 # locale stuff; avoid LC_ALL since it overrides everything
470 if (defined $ENV{LC_ALL}) {
471 $ENV{LANG} = $ENV{LC_ALL};
474 if (defined $config{locale}) {
475 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
476 $ENV{LANG}=$config{locale};
481 if (! defined $config{wiki_file_regexp}) {
482 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
485 if (ref $config{ENV} eq 'HASH') {
486 foreach my $val (keys %{$config{ENV}}) {
487 $ENV{$val}=$config{ENV}{$val};
491 if ($config{w3mmode}) {
492 eval q{use Cwd q{abs_path}};
494 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
495 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
496 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
497 unless $config{cgiurl} =~ m!file:///!;
498 $config{url}="file://".$config{destdir};
501 if ($config{cgi} && ! length $config{url}) {
502 error(gettext("Must specify url to wiki with --url when using --cgi"));
505 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
506 unless exists $config{wikistatedir} && defined $config{wikistatedir};
508 if (defined $config{umask}) {
509 umask(possibly_foolish_untaint($config{umask}));
512 run_hooks(checkconfig => sub { shift->() });
520 foreach my $dir (@INC, $config{libdir}) {
521 next unless defined $dir && length $dir;
522 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
523 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
527 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
528 next unless defined $dir && length $dir;
529 foreach my $file (glob("$dir/plugins/*")) {
530 $ret{basename($file)}=1 if -x $file;
538 if (defined $config{libdir} && length $config{libdir}) {
539 unshift @INC, possibly_foolish_untaint($config{libdir});
542 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
547 if (exists $IkiWiki::hooks{rcs}) {
548 error(gettext("cannot use multiple rcs plugins"));
550 loadplugin($config{rcs});
552 if (! exists $IkiWiki::hooks{rcs}) {
556 run_hooks(getopt => sub { shift->() });
557 if (grep /^-/, @ARGV) {
558 print STDERR "Unknown option (or missing parameter): $_\n"
559 foreach grep /^-/, @ARGV;
569 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
571 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
572 "$installdir/lib/ikiwiki") {
573 if (defined $dir && -x "$dir/plugins/$plugin") {
574 eval { require IkiWiki::Plugin::external };
577 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
579 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
580 $loaded_plugins{$plugin}=1;
585 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
588 error("Failed to load plugin $mod: $@");
590 $loaded_plugins{$plugin}=1;
597 log_message('err' => $message) if $config{syslog};
598 if (defined $cleaner) {
605 return unless $config{verbose};
606 return log_message(debug => @_);
610 sub log_message ($$) {
613 if ($config{syslog}) {
616 Sys::Syslog::setlogsock('unix');
617 Sys::Syslog::openlog('ikiwiki', '', 'user');
621 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
624 elsif (! $config{cgi}) {
628 return print STDERR "@_\n";
632 sub possibly_foolish_untaint ($) {
634 my ($untainted)=$tainted=~/(.*)/s;
654 return exists $pagesources{$page} &&
655 $pagesources{$page} =~ /\._([^.]+)$/;
661 if ($file =~ /\.([^.]+)$/) {
662 return $1 if exists $hooks{htmlize}{$1};
664 my $base=basename($file);
665 if (exists $hooks{htmlize}{$base} &&
666 $hooks{htmlize}{$base}{noextension}) {
677 if (exists $pagename_cache{$file}) {
678 return $pagename_cache{$file};
681 my $type=pagetype($file);
683 $page=~s/\Q.$type\E*$//
684 if defined $type && !$hooks{htmlize}{$type}{keepextension}
685 && !$hooks{htmlize}{$type}{noextension};
686 if ($config{indexpages} && $page=~/(.*)\/index$/) {
690 $pagename_cache{$file} = $page;
694 sub newpagefile ($$) {
698 if (! $config{indexpages} || $page eq 'index') {
699 return $page.".".$type;
702 return $page."/index.".$type;
706 sub targetpage ($$;$) {
711 if (defined $filename) {
712 return $page."/".$filename.".".$ext;
714 elsif (! $config{usedirs} || $page eq 'index') {
715 return $page.".".$ext;
718 return $page."/index.".$ext;
725 return targetpage($page, $config{htmlext});
732 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
733 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
734 return "$dir/$file", stat(_) if -e "$dir/$file";
736 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
741 return (srcfile_stat(@_))[0];
744 sub add_underlay ($) {
748 $dir="$config{underlaydirbase}/$dir";
751 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
752 unshift @{$config{underlaydirs}}, $dir;
758 sub readfile ($;$$) {
764 error("cannot read a symlink ($file)");
768 open (my $in, "<", $file) || error("failed to read $file: $!");
769 binmode($in) if ($binary);
770 return \*$in if $wantfd;
772 # check for invalid utf-8, and toss it back to avoid crashes
773 if (! utf8::valid($ret)) {
774 $ret=encode_utf8($ret);
776 close $in || error("failed to read $file: $!");
780 sub prep_writefile ($$) {
785 while (length $test) {
786 if (-l "$destdir/$test") {
787 error("cannot write to a symlink ($test)");
789 $test=dirname($test);
792 my $dir=dirname("$destdir/$file");
795 foreach my $s (split(m!/+!, $dir)) {
798 mkdir($d) || error("failed to create directory $d: $!");
806 sub writefile ($$$;$$) {
807 my $file=shift; # can include subdirs
808 my $destdir=shift; # directory to put file in
813 prep_writefile($file, $destdir);
815 my $newfile="$destdir/$file.ikiwiki-new";
817 error("cannot write to a symlink ($newfile)");
820 my $cleanup = sub { unlink($newfile) };
821 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
822 binmode($out) if ($binary);
824 $writer->(\*$out, $cleanup);
827 print $out $content or error("failed writing to $newfile: $!", $cleanup);
829 close $out || error("failed saving $newfile: $!", $cleanup);
830 rename($newfile, "$destdir/$file") ||
831 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
837 sub will_render ($$;$) {
842 # Important security check.
843 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
844 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
845 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
848 if (! $clear || $cleared{$page}) {
849 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
852 foreach my $old (@{$renderedfiles{$page}}) {
853 delete $destsources{$old};
855 $renderedfiles{$page}=[$dest];
858 $destsources{$dest}=$page;
868 if ($link=~s/^\/+//) {
876 $l.="/" if length $l;
879 if (exists $links{$l}) {
882 elsif (exists $pagecase{lc $l}) {
883 return $pagecase{lc $l};
885 } while $cwd=~s{/?[^/]+$}{};
887 if (length $config{userdir}) {
888 my $l = "$config{userdir}/".lc($link);
889 if (exists $links{$l}) {
892 elsif (exists $pagecase{lc $l}) {
893 return $pagecase{lc $l};
897 #print STDERR "warning: page $page, broken link: $link\n";
901 sub isinlinableimage ($) {
904 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
907 sub pagetitle ($;$) {
912 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
915 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
923 # support use w/o %config set
924 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
925 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
931 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
932 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
939 return $config{cgiurl}."?".
940 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
946 return "$config{url}/" if ! defined $page;
948 $page=htmlpage($page);
950 $page=~s/[^\/]+\//..\//g;
955 # Work around very innefficient behavior in File::Spec if abs2rel
956 # is passed two relative paths. It's much faster if paths are
957 # absolute! (Debian bug #376658; fixed in debian unstable now)
962 my $ret=File::Spec->abs2rel($path, $base);
963 $ret=~s/^// if defined $ret;
967 sub displaytime ($;$) {
968 # Plugins can override this function to mark up the time to
970 return '<span class="date">'.formattime(@_).'</span>';
973 sub formattime ($;$) {
974 # Plugins can override this function to format the time.
977 if (! defined $format) {
978 $format=$config{timeformat};
981 # strftime doesn't know about encodings, so make sure
982 # its output is properly treated as utf8
983 return decode_utf8(POSIX::strftime($format, localtime($time)));
986 sub beautify_urlpath ($) {
989 # Ensure url is not an empty link, and if necessary,
990 # add ./ to avoid colon confusion.
991 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
995 if ($config{usedirs}) {
996 $url =~ s!/index.$config{htmlext}$!/!;
1008 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1011 if (! $destsources{$to}) {
1016 return $config{url}.beautify_urlpath("/".$to);
1019 my $link = abs2rel($to, dirname(htmlpage($from)));
1021 return beautify_urlpath($link);
1024 sub htmllink ($$$;@) {
1025 my $lpage=shift; # the page doing the linking
1026 my $page=shift; # the page that will contain the link (different for inline)
1033 if (! $opts{forcesubpage}) {
1034 $bestlink=bestlink($lpage, $link);
1037 $bestlink="$lpage/".lc($link);
1041 if (defined $opts{linktext}) {
1042 $linktext=$opts{linktext};
1045 $linktext=pagetitle(basename($link));
1048 return "<span class=\"selflink\">$linktext</span>"
1049 if length $bestlink && $page eq $bestlink &&
1050 ! defined $opts{anchor};
1052 if (! $destsources{$bestlink}) {
1053 $bestlink=htmlpage($bestlink);
1055 if (! $destsources{$bestlink}) {
1056 return $linktext unless length $config{cgiurl};
1057 return "<span class=\"createlink\"><a href=\"".
1063 "\" rel=\"nofollow\">?</a>$linktext</span>"
1067 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1068 $bestlink=beautify_urlpath($bestlink);
1070 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1071 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1074 if (defined $opts{anchor}) {
1075 $bestlink.="#".$opts{anchor};
1079 if (defined $opts{rel}) {
1080 push @attrs, ' rel="'.$opts{rel}.'"';
1082 if (defined $opts{class}) {
1083 push @attrs, ' class="'.$opts{class}.'"';
1086 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1089 sub openiduser ($) {
1092 if ($user =~ m!^https?://! &&
1093 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1096 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1097 # this works in at least 2.x
1098 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1101 # this only works in 1.x
1102 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1103 $display=$oid->display;
1106 # Convert "user.somehost.com" to "user [somehost.com]"
1107 # (also "user.somehost.co.uk")
1108 if ($display !~ /\[/) {
1109 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1111 # Convert "http://somehost.com/user" to "user [somehost.com]".
1112 # (also "https://somehost.com/user/")
1113 if ($display !~ /\[/) {
1114 $display=~s/^https?:\/\/(.+)\/([^\/]+)\/?$/$2 [$1]/;
1116 $display=~s!^https?://!!; # make sure this is removed
1117 eval q{use CGI 'escapeHTML'};
1119 return escapeHTML($display);
1127 my $oiduser=eval { openiduser($user) };
1128 if (defined $oiduser) {
1129 return "<a href=\"$user\">$oiduser</a>";
1132 eval q{use CGI 'escapeHTML'};
1135 return htmllink("", "", escapeHTML(
1136 length $config{userdir} ? $config{userdir}."/".$user : $user
1137 ), noimageinline => 1);
1141 sub htmlize ($$$$) {
1147 my $oneline = $content !~ /\n/;
1149 if (exists $hooks{htmlize}{$type}) {
1150 $content=$hooks{htmlize}{$type}{call}->(
1152 content => $content,
1156 error("htmlization of $type not supported");
1159 run_hooks(sanitize => sub {
1162 destpage => $destpage,
1163 content => $content,
1168 # hack to get rid of enclosing junk added by markdown
1169 # and other htmlizers
1170 $content=~s/^<p>//i;
1171 $content=~s/<\/p>$//i;
1183 run_hooks(linkify => sub {
1186 destpage => $destpage,
1187 content => $content,
1195 our $preprocess_preview=0;
1196 sub preprocess ($$$;$$) {
1197 my $page=shift; # the page the data comes from
1198 my $destpage=shift; # the page the data will appear in (different for inline)
1203 # Using local because it needs to be set within any nested calls
1205 local $preprocess_preview=$preview if defined $preview;
1212 $params="" if ! defined $params;
1214 if (length $escape) {
1215 return "[[$prefix$command $params]]";
1217 elsif (exists $hooks{preprocess}{$command}) {
1218 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1219 # Note: preserve order of params, some plugins may
1220 # consider it significant.
1222 while ($params =~ m{
1223 (?:([-\w]+)=)? # 1: named parameter key?
1225 """(.*?)""" # 2: triple-quoted value
1227 "([^"]+)" # 3: single-quoted value
1229 (\S+) # 4: unquoted value
1231 (?:\s+|$) # delimiter to next param
1241 elsif (defined $3) {
1244 elsif (defined $4) {
1249 push @params, $key, $val;
1252 push @params, $val, '';
1255 if ($preprocessing{$page}++ > 3) {
1256 # Avoid loops of preprocessed pages preprocessing
1257 # other pages that preprocess them, etc.
1258 return "[[!$command <span class=\"error\">".
1259 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1260 $page, $preprocessing{$page}).
1266 $hooks{preprocess}{$command}{call}->(
1269 destpage => $destpage,
1270 preview => $preprocess_preview,
1276 $ret="[[!$command <span class=\"error\">".
1277 gettext("Error").": $error"."</span>]]";
1281 # use void context during scan pass
1283 $hooks{preprocess}{$command}{call}->(
1286 destpage => $destpage,
1287 preview => $preprocess_preview,
1292 $preprocessing{$page}--;
1296 return "[[$prefix$command $params]]";
1301 if ($config{prefix_directives}) {
1304 \[\[(!) # directive open; 2: prefix
1305 ([-\w]+) # 3: command
1306 ( # 4: the parameters..
1307 \s+ # Must have space if parameters present
1309 (?:[-\w]+=)? # named parameter key?
1311 """.*?""" # triple-quoted value
1313 "[^"]+" # single-quoted value
1315 [^"\s\]]+ # unquoted value
1317 \s* # whitespace or end
1320 *)? # 0 or more parameters
1321 \]\] # directive closed
1327 \[\[(!?) # directive open; 2: optional prefix
1328 ([-\w]+) # 3: command
1330 ( # 4: the parameters..
1332 (?:[-\w]+=)? # named parameter key?
1334 """.*?""" # triple-quoted value
1336 "[^"]+" # single-quoted value
1338 [^"\s\]]+ # unquoted value
1340 \s* # whitespace or end
1343 *) # 0 or more parameters
1344 \]\] # directive closed
1348 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1357 run_hooks(filter => sub {
1358 $content=shift->(page => $page, destpage => $destpage,
1359 content => $content);
1366 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1369 sub check_canedit ($$$;$) {
1376 run_hooks(canedit => sub {
1377 return if defined $canedit;
1378 my $ret=shift->($page, $q, $session);
1383 elsif (ref $ret eq 'CODE') {
1384 $ret->() unless $nonfatal;
1387 elsif (defined $ret) {
1388 error($ret) unless $nonfatal;
1393 return defined $canedit ? $canedit : 1;
1396 sub check_content (@) {
1399 return 1 if ! exists $hooks{checkcontent}; # optimisation
1401 if (exists $pagesources{$params{page}}) {
1403 my %old=map { $_ => 1 }
1404 split("\n", readfile(srcfile($pagesources{$params{page}})));
1405 foreach my $line (split("\n", $params{content})) {
1406 push @diff, $line if ! exists $old{$_};
1408 $params{diff}=join("\n", @diff);
1412 run_hooks(checkcontent => sub {
1413 return if defined $ok;
1414 my $ret=shift->(%params);
1419 elsif (ref $ret eq 'CODE') {
1420 $ret->() unless $params{nonfatal};
1423 elsif (defined $ret) {
1424 error($ret) unless $params{nonfatal};
1430 return defined $ok ? $ok : 1;
1436 # Take an exclusive lock on the wiki to prevent multiple concurrent
1437 # run issues. The lock will be dropped on program exit.
1438 if (! -d $config{wikistatedir}) {
1439 mkdir($config{wikistatedir});
1441 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1442 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1443 if (! flock($wikilock, 2)) { # LOCK_EX
1444 error("failed to get lock");
1450 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1451 return close($wikilock) if $wikilock;
1457 sub commit_hook_enabled () {
1458 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1459 error("cannot write to $config{wikistatedir}/commitlock: $!");
1460 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1461 close($commitlock) || error("failed closing commitlock: $!");
1464 close($commitlock) || error("failed closing commitlock: $!");
1468 sub disable_commit_hook () {
1469 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1470 error("cannot write to $config{wikistatedir}/commitlock: $!");
1471 if (! flock($commitlock, 2)) { # LOCK_EX
1472 error("failed to get commit lock");
1477 sub enable_commit_hook () {
1478 return close($commitlock) if $commitlock;
1483 %oldrenderedfiles=%pagectime=();
1484 if (! $config{rebuild}) {
1485 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1486 %destsources=%renderedfiles=%pagecase=%pagestate=
1490 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1491 if (-e "$config{wikistatedir}/index") {
1492 system("ikiwiki-transition", "indexdb", $config{srcdir});
1493 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1500 my $index=Storable::fd_retrieve($in);
1501 if (! defined $index) {
1506 if (exists $index->{version} && ! ref $index->{version}) {
1507 $pages=$index->{page};
1508 %wikistate=%{$index->{state}};
1515 foreach my $src (keys %$pages) {
1516 my $d=$pages->{$src};
1517 my $page=pagename($src);
1518 $pagectime{$page}=$d->{ctime};
1519 if (! $config{rebuild}) {
1520 $pagesources{$page}=$src;
1521 $pagemtime{$page}=$d->{mtime};
1522 $renderedfiles{$page}=$d->{dest};
1523 if (exists $d->{links} && ref $d->{links}) {
1524 $links{$page}=$d->{links};
1525 $oldlinks{$page}=[@{$d->{links}}];
1527 if (exists $d->{depends_simple}) {
1528 $depends_simple{$page}={
1529 map { $_ => 1 } @{$d->{depends_simple}}
1532 if (exists $d->{dependslist}) {
1534 map { $_ => 1 } @{$d->{dependslist}}
1537 elsif (exists $d->{depends}) {
1538 $depends{$page}={$d->{depends} => 1};
1540 if (exists $d->{state}) {
1541 $pagestate{$page}=$d->{state};
1544 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1546 foreach my $page (keys %pagesources) {
1547 $pagecase{lc $page}=$page;
1549 foreach my $page (keys %renderedfiles) {
1550 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1556 run_hooks(savestate => sub { shift->() });
1559 foreach my $type (keys %hooks) {
1560 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1562 my @hookids=keys %hookids;
1564 if (! -d $config{wikistatedir}) {
1565 mkdir($config{wikistatedir});
1567 my $newfile="$config{wikistatedir}/indexdb.new";
1568 my $cleanup = sub { unlink($newfile) };
1569 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1572 foreach my $page (keys %pagemtime) {
1573 next unless $pagemtime{$page};
1574 my $src=$pagesources{$page};
1576 $index{page}{$src}={
1577 ctime => $pagectime{$page},
1578 mtime => $pagemtime{$page},
1579 dest => $renderedfiles{$page},
1580 links => $links{$page},
1583 if (exists $depends{$page}) {
1584 $index{page}{$src}{dependslist} = [ keys %{$depends{$page}} ];
1587 if (exists $depends_simple{$page}) {
1588 $index{page}{$src}{depends_simple} = [ keys %{$depends_simple{$page}} ];
1591 if (exists $pagestate{$page}) {
1592 foreach my $id (@hookids) {
1593 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1594 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1601 foreach my $id (@hookids) {
1602 foreach my $key (keys %{$wikistate{$id}}) {
1603 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1607 $index{version}="3";
1608 my $ret=Storable::nstore_fd(\%index, $out);
1609 return if ! defined $ret || ! $ret;
1610 close $out || error("failed saving to $newfile: $!", $cleanup);
1611 rename($newfile, "$config{wikistatedir}/indexdb") ||
1612 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1617 sub template_file ($) {
1620 foreach my $dir ($config{templatedir}, @{$config{templatedirs}},
1621 "$installdir/share/ikiwiki/templates") {
1622 return "$dir/$template" if -e "$dir/$template";
1627 sub template_params (@) {
1628 my $filename=template_file(shift);
1630 if (! defined $filename) {
1631 return if wantarray;
1637 my $text_ref = shift;
1638 ${$text_ref} = decode_utf8(${$text_ref});
1640 filename => $filename,
1641 loop_context_vars => 1,
1642 die_on_bad_params => 0,
1645 return wantarray ? @ret : {@ret};
1648 sub template ($;@) {
1649 require HTML::Template;
1650 return HTML::Template->new(template_params(@_));
1653 sub misctemplate ($$;@) {
1657 my $template=template("misc.tmpl");
1660 indexlink => indexlink(),
1661 wikiname => $config{wikiname},
1662 pagebody => $pagebody,
1663 baseurl => baseurl(),
1666 run_hooks(pagetemplate => sub {
1667 shift->(page => "", destpage => "", template => $template);
1669 return $template->output;
1675 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1676 error 'hook requires type, call, and id parameters';
1679 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1681 $hooks{$param{type}}{$param{id}}=\%param;
1685 sub run_hooks ($$) {
1686 # Calls the given sub for each hook of the given type,
1687 # passing it the hook function to call.
1691 if (exists $hooks{$type}) {
1692 my (@first, @middle, @last);
1693 foreach my $id (keys %{$hooks{$type}}) {
1694 if ($hooks{$type}{$id}{first}) {
1697 elsif ($hooks{$type}{$id}{last}) {
1704 foreach my $id (@first, @middle, @last) {
1705 $sub->($hooks{$type}{$id}{call});
1713 $hooks{rcs}{rcs_update}{call}->(@_);
1716 sub rcs_prepedit ($) {
1717 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1720 sub rcs_commit ($$$;$$) {
1721 $hooks{rcs}{rcs_commit}{call}->(@_);
1724 sub rcs_commit_staged ($$$) {
1725 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1729 $hooks{rcs}{rcs_add}{call}->(@_);
1732 sub rcs_remove ($) {
1733 $hooks{rcs}{rcs_remove}{call}->(@_);
1736 sub rcs_rename ($$) {
1737 $hooks{rcs}{rcs_rename}{call}->(@_);
1740 sub rcs_recentchanges ($) {
1741 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1745 $hooks{rcs}{rcs_diff}{call}->(@_);
1748 sub rcs_getctime ($) {
1749 $hooks{rcs}{rcs_getctime}{call}->(@_);
1752 sub rcs_receive () {
1753 $hooks{rcs}{rcs_receive}{call}->();
1756 sub add_depends ($$) {
1760 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1761 $pagespec !~ /[\s*?()!]/) {
1762 # a simple dependency, which can be matched by string eq
1763 $depends_simple{$page}{lc $pagespec} = 1;
1767 return unless pagespec_valid($pagespec);
1769 $depends{$page}{$pagespec} = 1;
1773 sub file_pruned ($$) {
1775 my $file=File::Spec->canonpath(shift);
1776 my $base=File::Spec->canonpath(shift);
1777 $file =~ s#^\Q$base\E/+##;
1779 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1780 return $file =~ m/$regexp/ && $file ne $base;
1783 sub define_gettext () {
1784 # If translation is needed, redefine the gettext function to do it.
1785 # Otherwise, it becomes a quick no-op.
1786 no warnings 'redefine';
1787 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1788 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1789 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1791 my $gettext_obj=eval q{
1792 use Locale::gettext q{textdomain};
1793 Locale::gettext->domain('ikiwiki')
1797 $gettext_obj->get(shift);
1805 *gettext=sub { return shift };
1817 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1821 # Injects a new function into the symbol table to replace an
1822 # exported function.
1825 # This is deep ugly perl foo, beware.
1828 if (! defined $params{parent}) {
1829 $params{parent}='::';
1830 $params{old}=\&{$params{name}};
1831 $params{name}=~s/.*:://;
1833 my $parent=$params{parent};
1834 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1835 $ns = $params{parent} . $ns;
1836 inject(%params, parent => $ns) unless $ns eq '::main::';
1837 *{$ns . $params{name}} = $params{call}
1838 if exists ${$ns}{$params{name}} &&
1839 \&{${$ns}{$params{name}}} == $params{old};
1849 push @{$links{$page}}, $link
1850 unless grep { $_ eq $link } @{$links{$page}};
1853 sub pagespec_translate ($) {
1856 # Convert spec to perl code.
1860 \s* # ignore whitespace
1861 ( # 1: match a single word
1868 \w+\([^\)]*\) # command(params)
1870 [^\s()]+ # any other text
1872 \s* # ignore whitespace
1875 if (lc $word eq 'and') {
1878 elsif (lc $word eq 'or') {
1881 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1884 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1885 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1887 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
1890 push @data, qq{unknown function in pagespec "$word"};
1891 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
1896 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
1900 if (! length $code) {
1901 $code="IkiWiki::FailReason->new('empty pagespec')";
1905 return eval 'sub { my $page=shift; '.$code.' }';
1908 sub pagespec_match ($$;@) {
1913 # Backwards compatability with old calling convention.
1915 unshift @params, 'location';
1918 my $sub=pagespec_translate($spec);
1919 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
1920 if $@ || ! defined $sub;
1921 return $sub->($page, @params);
1924 sub pagespec_match_list ($$;@) {
1929 my $sub=pagespec_translate($spec);
1930 error "syntax error in pagespec \"$spec\""
1931 if $@ || ! defined $sub;
1935 foreach my $page (@$pages) {
1936 $r=$sub->($page, @params);
1937 push @ret, $page if $r;
1940 if (! @ret && defined $r && $r->isa("IkiWiki::ErrorReason")) {
1941 error(sprintf(gettext("cannot match pages: %s"), $r));
1948 sub pagespec_valid ($) {
1951 my $sub=pagespec_translate($spec);
1956 my $re=quotemeta(shift);
1962 package IkiWiki::FailReason;
1965 '""' => sub { ${$_[0]} },
1967 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1974 return bless \$value, $class;
1977 package IkiWiki::ErrorReason;
1979 our @ISA = 'IkiWiki::FailReason';
1981 package IkiWiki::SuccessReason;
1984 '""' => sub { ${$_[0]} },
1986 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1993 return bless \$value, $class;
1996 package IkiWiki::PageSpec;
2002 if ($path =~ m!^\./!) {
2003 $from=~s#/?[^/]+$## if defined $from;
2005 $path="$from/$path" if length $from;
2011 sub match_glob ($$;@) {
2016 $glob=derel($glob, $params{location});
2018 my $regexp=IkiWiki::glob2re($glob);
2019 if ($page=~/^$regexp$/i) {
2020 if (! IkiWiki::isinternal($page) || $params{internal}) {
2021 return IkiWiki::SuccessReason->new("$glob matches $page");
2024 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2028 return IkiWiki::FailReason->new("$glob does not match $page");
2032 sub match_internal ($$;@) {
2033 return match_glob($_[0], $_[1], @_, internal => 1)
2036 sub match_link ($$;@) {
2041 $link=derel($link, $params{location});
2042 my $from=exists $params{location} ? $params{location} : '';
2044 my $links = $IkiWiki::links{$page};
2045 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
2046 my $bestlink = IkiWiki::bestlink($from, $link);
2047 foreach my $p (@{$links}) {
2048 if (length $bestlink) {
2049 return IkiWiki::SuccessReason->new("$page links to $link")
2050 if $bestlink eq IkiWiki::bestlink($page, $p);
2053 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
2054 if match_glob($p, $link, %params);
2057 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
2058 if match_glob($p, $link, %params);
2061 return IkiWiki::FailReason->new("$page does not link to $link");
2064 sub match_backlink ($$;@) {
2065 return match_link($_[1], $_[0], @_);
2068 sub match_created_before ($$;@) {
2073 $testpage=derel($testpage, $params{location});
2075 if (exists $IkiWiki::pagectime{$testpage}) {
2076 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2077 return IkiWiki::SuccessReason->new("$page created before $testpage");
2080 return IkiWiki::FailReason->new("$page not created before $testpage");
2084 return IkiWiki::ErrorReason->new("$testpage does not exist");
2088 sub match_created_after ($$;@) {
2093 $testpage=derel($testpage, $params{location});
2095 if (exists $IkiWiki::pagectime{$testpage}) {
2096 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2097 return IkiWiki::SuccessReason->new("$page created after $testpage");
2100 return IkiWiki::FailReason->new("$page not created after $testpage");
2104 return IkiWiki::ErrorReason->new("$testpage does not exist");
2108 sub match_creation_day ($$;@) {
2109 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2110 return IkiWiki::SuccessReason->new('creation_day matched');
2113 return IkiWiki::FailReason->new('creation_day did not match');
2117 sub match_creation_month ($$;@) {
2118 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2119 return IkiWiki::SuccessReason->new('creation_month matched');
2122 return IkiWiki::FailReason->new('creation_month did not match');
2126 sub match_creation_year ($$;@) {
2127 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2128 return IkiWiki::SuccessReason->new('creation_year matched');
2131 return IkiWiki::FailReason->new('creation_year did not match');
2135 sub match_user ($$;@) {
2140 if (! exists $params{user}) {
2141 return IkiWiki::ErrorReason->new("no user specified");
2144 if (defined $params{user} && lc $params{user} eq lc $user) {
2145 return IkiWiki::SuccessReason->new("user is $user");
2147 elsif (! defined $params{user}) {
2148 return IkiWiki::FailReason->new("not logged in");
2151 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2155 sub match_admin ($$;@) {
2160 if (! exists $params{user}) {
2161 return IkiWiki::ErrorReason->new("no user specified");
2164 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2165 return IkiWiki::SuccessReason->new("user is an admin");
2167 elsif (! defined $params{user}) {
2168 return IkiWiki::FailReason->new("not logged in");
2171 return IkiWiki::FailReason->new("user is not an admin");
2175 sub match_ip ($$;@) {
2180 if (! exists $params{ip}) {
2181 return IkiWiki::ErrorReason->new("no IP specified");
2184 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2185 return IkiWiki::SuccessReason->new("IP is $ip");
2188 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");