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 %hooks %forcerebuild
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");
41 description => "name of the wiki",
48 example => 'me@example.com',
49 description => "contact email for wiki",
56 description => "users who are wiki admins",
63 description => "users who are banned from the wiki",
70 example => "$ENV{HOME}/wiki",
71 description => "where the source of the wiki is located",
78 example => "/var/www/wiki",
79 description => "where to build the wiki",
86 example => "http://example.com/wiki",
87 description => "base url to the wiki",
94 example => "http://example.com/wiki/ikiwiki.cgi",
95 description => "url to the ikiwiki.cgi",
102 example => "/var/www/wiki/ikiwiki.cgi",
103 description => "filename of cgi wrapper to generate",
110 description => "mode for cgi_wrapper (can safely be made suid)",
117 description => "rcs backend to use",
118 safe => 0, # don't allow overriding
123 default => [qw{mdwn link inline meta htmlscrubber passwordauth
124 openid signinedit lockedit conditional
125 recentchanges parentlinks editpage}],
126 description => "plugins to enable by default",
133 description => "plugins to add to the default configuration",
140 description => "plugins to disable",
146 default => "$installdir/share/ikiwiki/templates",
147 description => "location of template files",
154 default => "$installdir/share/ikiwiki/basewiki",
155 description => "base wiki source location",
162 default => "$installdir/share/ikiwiki",
163 description => "parent directory containing additional underlays",
170 description => "wrappers to generate",
177 description => "additional underlays to use",
184 description => "display verbose messages?",
191 description => "log to syslog?",
198 description => "create output files named page/index.html?",
199 safe => 0, # changing requires manual transition
202 prefix_directives => {
205 description => "use '!'-prefixed preprocessor directives?",
206 safe => 0, # changing requires manual transition
212 description => "use page/index.mdwn source files",
219 description => "enable Discussion pages?",
226 description => "only send cookies over SSL connections?",
234 description => "extension to use for new pages",
235 safe => 0, # not sanitized
241 description => "extension to use for html files",
242 safe => 0, # not sanitized
248 description => "strftime format string to display date",
256 example => "en_US.UTF-8",
257 description => "UTF-8 locale to use",
266 description => "put user pages below specified page",
273 description => "how many backlinks to show before hiding excess (0 to show all)",
280 description => "attempt to hardlink source files? (optimisation for large files)",
282 safe => 0, # paranoia
288 description => "force ikiwiki to use a particular umask",
290 safe => 0, # paranoia
295 example => "ikiwiki",
296 description => "group for wrappers to run in",
298 safe => 0, # paranoia
304 example => "$ENV{HOME}/.ikiwiki/",
305 description => "extra library and plugin directory",
307 safe => 0, # directory
313 description => "environment variables",
314 safe => 0, # paranoia
321 description => "regexp of source files to ignore",
326 wiki_file_prune_regexps => {
328 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
329 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
330 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
331 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
333 description => "regexps of source files to ignore",
339 description => "specifies the characters that are allowed in source filenames",
340 default => "-[:alnum:]+/.:_",
344 wiki_file_regexp => {
346 description => "regexp of legal source files",
350 web_commit_regexp => {
352 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
353 description => "regexp to parse web commits from logs",
360 description => "run as a cgi",
364 cgi_disable_uploads => {
367 description => "whether CGI should accept file uploads",
374 description => "run as a post-commit hook",
381 description => "running in rebuild mode",
388 description => "running in setup mode",
395 description => "running in refresh mode",
402 description => "running in receive test mode",
409 description => "running in getctime mode",
416 description => "running in w3mmode",
423 description => "path to the .ikiwiki directory holding ikiwiki state",
430 description => "path to setup file",
434 allow_symlinks_before_srcdir => {
437 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
443 sub defaultconfig () {
446 foreach my $key (keys %s) {
447 push @ret, $key, $s{$key}->{default};
454 # locale stuff; avoid LC_ALL since it overrides everything
455 if (defined $ENV{LC_ALL}) {
456 $ENV{LANG} = $ENV{LC_ALL};
459 if (defined $config{locale}) {
460 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
461 $ENV{LANG}=$config{locale};
466 if (! defined $config{wiki_file_regexp}) {
467 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
470 if (ref $config{ENV} eq 'HASH') {
471 foreach my $val (keys %{$config{ENV}}) {
472 $ENV{$val}=$config{ENV}{$val};
476 if ($config{w3mmode}) {
477 eval q{use Cwd q{abs_path}};
479 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
480 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
481 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
482 unless $config{cgiurl} =~ m!file:///!;
483 $config{url}="file://".$config{destdir};
486 if ($config{cgi} && ! length $config{url}) {
487 error(gettext("Must specify url to wiki with --url when using --cgi"));
490 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
491 unless exists $config{wikistatedir} && defined $config{wikistatedir};
493 if (defined $config{umask}) {
494 umask(possibly_foolish_untaint($config{umask}));
497 run_hooks(checkconfig => sub { shift->() });
505 foreach my $dir (@INC, $config{libdir}) {
506 next unless defined $dir && length $dir;
507 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
508 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
512 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
513 next unless defined $dir && length $dir;
514 foreach my $file (glob("$dir/plugins/*")) {
515 $ret{basename($file)}=1 if -x $file;
523 if (defined $config{libdir} && length $config{libdir}) {
524 unshift @INC, possibly_foolish_untaint($config{libdir});
527 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
532 if (exists $IkiWiki::hooks{rcs}) {
533 error(gettext("cannot use multiple rcs plugins"));
535 loadplugin($config{rcs});
537 if (! exists $IkiWiki::hooks{rcs}) {
541 run_hooks(getopt => sub { shift->() });
542 if (grep /^-/, @ARGV) {
543 print STDERR "Unknown option (or missing parameter): $_\n"
544 foreach grep /^-/, @ARGV;
554 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
556 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
557 "$installdir/lib/ikiwiki") {
558 if (defined $dir && -x "$dir/plugins/$plugin") {
559 eval { require IkiWiki::Plugin::external };
562 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
564 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
565 $loaded_plugins{$plugin}=1;
570 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
573 error("Failed to load plugin $mod: $@");
575 $loaded_plugins{$plugin}=1;
582 log_message('err' => $message) if $config{syslog};
583 if (defined $cleaner) {
590 return unless $config{verbose};
591 return log_message(debug => @_);
595 sub log_message ($$) {
598 if ($config{syslog}) {
601 Sys::Syslog::setlogsock('unix');
602 Sys::Syslog::openlog('ikiwiki', '', 'user');
606 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
609 elsif (! $config{cgi}) {
613 return print STDERR "@_\n";
617 sub possibly_foolish_untaint ($) {
619 my ($untainted)=$tainted=~/(.*)/s;
639 return exists $pagesources{$page} &&
640 $pagesources{$page} =~ /\._([^.]+)$/;
646 if ($file =~ /\.([^.]+)$/) {
647 return $1 if exists $hooks{htmlize}{$1};
649 my $base=basename($file);
650 if (exists $hooks{htmlize}{$base} &&
651 $hooks{htmlize}{$base}{noextension}) {
660 my $type=pagetype($file);
662 $page=~s/\Q.$type\E*$//
663 if defined $type && !$hooks{htmlize}{$type}{keepextension}
664 && !$hooks{htmlize}{$type}{noextension};
665 if ($config{indexpages} && $page=~/(.*)\/index$/) {
671 sub newpagefile ($$) {
675 if (! $config{indexpages} || $page eq 'index') {
676 return $page.".".$type;
679 return $page."/index.".$type;
683 sub targetpage ($$;$) {
688 if (defined $filename) {
689 return $page."/".$filename.".".$ext;
691 elsif (! $config{usedirs} || $page eq 'index') {
692 return $page.".".$ext;
695 return $page."/index.".$ext;
702 return targetpage($page, $config{htmlext});
709 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
710 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
711 return "$dir/$file", stat(_) if -e "$dir/$file";
713 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
718 return (srcfile_stat(@_))[0];
721 sub add_underlay ($) {
725 $dir="$config{underlaydirbase}/$dir";
728 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
729 unshift @{$config{underlaydirs}}, $dir;
735 sub readfile ($;$$) {
741 error("cannot read a symlink ($file)");
745 open (my $in, "<", $file) || error("failed to read $file: $!");
746 binmode($in) if ($binary);
747 return \*$in if $wantfd;
749 # check for invalid utf-8, and toss it back to avoid crashes
750 if (! utf8::valid($ret)) {
751 $ret=encode_utf8($ret);
753 close $in || error("failed to read $file: $!");
757 sub prep_writefile ($$) {
762 while (length $test) {
763 if (-l "$destdir/$test") {
764 error("cannot write to a symlink ($test)");
766 $test=dirname($test);
769 my $dir=dirname("$destdir/$file");
772 foreach my $s (split(m!/+!, $dir)) {
775 mkdir($d) || error("failed to create directory $d: $!");
783 sub writefile ($$$;$$) {
784 my $file=shift; # can include subdirs
785 my $destdir=shift; # directory to put file in
790 prep_writefile($file, $destdir);
792 my $newfile="$destdir/$file.ikiwiki-new";
794 error("cannot write to a symlink ($newfile)");
797 my $cleanup = sub { unlink($newfile) };
798 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
799 binmode($out) if ($binary);
801 $writer->(\*$out, $cleanup);
804 print $out $content or error("failed writing to $newfile: $!", $cleanup);
806 close $out || error("failed saving $newfile: $!", $cleanup);
807 rename($newfile, "$destdir/$file") ||
808 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
814 sub will_render ($$;$) {
819 # Important security check.
820 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
821 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
822 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
825 if (! $clear || $cleared{$page}) {
826 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
829 foreach my $old (@{$renderedfiles{$page}}) {
830 delete $destsources{$old};
832 $renderedfiles{$page}=[$dest];
835 $destsources{$dest}=$page;
845 if ($link=~s/^\/+//) {
853 $l.="/" if length $l;
856 if (exists $links{$l}) {
859 elsif (exists $pagecase{lc $l}) {
860 return $pagecase{lc $l};
862 } while $cwd=~s{/?[^/]+$}{};
864 if (length $config{userdir}) {
865 my $l = "$config{userdir}/".lc($link);
866 if (exists $links{$l}) {
869 elsif (exists $pagecase{lc $l}) {
870 return $pagecase{lc $l};
874 #print STDERR "warning: page $page, broken link: $link\n";
878 sub isinlinableimage ($) {
881 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
884 sub pagetitle ($;$) {
889 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
892 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
900 # support use w/o %config set
901 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
902 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
908 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
909 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
916 return $config{cgiurl}."?".
917 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
923 return "$config{url}/" if ! defined $page;
925 $page=htmlpage($page);
927 $page=~s/[^\/]+\//..\//g;
932 # Work around very innefficient behavior in File::Spec if abs2rel
933 # is passed two relative paths. It's much faster if paths are
934 # absolute! (Debian bug #376658; fixed in debian unstable now)
939 my $ret=File::Spec->abs2rel($path, $base);
940 $ret=~s/^// if defined $ret;
944 sub displaytime ($;$) {
945 # Plugins can override this function to mark up the time to
947 return '<span class="date">'.formattime(@_).'</span>';
950 sub formattime ($;$) {
951 # Plugins can override this function to format the time.
954 if (! defined $format) {
955 $format=$config{timeformat};
958 # strftime doesn't know about encodings, so make sure
959 # its output is properly treated as utf8
960 return decode_utf8(POSIX::strftime($format, localtime($time)));
963 sub beautify_urlpath ($) {
966 # Ensure url is not an empty link, and if necessary,
967 # add ./ to avoid colon confusion.
968 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
972 if ($config{usedirs}) {
973 $url =~ s!/index.$config{htmlext}$!/!;
985 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
988 if (! $destsources{$to}) {
993 return $config{url}.beautify_urlpath("/".$to);
996 my $link = abs2rel($to, dirname(htmlpage($from)));
998 return beautify_urlpath($link);
1001 sub htmllink ($$$;@) {
1002 my $lpage=shift; # the page doing the linking
1003 my $page=shift; # the page that will contain the link (different for inline)
1010 if (! $opts{forcesubpage}) {
1011 $bestlink=bestlink($lpage, $link);
1014 $bestlink="$lpage/".lc($link);
1018 if (defined $opts{linktext}) {
1019 $linktext=$opts{linktext};
1022 $linktext=pagetitle(basename($link));
1025 return "<span class=\"selflink\">$linktext</span>"
1026 if length $bestlink && $page eq $bestlink &&
1027 ! defined $opts{anchor};
1029 if (! $destsources{$bestlink}) {
1030 $bestlink=htmlpage($bestlink);
1032 if (! $destsources{$bestlink}) {
1033 return $linktext unless length $config{cgiurl};
1034 return "<span class=\"createlink\"><a href=\"".
1040 "\" rel=\"nofollow\">?</a>$linktext</span>"
1044 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1045 $bestlink=beautify_urlpath($bestlink);
1047 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1048 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1051 if (defined $opts{anchor}) {
1052 $bestlink.="#".$opts{anchor};
1056 if (defined $opts{rel}) {
1057 push @attrs, ' rel="'.$opts{rel}.'"';
1059 if (defined $opts{class}) {
1060 push @attrs, ' class="'.$opts{class}.'"';
1063 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1066 sub openiduser ($) {
1069 if ($user =~ m!^https?://! &&
1070 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1073 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1074 # this works in at least 2.x
1075 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1078 # this only works in 1.x
1079 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1080 $display=$oid->display;
1083 # Convert "user.somehost.com" to "user [somehost.com]"
1084 # (also "user.somehost.co.uk")
1085 if ($display !~ /\[/) {
1086 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1088 # Convert "http://somehost.com/user" to "user [somehost.com]".
1089 # (also "https://somehost.com/user/")
1090 if ($display !~ /\[/) {
1091 $display=~s/^https?:\/\/(.+)\/([^\/]+)\/?$/$2 [$1]/;
1093 $display=~s!^https?://!!; # make sure this is removed
1094 eval q{use CGI 'escapeHTML'};
1096 return escapeHTML($display);
1104 my $oiduser=eval { openiduser($user) };
1105 if (defined $oiduser) {
1106 return "<a href=\"$user\">$oiduser</a>";
1109 eval q{use CGI 'escapeHTML'};
1112 return htmllink("", "", escapeHTML(
1113 length $config{userdir} ? $config{userdir}."/".$user : $user
1114 ), noimageinline => 1);
1118 sub htmlize ($$$$) {
1124 my $oneline = $content !~ /\n/;
1126 if (exists $hooks{htmlize}{$type}) {
1127 $content=$hooks{htmlize}{$type}{call}->(
1129 content => $content,
1133 error("htmlization of $type not supported");
1136 run_hooks(sanitize => sub {
1139 destpage => $destpage,
1140 content => $content,
1145 # hack to get rid of enclosing junk added by markdown
1146 # and other htmlizers
1147 $content=~s/^<p>//i;
1148 $content=~s/<\/p>$//i;
1160 run_hooks(linkify => sub {
1163 destpage => $destpage,
1164 content => $content,
1172 our $preprocess_preview=0;
1173 sub preprocess ($$$;$$) {
1174 my $page=shift; # the page the data comes from
1175 my $destpage=shift; # the page the data will appear in (different for inline)
1180 # Using local because it needs to be set within any nested calls
1182 local $preprocess_preview=$preview if defined $preview;
1189 $params="" if ! defined $params;
1191 if (length $escape) {
1192 return "[[$prefix$command $params]]";
1194 elsif (exists $hooks{preprocess}{$command}) {
1195 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1196 # Note: preserve order of params, some plugins may
1197 # consider it significant.
1199 while ($params =~ m{
1200 (?:([-\w]+)=)? # 1: named parameter key?
1202 """(.*?)""" # 2: triple-quoted value
1204 "([^"]+)" # 3: single-quoted value
1206 (\S+) # 4: unquoted value
1208 (?:\s+|$) # delimiter to next param
1218 elsif (defined $3) {
1221 elsif (defined $4) {
1226 push @params, $key, $val;
1229 push @params, $val, '';
1232 if ($preprocessing{$page}++ > 3) {
1233 # Avoid loops of preprocessed pages preprocessing
1234 # other pages that preprocess them, etc.
1235 return "[[!$command <span class=\"error\">".
1236 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1237 $page, $preprocessing{$page}).
1243 $hooks{preprocess}{$command}{call}->(
1246 destpage => $destpage,
1247 preview => $preprocess_preview,
1252 $ret="[[!$command <span class=\"error\">".
1253 gettext("Error").": $@"."</span>]]";
1257 # use void context during scan pass
1259 $hooks{preprocess}{$command}{call}->(
1262 destpage => $destpage,
1263 preview => $preprocess_preview,
1268 $preprocessing{$page}--;
1272 return "[[$prefix$command $params]]";
1277 if ($config{prefix_directives}) {
1280 \[\[(!) # directive open; 2: prefix
1281 ([-\w]+) # 3: command
1282 ( # 4: the parameters..
1283 \s+ # Must have space if parameters present
1285 (?:[-\w]+=)? # named parameter key?
1287 """.*?""" # triple-quoted value
1289 "[^"]+" # single-quoted value
1291 [^"\s\]]+ # unquoted value
1293 \s* # whitespace or end
1296 *)? # 0 or more parameters
1297 \]\] # directive closed
1303 \[\[(!?) # directive open; 2: optional prefix
1304 ([-\w]+) # 3: command
1306 ( # 4: the parameters..
1308 (?:[-\w]+=)? # named parameter key?
1310 """.*?""" # triple-quoted value
1312 "[^"]+" # single-quoted value
1314 [^"\s\]]+ # unquoted value
1316 \s* # whitespace or end
1319 *) # 0 or more parameters
1320 \]\] # directive closed
1324 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1333 run_hooks(filter => sub {
1334 $content=shift->(page => $page, destpage => $destpage,
1335 content => $content);
1342 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1345 sub check_canedit ($$$;$) {
1352 run_hooks(canedit => sub {
1353 return if defined $canedit;
1354 my $ret=shift->($page, $q, $session);
1359 elsif (ref $ret eq 'CODE') {
1360 $ret->() unless $nonfatal;
1363 elsif (defined $ret) {
1364 error($ret) unless $nonfatal;
1369 return defined $canedit ? $canedit : 1;
1372 sub check_content (@) {
1375 return 1 if ! exists $hooks{checkcontent}; # optimisation
1377 if (exists $pagesources{$params{page}}) {
1379 my %old=map { $_ => 1 }
1380 split("\n", readfile(srcfile($pagesources{$params{page}})));
1381 foreach my $line (split("\n", $params{content})) {
1382 push @diff, $line if ! exists $old{$_};
1384 $params{content}=join("\n", @diff);
1388 run_hooks(checkcontent => sub {
1389 return if defined $ok;
1390 my $ret=shift->(%params);
1395 elsif (ref $ret eq 'CODE') {
1396 $ret->() unless $params{nonfatal};
1399 elsif (defined $ret) {
1400 error($ret) unless $params{nonfatal};
1406 return defined $ok ? $ok : 1;
1412 # Take an exclusive lock on the wiki to prevent multiple concurrent
1413 # run issues. The lock will be dropped on program exit.
1414 if (! -d $config{wikistatedir}) {
1415 mkdir($config{wikistatedir});
1417 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1418 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1419 if (! flock($wikilock, 2)) { # LOCK_EX
1420 error("failed to get lock");
1426 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1427 return close($wikilock) if $wikilock;
1433 sub commit_hook_enabled () {
1434 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1435 error("cannot write to $config{wikistatedir}/commitlock: $!");
1436 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1437 close($commitlock) || error("failed closing commitlock: $!");
1440 close($commitlock) || error("failed closing commitlock: $!");
1444 sub disable_commit_hook () {
1445 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1446 error("cannot write to $config{wikistatedir}/commitlock: $!");
1447 if (! flock($commitlock, 2)) { # LOCK_EX
1448 error("failed to get commit lock");
1453 sub enable_commit_hook () {
1454 return close($commitlock) if $commitlock;
1459 %oldrenderedfiles=%pagectime=();
1460 if (! $config{rebuild}) {
1461 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1462 %destsources=%renderedfiles=%pagecase=%pagestate=();
1465 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1466 if (-e "$config{wikistatedir}/index") {
1467 system("ikiwiki-transition", "indexdb", $config{srcdir});
1468 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1475 my $index=Storable::fd_retrieve($in);
1476 if (! defined $index) {
1481 if (exists $index->{version} && ! ref $index->{version}) {
1482 $pages=$index->{page};
1483 %wikistate=%{$index->{state}};
1490 foreach my $src (keys %$pages) {
1491 my $d=$pages->{$src};
1492 my $page=pagename($src);
1493 $pagectime{$page}=$d->{ctime};
1494 if (! $config{rebuild}) {
1495 $pagesources{$page}=$src;
1496 $pagemtime{$page}=$d->{mtime};
1497 $renderedfiles{$page}=$d->{dest};
1498 if (exists $d->{links} && ref $d->{links}) {
1499 $links{$page}=$d->{links};
1500 $oldlinks{$page}=[@{$d->{links}}];
1502 if (exists $d->{depends}) {
1503 $depends{$page}=$d->{depends};
1505 if (exists $d->{state}) {
1506 $pagestate{$page}=$d->{state};
1509 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1511 foreach my $page (keys %pagesources) {
1512 $pagecase{lc $page}=$page;
1514 foreach my $page (keys %renderedfiles) {
1515 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1521 run_hooks(savestate => sub { shift->() });
1524 foreach my $type (keys %hooks) {
1525 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1527 my @hookids=keys %hookids;
1529 if (! -d $config{wikistatedir}) {
1530 mkdir($config{wikistatedir});
1532 my $newfile="$config{wikistatedir}/indexdb.new";
1533 my $cleanup = sub { unlink($newfile) };
1534 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1537 foreach my $page (keys %pagemtime) {
1538 next unless $pagemtime{$page};
1539 my $src=$pagesources{$page};
1541 $index{page}{$src}={
1542 ctime => $pagectime{$page},
1543 mtime => $pagemtime{$page},
1544 dest => $renderedfiles{$page},
1545 links => $links{$page},
1548 if (exists $depends{$page}) {
1549 $index{page}{$src}{depends} = $depends{$page};
1552 if (exists $pagestate{$page}) {
1553 foreach my $id (@hookids) {
1554 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1555 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1562 foreach my $id (@hookids) {
1563 foreach my $key (keys %{$wikistate{$id}}) {
1564 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1568 $index{version}="3";
1569 my $ret=Storable::nstore_fd(\%index, $out);
1570 return if ! defined $ret || ! $ret;
1571 close $out || error("failed saving to $newfile: $!", $cleanup);
1572 rename($newfile, "$config{wikistatedir}/indexdb") ||
1573 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1578 sub template_file ($) {
1581 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1582 return "$dir/$template" if -e "$dir/$template";
1587 sub template_params (@) {
1588 my $filename=template_file(shift);
1590 if (! defined $filename) {
1591 return if wantarray;
1597 my $text_ref = shift;
1598 ${$text_ref} = decode_utf8(${$text_ref});
1600 filename => $filename,
1601 loop_context_vars => 1,
1602 die_on_bad_params => 0,
1605 return wantarray ? @ret : {@ret};
1608 sub template ($;@) {
1609 require HTML::Template;
1610 return HTML::Template->new(template_params(@_));
1613 sub misctemplate ($$;@) {
1617 my $template=template("misc.tmpl");
1620 indexlink => indexlink(),
1621 wikiname => $config{wikiname},
1622 pagebody => $pagebody,
1623 baseurl => baseurl(),
1626 run_hooks(pagetemplate => sub {
1627 shift->(page => "", destpage => "", template => $template);
1629 return $template->output;
1635 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1636 error 'hook requires type, call, and id parameters';
1639 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1641 $hooks{$param{type}}{$param{id}}=\%param;
1645 sub run_hooks ($$) {
1646 # Calls the given sub for each hook of the given type,
1647 # passing it the hook function to call.
1651 if (exists $hooks{$type}) {
1652 my (@first, @middle, @last);
1653 foreach my $id (keys %{$hooks{$type}}) {
1654 if ($hooks{$type}{$id}{first}) {
1657 elsif ($hooks{$type}{$id}{last}) {
1664 foreach my $id (@first, @middle, @last) {
1665 $sub->($hooks{$type}{$id}{call});
1673 $hooks{rcs}{rcs_update}{call}->(@_);
1676 sub rcs_prepedit ($) {
1677 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1680 sub rcs_commit ($$$;$$) {
1681 $hooks{rcs}{rcs_commit}{call}->(@_);
1684 sub rcs_commit_staged ($$$) {
1685 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1689 $hooks{rcs}{rcs_add}{call}->(@_);
1692 sub rcs_remove ($) {
1693 $hooks{rcs}{rcs_remove}{call}->(@_);
1696 sub rcs_rename ($$) {
1697 $hooks{rcs}{rcs_rename}{call}->(@_);
1700 sub rcs_recentchanges ($) {
1701 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1705 $hooks{rcs}{rcs_diff}{call}->(@_);
1708 sub rcs_getctime ($) {
1709 $hooks{rcs}{rcs_getctime}{call}->(@_);
1712 sub rcs_receive () {
1713 $hooks{rcs}{rcs_receive}{call}->();
1716 sub add_depends ($$) {
1720 return unless pagespec_valid($pagespec);
1722 if (! exists $depends{$page}) {
1723 $depends{$page}=$pagespec;
1726 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1732 sub file_pruned ($$) {
1734 my $file=File::Spec->canonpath(shift);
1735 my $base=File::Spec->canonpath(shift);
1736 $file =~ s#^\Q$base\E/+##;
1738 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1739 return $file =~ m/$regexp/ && $file ne $base;
1742 sub define_gettext () {
1743 # If translation is needed, redefine the gettext function to do it.
1744 # Otherwise, it becomes a quick no-op.
1745 no warnings 'redefine';
1746 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1747 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1748 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1750 my $gettext_obj=eval q{
1751 use Locale::gettext q{textdomain};
1752 Locale::gettext->domain('ikiwiki')
1756 $gettext_obj->get(shift);
1764 *gettext=sub { return shift };
1776 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1780 # Injects a new function into the symbol table to replace an
1781 # exported function.
1784 # This is deep ugly perl foo, beware.
1787 if (! defined $params{parent}) {
1788 $params{parent}='::';
1789 $params{old}=\&{$params{name}};
1790 $params{name}=~s/.*:://;
1792 my $parent=$params{parent};
1793 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1794 $ns = $params{parent} . $ns;
1795 inject(%params, parent => $ns) unless $ns eq '::main::';
1796 *{$ns . $params{name}} = $params{call}
1797 if exists ${$ns}{$params{name}} &&
1798 \&{${$ns}{$params{name}}} == $params{old};
1808 push @{$links{$page}}, $link
1809 unless grep { $_ eq $link } @{$links{$page}};
1812 sub pagespec_merge ($$) {
1816 return $a if $a eq $b;
1817 return "($a) or ($b)";
1820 sub pagespec_translate ($) {
1823 # Convert spec to perl code.
1827 \s* # ignore whitespace
1828 ( # 1: match a single word
1835 \w+\([^\)]*\) # command(params)
1837 [^\s()]+ # any other text
1839 \s* # ignore whitespace
1842 if (lc $word eq 'and') {
1845 elsif (lc $word eq 'or') {
1848 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1851 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1852 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1854 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
1857 push @data, qq{unknown function in pagespec "$word"};
1858 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
1863 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
1867 if (! length $code) {
1868 $code="IkiWiki::FailReason->new('empty pagespec')";
1872 return eval 'sub { my $page=shift; '.$code.' }';
1875 sub pagespec_match ($$;@) {
1880 # Backwards compatability with old calling convention.
1882 unshift @params, 'location';
1885 my $sub=pagespec_translate($spec);
1886 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
1887 if $@ || ! defined $sub;
1888 return $sub->($page, @params);
1891 sub pagespec_match_list ($$;@) {
1896 my $sub=pagespec_translate($spec);
1897 error "syntax error in pagespec \"$spec\""
1898 if $@ || ! defined $sub;
1902 foreach my $page (@$pages) {
1903 $r=$sub->($page, @params);
1904 push @ret, $page if $r;
1907 if (! @ret && defined $r && $r->isa("IkiWiki::ErrorReason")) {
1908 error(sprintf(gettext("cannot match pages: %s"), $r));
1915 sub pagespec_valid ($) {
1918 my $sub=pagespec_translate($spec);
1923 my $re=quotemeta(shift);
1929 package IkiWiki::FailReason;
1932 '""' => sub { ${$_[0]} },
1934 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1941 return bless \$value, $class;
1944 package IkiWiki::ErrorReason;
1946 our @ISA = 'IkiWiki::FailReason';
1948 package IkiWiki::SuccessReason;
1951 '""' => sub { ${$_[0]} },
1953 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1960 return bless \$value, $class;
1963 package IkiWiki::PageSpec;
1969 if ($path =~ m!^\./!) {
1970 $from=~s#/?[^/]+$## if defined $from;
1972 $path="$from/$path" if length $from;
1978 sub match_glob ($$;@) {
1983 $glob=derel($glob, $params{location});
1985 my $regexp=IkiWiki::glob2re($glob);
1986 if ($page=~/^$regexp$/i) {
1987 if (! IkiWiki::isinternal($page) || $params{internal}) {
1988 return IkiWiki::SuccessReason->new("$glob matches $page");
1991 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1995 return IkiWiki::FailReason->new("$glob does not match $page");
1999 sub match_internal ($$;@) {
2000 return match_glob($_[0], $_[1], @_, internal => 1)
2003 sub match_link ($$;@) {
2008 $link=derel($link, $params{location});
2009 my $from=exists $params{location} ? $params{location} : '';
2011 my $links = $IkiWiki::links{$page};
2012 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
2013 my $bestlink = IkiWiki::bestlink($from, $link);
2014 foreach my $p (@{$links}) {
2015 if (length $bestlink) {
2016 return IkiWiki::SuccessReason->new("$page links to $link")
2017 if $bestlink eq IkiWiki::bestlink($page, $p);
2020 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
2021 if match_glob($p, $link, %params);
2024 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
2025 if match_glob($p, $link, %params);
2028 return IkiWiki::FailReason->new("$page does not link to $link");
2031 sub match_backlink ($$;@) {
2032 return match_link($_[1], $_[0], @_);
2035 sub match_created_before ($$;@) {
2040 $testpage=derel($testpage, $params{location});
2042 if (exists $IkiWiki::pagectime{$testpage}) {
2043 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2044 return IkiWiki::SuccessReason->new("$page created before $testpage");
2047 return IkiWiki::FailReason->new("$page not created before $testpage");
2051 return IkiWiki::FailReason->new("$testpage has no ctime");
2055 sub match_created_after ($$;@) {
2060 $testpage=derel($testpage, $params{location});
2062 if (exists $IkiWiki::pagectime{$testpage}) {
2063 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2064 return IkiWiki::SuccessReason->new("$page created after $testpage");
2067 return IkiWiki::FailReason->new("$page not created after $testpage");
2071 return IkiWiki::FailReason->new("$testpage has no ctime");
2075 sub match_creation_day ($$;@) {
2076 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2077 return IkiWiki::SuccessReason->new('creation_day matched');
2080 return IkiWiki::FailReason->new('creation_day did not match');
2084 sub match_creation_month ($$;@) {
2085 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2086 return IkiWiki::SuccessReason->new('creation_month matched');
2089 return IkiWiki::FailReason->new('creation_month did not match');
2093 sub match_creation_year ($$;@) {
2094 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2095 return IkiWiki::SuccessReason->new('creation_year matched');
2098 return IkiWiki::FailReason->new('creation_year did not match');
2102 sub match_user ($$;@) {
2107 if (! exists $params{user}) {
2108 return IkiWiki::ErrorReason->new("no user specified");
2111 if (defined $params{user} && lc $params{user} eq lc $user) {
2112 return IkiWiki::SuccessReason->new("user is $user");
2114 elsif (! defined $params{user}) {
2115 return IkiWiki::FailReason->new("not logged in");
2118 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2122 sub match_admin ($$;@) {
2127 if (! exists $params{user}) {
2128 return IkiWiki::ErrorReason->new("no user specified");
2131 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2132 return IkiWiki::SuccessReason->new("user is an admin");
2134 elsif (! defined $params{user}) {
2135 return IkiWiki::FailReason->new("not logged in");
2138 return IkiWiki::FailReason->new("user is not an admin");
2142 sub match_ip ($$;@) {
2147 if (! exists $params{ip}) {
2148 return IkiWiki::ErrorReason->new("no IP specified");
2151 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2152 return IkiWiki::SuccessReason->new("IP is $ip");
2155 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");