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
31 # Page dependency types.
33 our $DEPEND_CONTENT=2;
38 memoize("pagespec_translate");
39 memoize("file_pruned");
40 memoize("template_file");
46 description => "name of the wiki",
53 example => 'me@example.com',
54 description => "contact email for wiki",
61 description => "users who are wiki admins",
68 description => "users who are banned from the wiki",
75 example => "$ENV{HOME}/wiki",
76 description => "where the source of the wiki is located",
83 example => "/var/www/wiki",
84 description => "where to build the wiki",
91 example => "http://example.com/wiki",
92 description => "base url to the wiki",
99 example => "http://example.com/wiki/ikiwiki.cgi",
100 description => "url to the ikiwiki.cgi",
107 example => "/var/www/wiki/ikiwiki.cgi",
108 description => "filename of cgi wrapper to generate",
115 description => "mode for cgi_wrapper (can safely be made suid)",
122 description => "rcs backend to use",
123 safe => 0, # don't allow overriding
128 default => [qw{mdwn link inline meta htmlscrubber passwordauth
129 openid signinedit lockedit conditional
130 recentchanges parentlinks editpage}],
131 description => "plugins to enable by default",
138 description => "plugins to add to the default configuration",
145 description => "plugins to disable",
151 default => "$installdir/share/ikiwiki/templates",
152 description => "location of template files",
160 description => "additional directories containing template files",
166 default => "$installdir/share/ikiwiki/basewiki",
167 description => "base wiki source location",
174 default => "$installdir/share/ikiwiki",
175 description => "parent directory containing additional underlays",
182 description => "wrappers to generate",
189 description => "additional underlays to use",
196 description => "display verbose messages?",
203 description => "log to syslog?",
210 description => "create output files named page/index.html?",
211 safe => 0, # changing requires manual transition
214 prefix_directives => {
217 description => "use '!'-prefixed preprocessor directives?",
218 safe => 0, # changing requires manual transition
224 description => "use page/index.mdwn source files",
231 description => "enable Discussion pages?",
237 default => gettext("Discussion"),
238 description => "name of Discussion pages",
245 description => "only send cookies over SSL connections?",
253 description => "extension to use for new pages",
254 safe => 0, # not sanitized
260 description => "extension to use for html files",
261 safe => 0, # not sanitized
267 description => "strftime format string to display date",
275 example => "en_US.UTF-8",
276 description => "UTF-8 locale to use",
285 description => "put user pages below specified page",
292 description => "how many backlinks to show before hiding excess (0 to show all)",
299 description => "attempt to hardlink source files? (optimisation for large files)",
301 safe => 0, # paranoia
307 description => "force ikiwiki to use a particular umask",
309 safe => 0, # paranoia
314 example => "ikiwiki",
315 description => "group for wrappers to run in",
317 safe => 0, # paranoia
323 example => "$ENV{HOME}/.ikiwiki/",
324 description => "extra library and plugin directory",
326 safe => 0, # directory
332 description => "environment variables",
333 safe => 0, # paranoia
340 description => "regexp of source files to ignore",
345 wiki_file_prune_regexps => {
347 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
348 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
349 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
350 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
351 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
352 description => "regexps of source files to ignore",
358 description => "specifies the characters that are allowed in source filenames",
359 default => "-[:alnum:]+/.:_",
363 wiki_file_regexp => {
365 description => "regexp of legal source files",
369 web_commit_regexp => {
371 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
372 description => "regexp to parse web commits from logs",
379 description => "run as a cgi",
383 cgi_disable_uploads => {
386 description => "whether CGI should accept file uploads",
393 description => "run as a post-commit hook",
400 description => "running in rebuild mode",
407 description => "running in setup mode",
414 description => "running in refresh mode",
421 description => "running in receive test mode",
428 description => "running in getctime mode",
435 description => "running in w3mmode",
442 description => "path to the .ikiwiki directory holding ikiwiki state",
449 description => "path to setup file",
453 allow_symlinks_before_srcdir => {
456 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
462 sub defaultconfig () {
465 foreach my $key (keys %s) {
466 push @ret, $key, $s{$key}->{default};
473 # locale stuff; avoid LC_ALL since it overrides everything
474 if (defined $ENV{LC_ALL}) {
475 $ENV{LANG} = $ENV{LC_ALL};
478 if (defined $config{locale}) {
479 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
480 $ENV{LANG}=$config{locale};
485 if (! defined $config{wiki_file_regexp}) {
486 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
489 if (ref $config{ENV} eq 'HASH') {
490 foreach my $val (keys %{$config{ENV}}) {
491 $ENV{$val}=$config{ENV}{$val};
495 if ($config{w3mmode}) {
496 eval q{use Cwd q{abs_path}};
498 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
499 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
500 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
501 unless $config{cgiurl} =~ m!file:///!;
502 $config{url}="file://".$config{destdir};
505 if ($config{cgi} && ! length $config{url}) {
506 error(gettext("Must specify url to wiki with --url when using --cgi"));
509 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
510 unless exists $config{wikistatedir} && defined $config{wikistatedir};
512 if (defined $config{umask}) {
513 umask(possibly_foolish_untaint($config{umask}));
516 run_hooks(checkconfig => sub { shift->() });
524 foreach my $dir (@INC, $config{libdir}) {
525 next unless defined $dir && length $dir;
526 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
527 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
531 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
532 next unless defined $dir && length $dir;
533 foreach my $file (glob("$dir/plugins/*")) {
534 $ret{basename($file)}=1 if -x $file;
542 if (defined $config{libdir} && length $config{libdir}) {
543 unshift @INC, possibly_foolish_untaint($config{libdir});
546 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
551 if (exists $hooks{rcs}) {
552 error(gettext("cannot use multiple rcs plugins"));
554 loadplugin($config{rcs});
556 if (! exists $hooks{rcs}) {
560 run_hooks(getopt => sub { shift->() });
561 if (grep /^-/, @ARGV) {
562 print STDERR "Unknown option (or missing parameter): $_\n"
563 foreach grep /^-/, @ARGV;
573 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
575 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
576 "$installdir/lib/ikiwiki") {
577 if (defined $dir && -x "$dir/plugins/$plugin") {
578 eval { require IkiWiki::Plugin::external };
581 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
583 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
584 $loaded_plugins{$plugin}=1;
589 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
592 error("Failed to load plugin $mod: $@");
594 $loaded_plugins{$plugin}=1;
601 log_message('err' => $message) if $config{syslog};
602 if (defined $cleaner) {
609 return unless $config{verbose};
610 return log_message(debug => @_);
614 sub log_message ($$) {
617 if ($config{syslog}) {
620 Sys::Syslog::setlogsock('unix');
621 Sys::Syslog::openlog('ikiwiki', '', 'user');
625 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
628 elsif (! $config{cgi}) {
632 return print STDERR "@_\n";
636 sub possibly_foolish_untaint ($) {
638 my ($untainted)=$tainted=~/(.*)/s;
658 return exists $pagesources{$page} &&
659 $pagesources{$page} =~ /\._([^.]+)$/;
665 if ($file =~ /\.([^.]+)$/) {
666 return $1 if exists $hooks{htmlize}{$1};
668 my $base=basename($file);
669 if (exists $hooks{htmlize}{$base} &&
670 $hooks{htmlize}{$base}{noextension}) {
681 if (exists $pagename_cache{$file}) {
682 return $pagename_cache{$file};
685 my $type=pagetype($file);
687 $page=~s/\Q.$type\E*$//
688 if defined $type && !$hooks{htmlize}{$type}{keepextension}
689 && !$hooks{htmlize}{$type}{noextension};
690 if ($config{indexpages} && $page=~/(.*)\/index$/) {
694 $pagename_cache{$file} = $page;
698 sub newpagefile ($$) {
702 if (! $config{indexpages} || $page eq 'index') {
703 return $page.".".$type;
706 return $page."/index.".$type;
710 sub targetpage ($$;$) {
715 if (defined $filename) {
716 return $page."/".$filename.".".$ext;
718 elsif (! $config{usedirs} || $page eq 'index') {
719 return $page.".".$ext;
722 return $page."/index.".$ext;
729 return targetpage($page, $config{htmlext});
736 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
737 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
738 return "$dir/$file", stat(_) if -e "$dir/$file";
740 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
745 return (srcfile_stat(@_))[0];
748 sub add_underlay ($) {
752 $dir="$config{underlaydirbase}/$dir";
755 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
756 unshift @{$config{underlaydirs}}, $dir;
762 sub readfile ($;$$) {
768 error("cannot read a symlink ($file)");
772 open (my $in, "<", $file) || error("failed to read $file: $!");
773 binmode($in) if ($binary);
774 return \*$in if $wantfd;
776 # check for invalid utf-8, and toss it back to avoid crashes
777 if (! utf8::valid($ret)) {
778 $ret=encode_utf8($ret);
780 close $in || error("failed to read $file: $!");
784 sub prep_writefile ($$) {
789 while (length $test) {
790 if (-l "$destdir/$test") {
791 error("cannot write to a symlink ($test)");
793 $test=dirname($test);
796 my $dir=dirname("$destdir/$file");
799 foreach my $s (split(m!/+!, $dir)) {
802 mkdir($d) || error("failed to create directory $d: $!");
810 sub writefile ($$$;$$) {
811 my $file=shift; # can include subdirs
812 my $destdir=shift; # directory to put file in
817 prep_writefile($file, $destdir);
819 my $newfile="$destdir/$file.ikiwiki-new";
821 error("cannot write to a symlink ($newfile)");
824 my $cleanup = sub { unlink($newfile) };
825 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
826 binmode($out) if ($binary);
828 $writer->(\*$out, $cleanup);
831 print $out $content or error("failed writing to $newfile: $!", $cleanup);
833 close $out || error("failed saving $newfile: $!", $cleanup);
834 rename($newfile, "$destdir/$file") ||
835 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
841 sub will_render ($$;$) {
846 # Important security check.
847 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
848 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
849 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
852 if (! $clear || $cleared{$page}) {
853 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
856 foreach my $old (@{$renderedfiles{$page}}) {
857 delete $destsources{$old};
859 $renderedfiles{$page}=[$dest];
862 $destsources{$dest}=$page;
872 if ($link=~s/^\/+//) {
880 $l.="/" if length $l;
883 if (exists $links{$l}) {
886 elsif (exists $pagecase{lc $l}) {
887 return $pagecase{lc $l};
889 } while $cwd=~s{/?[^/]+$}{};
891 if (length $config{userdir}) {
892 my $l = "$config{userdir}/".lc($link);
893 if (exists $links{$l}) {
896 elsif (exists $pagecase{lc $l}) {
897 return $pagecase{lc $l};
901 #print STDERR "warning: page $page, broken link: $link\n";
905 sub isinlinableimage ($) {
908 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
911 sub pagetitle ($;$) {
916 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
919 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
927 # support use w/o %config set
928 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
929 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
935 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
936 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
943 return $config{cgiurl}."?".
944 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
950 return "$config{url}/" if ! defined $page;
952 $page=htmlpage($page);
954 $page=~s/[^\/]+\//..\//g;
959 # Work around very innefficient behavior in File::Spec if abs2rel
960 # is passed two relative paths. It's much faster if paths are
961 # absolute! (Debian bug #376658; fixed in debian unstable now)
966 my $ret=File::Spec->abs2rel($path, $base);
967 $ret=~s/^// if defined $ret;
971 sub displaytime ($;$) {
972 # Plugins can override this function to mark up the time to
974 return '<span class="date">'.formattime(@_).'</span>';
977 sub formattime ($;$) {
978 # Plugins can override this function to format the time.
981 if (! defined $format) {
982 $format=$config{timeformat};
985 # strftime doesn't know about encodings, so make sure
986 # its output is properly treated as utf8
987 return decode_utf8(POSIX::strftime($format, localtime($time)));
990 sub beautify_urlpath ($) {
993 # Ensure url is not an empty link, and if necessary,
994 # add ./ to avoid colon confusion.
995 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
999 if ($config{usedirs}) {
1000 $url =~ s!/index.$config{htmlext}$!/!;
1012 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1015 if (! $destsources{$to}) {
1020 return $config{url}.beautify_urlpath("/".$to);
1023 my $link = abs2rel($to, dirname(htmlpage($from)));
1025 return beautify_urlpath($link);
1028 sub htmllink ($$$;@) {
1029 my $lpage=shift; # the page doing the linking
1030 my $page=shift; # the page that will contain the link (different for inline)
1037 if (! $opts{forcesubpage}) {
1038 $bestlink=bestlink($lpage, $link);
1041 $bestlink="$lpage/".lc($link);
1045 if (defined $opts{linktext}) {
1046 $linktext=$opts{linktext};
1049 $linktext=pagetitle(basename($link));
1052 return "<span class=\"selflink\">$linktext</span>"
1053 if length $bestlink && $page eq $bestlink &&
1054 ! defined $opts{anchor};
1056 if (! $destsources{$bestlink}) {
1057 $bestlink=htmlpage($bestlink);
1059 if (! $destsources{$bestlink}) {
1060 return $linktext unless length $config{cgiurl};
1061 return "<span class=\"createlink\"><a href=\"".
1067 "\" rel=\"nofollow\">?</a>$linktext</span>"
1071 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1072 $bestlink=beautify_urlpath($bestlink);
1074 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1075 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1078 if (defined $opts{anchor}) {
1079 $bestlink.="#".$opts{anchor};
1083 if (defined $opts{rel}) {
1084 push @attrs, ' rel="'.$opts{rel}.'"';
1086 if (defined $opts{class}) {
1087 push @attrs, ' class="'.$opts{class}.'"';
1090 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1093 sub openiduser ($) {
1096 if ($user =~ m!^https?://! &&
1097 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1100 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1101 # this works in at least 2.x
1102 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1105 # this only works in 1.x
1106 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1107 $display=$oid->display;
1110 # Convert "user.somehost.com" to "user [somehost.com]"
1111 # (also "user.somehost.co.uk")
1112 if ($display !~ /\[/) {
1113 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1115 # Convert "http://somehost.com/user" to "user [somehost.com]".
1116 # (also "https://somehost.com/user/")
1117 if ($display !~ /\[/) {
1118 $display=~s/^https?:\/\/(.+)\/([^\/]+)\/?$/$2 [$1]/;
1120 $display=~s!^https?://!!; # make sure this is removed
1121 eval q{use CGI 'escapeHTML'};
1123 return escapeHTML($display);
1131 my $oiduser=eval { openiduser($user) };
1132 if (defined $oiduser) {
1133 return "<a href=\"$user\">$oiduser</a>";
1136 eval q{use CGI 'escapeHTML'};
1139 return htmllink("", "", escapeHTML(
1140 length $config{userdir} ? $config{userdir}."/".$user : $user
1141 ), noimageinline => 1);
1145 sub htmlize ($$$$) {
1151 my $oneline = $content !~ /\n/;
1153 if (exists $hooks{htmlize}{$type}) {
1154 $content=$hooks{htmlize}{$type}{call}->(
1156 content => $content,
1160 error("htmlization of $type not supported");
1163 run_hooks(sanitize => sub {
1166 destpage => $destpage,
1167 content => $content,
1172 # hack to get rid of enclosing junk added by markdown
1173 # and other htmlizers
1174 $content=~s/^<p>//i;
1175 $content=~s/<\/p>$//i;
1187 run_hooks(linkify => sub {
1190 destpage => $destpage,
1191 content => $content,
1199 our $preprocess_preview=0;
1200 sub preprocess ($$$;$$) {
1201 my $page=shift; # the page the data comes from
1202 my $destpage=shift; # the page the data will appear in (different for inline)
1207 # Using local because it needs to be set within any nested calls
1209 local $preprocess_preview=$preview if defined $preview;
1216 $params="" if ! defined $params;
1218 if (length $escape) {
1219 return "[[$prefix$command $params]]";
1221 elsif (exists $hooks{preprocess}{$command}) {
1222 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1223 # Note: preserve order of params, some plugins may
1224 # consider it significant.
1226 while ($params =~ m{
1227 (?:([-\w]+)=)? # 1: named parameter key?
1229 """(.*?)""" # 2: triple-quoted value
1231 "([^"]+)" # 3: single-quoted value
1233 (\S+) # 4: unquoted value
1235 (?:\s+|$) # delimiter to next param
1245 elsif (defined $3) {
1248 elsif (defined $4) {
1253 push @params, $key, $val;
1256 push @params, $val, '';
1259 if ($preprocessing{$page}++ > 3) {
1260 # Avoid loops of preprocessed pages preprocessing
1261 # other pages that preprocess them, etc.
1262 return "[[!$command <span class=\"error\">".
1263 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1264 $page, $preprocessing{$page}).
1270 $hooks{preprocess}{$command}{call}->(
1273 destpage => $destpage,
1274 preview => $preprocess_preview,
1280 $ret="[[!$command <span class=\"error\">".
1281 gettext("Error").": $error"."</span>]]";
1285 # use void context during scan pass
1287 $hooks{preprocess}{$command}{call}->(
1290 destpage => $destpage,
1291 preview => $preprocess_preview,
1296 $preprocessing{$page}--;
1300 return "[[$prefix$command $params]]";
1305 if ($config{prefix_directives}) {
1308 \[\[(!) # directive open; 2: prefix
1309 ([-\w]+) # 3: command
1310 ( # 4: the parameters..
1311 \s+ # Must have space if parameters present
1313 (?:[-\w]+=)? # named parameter key?
1315 """.*?""" # triple-quoted value
1317 "[^"]+" # single-quoted value
1319 [^"\s\]]+ # unquoted value
1321 \s* # whitespace or end
1324 *)? # 0 or more parameters
1325 \]\] # directive closed
1331 \[\[(!?) # directive open; 2: optional prefix
1332 ([-\w]+) # 3: command
1334 ( # 4: the parameters..
1336 (?:[-\w]+=)? # named parameter key?
1338 """.*?""" # triple-quoted value
1340 "[^"]+" # single-quoted value
1342 [^"\s\]]+ # unquoted value
1344 \s* # whitespace or end
1347 *) # 0 or more parameters
1348 \]\] # directive closed
1352 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1361 run_hooks(filter => sub {
1362 $content=shift->(page => $page, destpage => $destpage,
1363 content => $content);
1370 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1373 sub check_canedit ($$$;$) {
1380 run_hooks(canedit => sub {
1381 return if defined $canedit;
1382 my $ret=shift->($page, $q, $session);
1387 elsif (ref $ret eq 'CODE') {
1388 $ret->() unless $nonfatal;
1391 elsif (defined $ret) {
1392 error($ret) unless $nonfatal;
1397 return defined $canedit ? $canedit : 1;
1400 sub check_content (@) {
1403 return 1 if ! exists $hooks{checkcontent}; # optimisation
1405 if (exists $pagesources{$params{page}}) {
1407 my %old=map { $_ => 1 }
1408 split("\n", readfile(srcfile($pagesources{$params{page}})));
1409 foreach my $line (split("\n", $params{content})) {
1410 push @diff, $line if ! exists $old{$_};
1412 $params{diff}=join("\n", @diff);
1416 run_hooks(checkcontent => sub {
1417 return if defined $ok;
1418 my $ret=shift->(%params);
1423 elsif (ref $ret eq 'CODE') {
1424 $ret->() unless $params{nonfatal};
1427 elsif (defined $ret) {
1428 error($ret) unless $params{nonfatal};
1434 return defined $ok ? $ok : 1;
1440 # Take an exclusive lock on the wiki to prevent multiple concurrent
1441 # run issues. The lock will be dropped on program exit.
1442 if (! -d $config{wikistatedir}) {
1443 mkdir($config{wikistatedir});
1445 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1446 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1447 if (! flock($wikilock, 2)) { # LOCK_EX
1448 error("failed to get lock");
1454 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1455 return close($wikilock) if $wikilock;
1461 sub commit_hook_enabled () {
1462 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1463 error("cannot write to $config{wikistatedir}/commitlock: $!");
1464 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1465 close($commitlock) || error("failed closing commitlock: $!");
1468 close($commitlock) || error("failed closing commitlock: $!");
1472 sub disable_commit_hook () {
1473 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1474 error("cannot write to $config{wikistatedir}/commitlock: $!");
1475 if (! flock($commitlock, 2)) { # LOCK_EX
1476 error("failed to get commit lock");
1481 sub enable_commit_hook () {
1482 return close($commitlock) if $commitlock;
1487 %oldrenderedfiles=%pagectime=();
1488 if (! $config{rebuild}) {
1489 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1490 %destsources=%renderedfiles=%pagecase=%pagestate=
1494 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1495 if (-e "$config{wikistatedir}/index") {
1496 system("ikiwiki-transition", "indexdb", $config{srcdir});
1497 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1504 my $index=Storable::fd_retrieve($in);
1505 if (! defined $index) {
1510 if (exists $index->{version} && ! ref $index->{version}) {
1511 $pages=$index->{page};
1512 %wikistate=%{$index->{state}};
1519 foreach my $src (keys %$pages) {
1520 my $d=$pages->{$src};
1521 my $page=pagename($src);
1522 $pagectime{$page}=$d->{ctime};
1523 if (! $config{rebuild}) {
1524 $pagesources{$page}=$src;
1525 $pagemtime{$page}=$d->{mtime};
1526 $renderedfiles{$page}=$d->{dest};
1527 if (exists $d->{links} && ref $d->{links}) {
1528 $links{$page}=$d->{links};
1529 $oldlinks{$page}=[@{$d->{links}}];
1531 if (ref $d->{depends_simple} eq 'ARRAY') {
1533 $depends_simple{$page}={
1534 map { $_ => 1 } @{$d->{depends_simple}}
1537 elsif (exists $d->{depends_simple}) {
1538 $depends{$page}=$d->{depends_simple};
1540 if (exists $d->{dependslist}) {
1543 map { $_ => $DEPEND_CONTENT | $DEPEND_EXISTS }
1544 @{$d->{dependslist}}
1547 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1549 $depends{$page}={$d->{depends} => $DEPEND_CONTENT | $DEPEND_EXISTS};
1551 elsif (exists $d->{depends}) {
1552 $depends{$page}=$d->{depends};
1554 if (exists $d->{state}) {
1555 $pagestate{$page}=$d->{state};
1558 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1560 foreach my $page (keys %pagesources) {
1561 $pagecase{lc $page}=$page;
1563 foreach my $page (keys %renderedfiles) {
1564 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1570 run_hooks(savestate => sub { shift->() });
1573 foreach my $type (keys %hooks) {
1574 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1576 my @hookids=keys %hookids;
1578 if (! -d $config{wikistatedir}) {
1579 mkdir($config{wikistatedir});
1581 my $newfile="$config{wikistatedir}/indexdb.new";
1582 my $cleanup = sub { unlink($newfile) };
1583 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1586 foreach my $page (keys %pagemtime) {
1587 next unless $pagemtime{$page};
1588 my $src=$pagesources{$page};
1590 $index{page}{$src}={
1591 ctime => $pagectime{$page},
1592 mtime => $pagemtime{$page},
1593 dest => $renderedfiles{$page},
1594 links => $links{$page},
1597 if (exists $depends{$page}) {
1598 $index{page}{$src}{depends} = $depends{$page};
1601 if (exists $depends_simple{$page}) {
1602 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1605 if (exists $pagestate{$page}) {
1606 foreach my $id (@hookids) {
1607 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1608 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1615 foreach my $id (@hookids) {
1616 foreach my $key (keys %{$wikistate{$id}}) {
1617 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1621 $index{version}="3";
1622 my $ret=Storable::nstore_fd(\%index, $out);
1623 return if ! defined $ret || ! $ret;
1624 close $out || error("failed saving to $newfile: $!", $cleanup);
1625 rename($newfile, "$config{wikistatedir}/indexdb") ||
1626 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1631 sub template_file ($) {
1634 foreach my $dir ($config{templatedir}, @{$config{templatedirs}},
1635 "$installdir/share/ikiwiki/templates") {
1636 return "$dir/$template" if -e "$dir/$template";
1641 sub template_params (@) {
1642 my $filename=template_file(shift);
1644 if (! defined $filename) {
1645 return if wantarray;
1651 my $text_ref = shift;
1652 ${$text_ref} = decode_utf8(${$text_ref});
1654 filename => $filename,
1655 loop_context_vars => 1,
1656 die_on_bad_params => 0,
1659 return wantarray ? @ret : {@ret};
1662 sub template ($;@) {
1663 require HTML::Template;
1664 return HTML::Template->new(template_params(@_));
1667 sub misctemplate ($$;@) {
1671 my $template=template("misc.tmpl");
1674 indexlink => indexlink(),
1675 wikiname => $config{wikiname},
1676 pagebody => $pagebody,
1677 baseurl => baseurl(),
1680 run_hooks(pagetemplate => sub {
1681 shift->(page => "", destpage => "", template => $template);
1683 return $template->output;
1689 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1690 error 'hook requires type, call, and id parameters';
1693 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1695 $hooks{$param{type}}{$param{id}}=\%param;
1699 sub run_hooks ($$) {
1700 # Calls the given sub for each hook of the given type,
1701 # passing it the hook function to call.
1705 if (exists $hooks{$type}) {
1706 my (@first, @middle, @last);
1707 foreach my $id (keys %{$hooks{$type}}) {
1708 if ($hooks{$type}{$id}{first}) {
1711 elsif ($hooks{$type}{$id}{last}) {
1718 foreach my $id (@first, @middle, @last) {
1719 $sub->($hooks{$type}{$id}{call});
1727 $hooks{rcs}{rcs_update}{call}->(@_);
1730 sub rcs_prepedit ($) {
1731 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1734 sub rcs_commit ($$$;$$) {
1735 $hooks{rcs}{rcs_commit}{call}->(@_);
1738 sub rcs_commit_staged ($$$) {
1739 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1743 $hooks{rcs}{rcs_add}{call}->(@_);
1746 sub rcs_remove ($) {
1747 $hooks{rcs}{rcs_remove}{call}->(@_);
1750 sub rcs_rename ($$) {
1751 $hooks{rcs}{rcs_rename}{call}->(@_);
1754 sub rcs_recentchanges ($) {
1755 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1759 $hooks{rcs}{rcs_diff}{call}->(@_);
1762 sub rcs_getctime ($) {
1763 $hooks{rcs}{rcs_getctime}{call}->(@_);
1766 sub rcs_receive () {
1767 $hooks{rcs}{rcs_receive}{call}->();
1770 sub add_depends ($$;@) {
1774 my $simple=$pagespec =~ /$config{wiki_file_regexp}/ &&
1775 $pagespec !~ /[\s*?()!]/;
1777 my $deptype=$DEPEND_CONTENT | $DEPEND_EXISTS;
1780 if (defined $params{content} && $params{content} == 0 &&
1781 ($simple || pagespec_contentless($pagespec))) {
1782 $deptype=$deptype & ~$DEPEND_CONTENT;
1787 $depends_simple{$page}{lc $pagespec} |= $deptype;
1791 return unless pagespec_valid($pagespec);
1793 $depends{$page}{$pagespec} |= $deptype;
1797 sub file_pruned ($$) {
1799 my $file=File::Spec->canonpath(shift);
1800 my $base=File::Spec->canonpath(shift);
1801 $file =~ s#^\Q$base\E/+##;
1803 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1804 return $file =~ m/$regexp/ && $file ne $base;
1807 sub define_gettext () {
1808 # If translation is needed, redefine the gettext function to do it.
1809 # Otherwise, it becomes a quick no-op.
1810 no warnings 'redefine';
1811 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1812 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1813 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1815 my $gettext_obj=eval q{
1816 use Locale::gettext q{textdomain};
1817 Locale::gettext->domain('ikiwiki')
1821 $gettext_obj->get(shift);
1829 *gettext=sub { return shift };
1841 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1845 # Injects a new function into the symbol table to replace an
1846 # exported function.
1849 # This is deep ugly perl foo, beware.
1852 if (! defined $params{parent}) {
1853 $params{parent}='::';
1854 $params{old}=\&{$params{name}};
1855 $params{name}=~s/.*:://;
1857 my $parent=$params{parent};
1858 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1859 $ns = $params{parent} . $ns;
1860 inject(%params, parent => $ns) unless $ns eq '::main::';
1861 *{$ns . $params{name}} = $params{call}
1862 if exists ${$ns}{$params{name}} &&
1863 \&{${$ns}{$params{name}}} == $params{old};
1873 push @{$links{$page}}, $link
1874 unless grep { $_ eq $link } @{$links{$page}};
1877 sub pagespec_translate ($) {
1880 # Convert spec to perl code.
1884 \s* # ignore whitespace
1885 ( # 1: match a single word
1892 \w+\([^\)]*\) # command(params)
1894 [^\s()]+ # any other text
1896 \s* # ignore whitespace
1899 if (lc $word eq 'and') {
1902 elsif (lc $word eq 'or') {
1905 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1908 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1909 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1911 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
1914 push @data, qq{unknown function in pagespec "$word"};
1915 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
1920 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
1924 if (! length $code) {
1925 $code="IkiWiki::FailReason->new('empty pagespec')";
1929 return eval 'sub { my $page=shift; '.$code.' }';
1932 sub pagespec_match ($$;@) {
1937 # Backwards compatability with old calling convention.
1939 unshift @params, 'location';
1942 my $sub=pagespec_translate($spec);
1943 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
1944 if $@ || ! defined $sub;
1945 return $sub->($page, @params);
1948 sub pagespec_match_list ($$;@) {
1953 my $sub=pagespec_translate($spec);
1954 error "syntax error in pagespec \"$spec\""
1955 if $@ || ! defined $sub;
1959 foreach my $page (@$pages) {
1960 $r=$sub->($page, @params);
1961 push @ret, $page if $r;
1964 if (! @ret && defined $r && $r->isa("IkiWiki::ErrorReason")) {
1965 error(sprintf(gettext("cannot match pages: %s"), $r));
1972 sub pagespec_valid ($) {
1975 my $sub=pagespec_translate($spec);
1979 sub pagespec_contentless ($) {
1983 (\w+)\([^\)]*\) # only match pagespec functions
1985 return 0 unless $1=~/^(glob|internal|creation_month|creation_day|creation_year|created_before|created_after)$/;
1992 my $re=quotemeta(shift);
1998 package IkiWiki::FailReason;
2001 '""' => sub { ${$_[0]} },
2003 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2010 return bless \$value, $class;
2013 package IkiWiki::ErrorReason;
2015 our @ISA = 'IkiWiki::FailReason';
2017 package IkiWiki::SuccessReason;
2020 '""' => sub { ${$_[0]} },
2022 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2029 return bless \$value, $class;
2032 package IkiWiki::PageSpec;
2038 if ($path =~ m!^\./!) {
2039 $from=~s#/?[^/]+$## if defined $from;
2041 $path="$from/$path" if length $from;
2047 sub match_glob ($$;@) {
2052 $glob=derel($glob, $params{location});
2054 my $regexp=IkiWiki::glob2re($glob);
2055 if ($page=~/^$regexp$/i) {
2056 if (! IkiWiki::isinternal($page) || $params{internal}) {
2057 return IkiWiki::SuccessReason->new("$glob matches $page");
2060 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2064 return IkiWiki::FailReason->new("$glob does not match $page");
2068 sub match_internal ($$;@) {
2069 return match_glob($_[0], $_[1], @_, internal => 1)
2072 sub match_link ($$;@) {
2077 $link=derel($link, $params{location});
2078 my $from=exists $params{location} ? $params{location} : '';
2080 my $links = $IkiWiki::links{$page};
2081 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
2082 my $bestlink = IkiWiki::bestlink($from, $link);
2083 foreach my $p (@{$links}) {
2084 if (length $bestlink) {
2085 return IkiWiki::SuccessReason->new("$page links to $link")
2086 if $bestlink eq IkiWiki::bestlink($page, $p);
2089 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
2090 if match_glob($p, $link, %params);
2091 my ($p_rel)=$p=~/^\/?(.*)/;
2093 return IkiWiki::SuccessReason->new("$page links to page $p_rel matching $link")
2094 if match_glob($p_rel, $link, %params);
2097 return IkiWiki::FailReason->new("$page does not link to $link");
2100 sub match_backlink ($$;@) {
2101 return match_link($_[1], $_[0], @_);
2104 sub match_created_before ($$;@) {
2109 $testpage=derel($testpage, $params{location});
2111 if (exists $IkiWiki::pagectime{$testpage}) {
2112 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2113 return IkiWiki::SuccessReason->new("$page created before $testpage");
2116 return IkiWiki::FailReason->new("$page not created before $testpage");
2120 return IkiWiki::ErrorReason->new("$testpage does not exist");
2124 sub match_created_after ($$;@) {
2129 $testpage=derel($testpage, $params{location});
2131 if (exists $IkiWiki::pagectime{$testpage}) {
2132 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2133 return IkiWiki::SuccessReason->new("$page created after $testpage");
2136 return IkiWiki::FailReason->new("$page not created after $testpage");
2140 return IkiWiki::ErrorReason->new("$testpage does not exist");
2144 sub match_creation_day ($$;@) {
2145 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2146 return IkiWiki::SuccessReason->new('creation_day matched');
2149 return IkiWiki::FailReason->new('creation_day did not match');
2153 sub match_creation_month ($$;@) {
2154 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2155 return IkiWiki::SuccessReason->new('creation_month matched');
2158 return IkiWiki::FailReason->new('creation_month did not match');
2162 sub match_creation_year ($$;@) {
2163 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2164 return IkiWiki::SuccessReason->new('creation_year matched');
2167 return IkiWiki::FailReason->new('creation_year did not match');
2171 sub match_user ($$;@) {
2176 if (! exists $params{user}) {
2177 return IkiWiki::ErrorReason->new("no user specified");
2180 if (defined $params{user} && lc $params{user} eq lc $user) {
2181 return IkiWiki::SuccessReason->new("user is $user");
2183 elsif (! defined $params{user}) {
2184 return IkiWiki::FailReason->new("not logged in");
2187 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2191 sub match_admin ($$;@) {
2196 if (! exists $params{user}) {
2197 return IkiWiki::ErrorReason->new("no user specified");
2200 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2201 return IkiWiki::SuccessReason->new("user is an admin");
2203 elsif (! defined $params{user}) {
2204 return IkiWiki::FailReason->new("not logged in");
2207 return IkiWiki::FailReason->new("user is not an admin");
2211 sub match_ip ($$;@) {
2216 if (! exists $params{ip}) {
2217 return IkiWiki::ErrorReason->new("no IP specified");
2220 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2221 return IkiWiki::SuccessReason->new("IP is $ip");
2224 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");