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?",
225 default => gettext("Discussion"),
226 description => "name of Discussion pages",
233 description => "only send cookies over SSL connections?",
241 description => "extension to use for new pages",
242 safe => 0, # not sanitized
248 description => "extension to use for html files",
249 safe => 0, # not sanitized
255 description => "strftime format string to display date",
263 example => "en_US.UTF-8",
264 description => "UTF-8 locale to use",
273 description => "put user pages below specified page",
280 description => "how many backlinks to show before hiding excess (0 to show all)",
287 description => "attempt to hardlink source files? (optimisation for large files)",
289 safe => 0, # paranoia
295 description => "force ikiwiki to use a particular umask",
297 safe => 0, # paranoia
302 example => "ikiwiki",
303 description => "group for wrappers to run in",
305 safe => 0, # paranoia
311 example => "$ENV{HOME}/.ikiwiki/",
312 description => "extra library and plugin directory",
314 safe => 0, # directory
320 description => "environment variables",
321 safe => 0, # paranoia
328 description => "regexp of source files to ignore",
333 wiki_file_prune_regexps => {
335 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
336 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
337 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
338 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
340 description => "regexps of source files to ignore",
346 description => "specifies the characters that are allowed in source filenames",
347 default => "-[:alnum:]+/.:_",
351 wiki_file_regexp => {
353 description => "regexp of legal source files",
357 web_commit_regexp => {
359 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
360 description => "regexp to parse web commits from logs",
367 description => "run as a cgi",
371 cgi_disable_uploads => {
374 description => "whether CGI should accept file uploads",
381 description => "run as a post-commit hook",
388 description => "running in rebuild mode",
395 description => "running in setup mode",
402 description => "running in refresh mode",
409 description => "running in receive test mode",
416 description => "running in getctime mode",
423 description => "running in w3mmode",
430 description => "path to the .ikiwiki directory holding ikiwiki state",
437 description => "path to setup file",
441 allow_symlinks_before_srcdir => {
444 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
450 sub defaultconfig () {
453 foreach my $key (keys %s) {
454 push @ret, $key, $s{$key}->{default};
461 # locale stuff; avoid LC_ALL since it overrides everything
462 if (defined $ENV{LC_ALL}) {
463 $ENV{LANG} = $ENV{LC_ALL};
466 if (defined $config{locale}) {
467 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
468 $ENV{LANG}=$config{locale};
473 if (! defined $config{wiki_file_regexp}) {
474 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
477 if (ref $config{ENV} eq 'HASH') {
478 foreach my $val (keys %{$config{ENV}}) {
479 $ENV{$val}=$config{ENV}{$val};
483 if ($config{w3mmode}) {
484 eval q{use Cwd q{abs_path}};
486 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
487 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
488 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
489 unless $config{cgiurl} =~ m!file:///!;
490 $config{url}="file://".$config{destdir};
493 if ($config{cgi} && ! length $config{url}) {
494 error(gettext("Must specify url to wiki with --url when using --cgi"));
497 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
498 unless exists $config{wikistatedir} && defined $config{wikistatedir};
500 if (defined $config{umask}) {
501 umask(possibly_foolish_untaint($config{umask}));
504 run_hooks(checkconfig => sub { shift->() });
512 foreach my $dir (@INC, $config{libdir}) {
513 next unless defined $dir && length $dir;
514 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
515 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
519 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
520 next unless defined $dir && length $dir;
521 foreach my $file (glob("$dir/plugins/*")) {
522 $ret{basename($file)}=1 if -x $file;
530 if (defined $config{libdir} && length $config{libdir}) {
531 unshift @INC, possibly_foolish_untaint($config{libdir});
534 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
539 if (exists $IkiWiki::hooks{rcs}) {
540 error(gettext("cannot use multiple rcs plugins"));
542 loadplugin($config{rcs});
544 if (! exists $IkiWiki::hooks{rcs}) {
548 run_hooks(getopt => sub { shift->() });
549 if (grep /^-/, @ARGV) {
550 print STDERR "Unknown option (or missing parameter): $_\n"
551 foreach grep /^-/, @ARGV;
561 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
563 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
564 "$installdir/lib/ikiwiki") {
565 if (defined $dir && -x "$dir/plugins/$plugin") {
566 eval { require IkiWiki::Plugin::external };
569 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
571 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
572 $loaded_plugins{$plugin}=1;
577 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
580 error("Failed to load plugin $mod: $@");
582 $loaded_plugins{$plugin}=1;
589 log_message('err' => $message) if $config{syslog};
590 if (defined $cleaner) {
597 return unless $config{verbose};
598 return log_message(debug => @_);
602 sub log_message ($$) {
605 if ($config{syslog}) {
608 Sys::Syslog::setlogsock('unix');
609 Sys::Syslog::openlog('ikiwiki', '', 'user');
613 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
616 elsif (! $config{cgi}) {
620 return print STDERR "@_\n";
624 sub possibly_foolish_untaint ($) {
626 my ($untainted)=$tainted=~/(.*)/s;
646 return exists $pagesources{$page} &&
647 $pagesources{$page} =~ /\._([^.]+)$/;
653 if ($file =~ /\.([^.]+)$/) {
654 return $1 if exists $hooks{htmlize}{$1};
656 my $base=basename($file);
657 if (exists $hooks{htmlize}{$base} &&
658 $hooks{htmlize}{$base}{noextension}) {
669 if (exists $pagename_cache{$file}) {
670 return $pagename_cache{$file};
673 my $type=pagetype($file);
675 $page=~s/\Q.$type\E*$//
676 if defined $type && !$hooks{htmlize}{$type}{keepextension}
677 && !$hooks{htmlize}{$type}{noextension};
678 if ($config{indexpages} && $page=~/(.*)\/index$/) {
682 $pagename_cache{$file} = $page;
686 sub newpagefile ($$) {
690 if (! $config{indexpages} || $page eq 'index') {
691 return $page.".".$type;
694 return $page."/index.".$type;
698 sub targetpage ($$;$) {
703 if (defined $filename) {
704 return $page."/".$filename.".".$ext;
706 elsif (! $config{usedirs} || $page eq 'index') {
707 return $page.".".$ext;
710 return $page."/index.".$ext;
717 return targetpage($page, $config{htmlext});
724 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
725 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
726 return "$dir/$file", stat(_) if -e "$dir/$file";
728 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
733 return (srcfile_stat(@_))[0];
736 sub add_underlay ($) {
740 $dir="$config{underlaydirbase}/$dir";
743 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
744 unshift @{$config{underlaydirs}}, $dir;
750 sub readfile ($;$$) {
756 error("cannot read a symlink ($file)");
760 open (my $in, "<", $file) || error("failed to read $file: $!");
761 binmode($in) if ($binary);
762 return \*$in if $wantfd;
764 # check for invalid utf-8, and toss it back to avoid crashes
765 if (! utf8::valid($ret)) {
766 $ret=encode_utf8($ret);
768 close $in || error("failed to read $file: $!");
772 sub prep_writefile ($$) {
777 while (length $test) {
778 if (-l "$destdir/$test") {
779 error("cannot write to a symlink ($test)");
781 $test=dirname($test);
784 my $dir=dirname("$destdir/$file");
787 foreach my $s (split(m!/+!, $dir)) {
790 mkdir($d) || error("failed to create directory $d: $!");
798 sub writefile ($$$;$$) {
799 my $file=shift; # can include subdirs
800 my $destdir=shift; # directory to put file in
805 prep_writefile($file, $destdir);
807 my $newfile="$destdir/$file.ikiwiki-new";
809 error("cannot write to a symlink ($newfile)");
812 my $cleanup = sub { unlink($newfile) };
813 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
814 binmode($out) if ($binary);
816 $writer->(\*$out, $cleanup);
819 print $out $content or error("failed writing to $newfile: $!", $cleanup);
821 close $out || error("failed saving $newfile: $!", $cleanup);
822 rename($newfile, "$destdir/$file") ||
823 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
829 sub will_render ($$;$) {
834 # Important security check.
835 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
836 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
837 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
840 if (! $clear || $cleared{$page}) {
841 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
844 foreach my $old (@{$renderedfiles{$page}}) {
845 delete $destsources{$old};
847 $renderedfiles{$page}=[$dest];
850 $destsources{$dest}=$page;
860 if ($link=~s/^\/+//) {
868 $l.="/" if length $l;
871 if (exists $links{$l}) {
874 elsif (exists $pagecase{lc $l}) {
875 return $pagecase{lc $l};
877 } while $cwd=~s{/?[^/]+$}{};
879 if (length $config{userdir}) {
880 my $l = "$config{userdir}/".lc($link);
881 if (exists $links{$l}) {
884 elsif (exists $pagecase{lc $l}) {
885 return $pagecase{lc $l};
889 #print STDERR "warning: page $page, broken link: $link\n";
893 sub isinlinableimage ($) {
896 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
899 sub pagetitle ($;$) {
904 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
907 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
915 # support use w/o %config set
916 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
917 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
923 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
924 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
931 return $config{cgiurl}."?".
932 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
938 return "$config{url}/" if ! defined $page;
940 $page=htmlpage($page);
942 $page=~s/[^\/]+\//..\//g;
947 # Work around very innefficient behavior in File::Spec if abs2rel
948 # is passed two relative paths. It's much faster if paths are
949 # absolute! (Debian bug #376658; fixed in debian unstable now)
954 my $ret=File::Spec->abs2rel($path, $base);
955 $ret=~s/^// if defined $ret;
959 sub displaytime ($;$) {
960 # Plugins can override this function to mark up the time to
962 return '<span class="date">'.formattime(@_).'</span>';
965 sub formattime ($;$) {
966 # Plugins can override this function to format the time.
969 if (! defined $format) {
970 $format=$config{timeformat};
973 # strftime doesn't know about encodings, so make sure
974 # its output is properly treated as utf8
975 return decode_utf8(POSIX::strftime($format, localtime($time)));
978 sub beautify_urlpath ($) {
981 # Ensure url is not an empty link, and if necessary,
982 # add ./ to avoid colon confusion.
983 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
987 if ($config{usedirs}) {
988 $url =~ s!/index.$config{htmlext}$!/!;
1000 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1003 if (! $destsources{$to}) {
1008 return $config{url}.beautify_urlpath("/".$to);
1011 my $link = abs2rel($to, dirname(htmlpage($from)));
1013 return beautify_urlpath($link);
1016 sub htmllink ($$$;@) {
1017 my $lpage=shift; # the page doing the linking
1018 my $page=shift; # the page that will contain the link (different for inline)
1025 if (! $opts{forcesubpage}) {
1026 $bestlink=bestlink($lpage, $link);
1029 $bestlink="$lpage/".lc($link);
1033 if (defined $opts{linktext}) {
1034 $linktext=$opts{linktext};
1037 $linktext=pagetitle(basename($link));
1040 return "<span class=\"selflink\">$linktext</span>"
1041 if length $bestlink && $page eq $bestlink &&
1042 ! defined $opts{anchor};
1044 if (! $destsources{$bestlink}) {
1045 $bestlink=htmlpage($bestlink);
1047 if (! $destsources{$bestlink}) {
1048 return $linktext unless length $config{cgiurl};
1049 return "<span class=\"createlink\"><a href=\"".
1055 "\" rel=\"nofollow\">?</a>$linktext</span>"
1059 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1060 $bestlink=beautify_urlpath($bestlink);
1062 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1063 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1066 if (defined $opts{anchor}) {
1067 $bestlink.="#".$opts{anchor};
1071 if (defined $opts{rel}) {
1072 push @attrs, ' rel="'.$opts{rel}.'"';
1074 if (defined $opts{class}) {
1075 push @attrs, ' class="'.$opts{class}.'"';
1078 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1081 sub openiduser ($) {
1084 if ($user =~ m!^https?://! &&
1085 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1088 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1089 # this works in at least 2.x
1090 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1093 # this only works in 1.x
1094 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1095 $display=$oid->display;
1098 # Convert "user.somehost.com" to "user [somehost.com]"
1099 # (also "user.somehost.co.uk")
1100 if ($display !~ /\[/) {
1101 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1103 # Convert "http://somehost.com/user" to "user [somehost.com]".
1104 # (also "https://somehost.com/user/")
1105 if ($display !~ /\[/) {
1106 $display=~s/^https?:\/\/(.+)\/([^\/]+)\/?$/$2 [$1]/;
1108 $display=~s!^https?://!!; # make sure this is removed
1109 eval q{use CGI 'escapeHTML'};
1111 return escapeHTML($display);
1119 my $oiduser=eval { openiduser($user) };
1120 if (defined $oiduser) {
1121 return "<a href=\"$user\">$oiduser</a>";
1124 eval q{use CGI 'escapeHTML'};
1127 return htmllink("", "", escapeHTML(
1128 length $config{userdir} ? $config{userdir}."/".$user : $user
1129 ), noimageinline => 1);
1133 sub htmlize ($$$$) {
1139 my $oneline = $content !~ /\n/;
1141 if (exists $hooks{htmlize}{$type}) {
1142 $content=$hooks{htmlize}{$type}{call}->(
1144 content => $content,
1148 error("htmlization of $type not supported");
1151 run_hooks(sanitize => sub {
1154 destpage => $destpage,
1155 content => $content,
1160 # hack to get rid of enclosing junk added by markdown
1161 # and other htmlizers
1162 $content=~s/^<p>//i;
1163 $content=~s/<\/p>$//i;
1175 run_hooks(linkify => sub {
1178 destpage => $destpage,
1179 content => $content,
1187 our $preprocess_preview=0;
1188 sub preprocess ($$$;$$) {
1189 my $page=shift; # the page the data comes from
1190 my $destpage=shift; # the page the data will appear in (different for inline)
1195 # Using local because it needs to be set within any nested calls
1197 local $preprocess_preview=$preview if defined $preview;
1204 $params="" if ! defined $params;
1206 if (length $escape) {
1207 return "[[$prefix$command $params]]";
1209 elsif (exists $hooks{preprocess}{$command}) {
1210 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1211 # Note: preserve order of params, some plugins may
1212 # consider it significant.
1214 while ($params =~ m{
1215 (?:([-\w]+)=)? # 1: named parameter key?
1217 """(.*?)""" # 2: triple-quoted value
1219 "([^"]+)" # 3: single-quoted value
1221 (\S+) # 4: unquoted value
1223 (?:\s+|$) # delimiter to next param
1233 elsif (defined $3) {
1236 elsif (defined $4) {
1241 push @params, $key, $val;
1244 push @params, $val, '';
1247 if ($preprocessing{$page}++ > 3) {
1248 # Avoid loops of preprocessed pages preprocessing
1249 # other pages that preprocess them, etc.
1250 return "[[!$command <span class=\"error\">".
1251 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1252 $page, $preprocessing{$page}).
1258 $hooks{preprocess}{$command}{call}->(
1261 destpage => $destpage,
1262 preview => $preprocess_preview,
1268 $ret="[[!$command <span class=\"error\">".
1269 gettext("Error").": $error"."</span>]]";
1273 # use void context during scan pass
1275 $hooks{preprocess}{$command}{call}->(
1278 destpage => $destpage,
1279 preview => $preprocess_preview,
1284 $preprocessing{$page}--;
1288 return "[[$prefix$command $params]]";
1293 if ($config{prefix_directives}) {
1296 \[\[(!) # directive open; 2: prefix
1297 ([-\w]+) # 3: command
1298 ( # 4: the parameters..
1299 \s+ # Must have space if parameters present
1301 (?:[-\w]+=)? # named parameter key?
1303 """.*?""" # triple-quoted value
1305 "[^"]+" # single-quoted value
1307 [^"\s\]]+ # unquoted value
1309 \s* # whitespace or end
1312 *)? # 0 or more parameters
1313 \]\] # directive closed
1319 \[\[(!?) # directive open; 2: optional prefix
1320 ([-\w]+) # 3: command
1322 ( # 4: the parameters..
1324 (?:[-\w]+=)? # named parameter key?
1326 """.*?""" # triple-quoted value
1328 "[^"]+" # single-quoted value
1330 [^"\s\]]+ # unquoted value
1332 \s* # whitespace or end
1335 *) # 0 or more parameters
1336 \]\] # directive closed
1340 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1349 run_hooks(filter => sub {
1350 $content=shift->(page => $page, destpage => $destpage,
1351 content => $content);
1358 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1361 sub check_canedit ($$$;$) {
1368 run_hooks(canedit => sub {
1369 return if defined $canedit;
1370 my $ret=shift->($page, $q, $session);
1375 elsif (ref $ret eq 'CODE') {
1376 $ret->() unless $nonfatal;
1379 elsif (defined $ret) {
1380 error($ret) unless $nonfatal;
1385 return defined $canedit ? $canedit : 1;
1388 sub check_content (@) {
1391 return 1 if ! exists $hooks{checkcontent}; # optimisation
1393 if (exists $pagesources{$params{page}}) {
1395 my %old=map { $_ => 1 }
1396 split("\n", readfile(srcfile($pagesources{$params{page}})));
1397 foreach my $line (split("\n", $params{content})) {
1398 push @diff, $line if ! exists $old{$_};
1400 $params{diff}=join("\n", @diff);
1404 run_hooks(checkcontent => sub {
1405 return if defined $ok;
1406 my $ret=shift->(%params);
1411 elsif (ref $ret eq 'CODE') {
1412 $ret->() unless $params{nonfatal};
1415 elsif (defined $ret) {
1416 error($ret) unless $params{nonfatal};
1422 return defined $ok ? $ok : 1;
1428 # Take an exclusive lock on the wiki to prevent multiple concurrent
1429 # run issues. The lock will be dropped on program exit.
1430 if (! -d $config{wikistatedir}) {
1431 mkdir($config{wikistatedir});
1433 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1434 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1435 if (! flock($wikilock, 2)) { # LOCK_EX
1436 error("failed to get lock");
1442 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1443 return close($wikilock) if $wikilock;
1449 sub commit_hook_enabled () {
1450 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1451 error("cannot write to $config{wikistatedir}/commitlock: $!");
1452 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1453 close($commitlock) || error("failed closing commitlock: $!");
1456 close($commitlock) || error("failed closing commitlock: $!");
1460 sub disable_commit_hook () {
1461 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1462 error("cannot write to $config{wikistatedir}/commitlock: $!");
1463 if (! flock($commitlock, 2)) { # LOCK_EX
1464 error("failed to get commit lock");
1469 sub enable_commit_hook () {
1470 return close($commitlock) if $commitlock;
1475 %oldrenderedfiles=%pagectime=();
1476 if (! $config{rebuild}) {
1477 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1478 %destsources=%renderedfiles=%pagecase=%pagestate=();
1481 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1482 if (-e "$config{wikistatedir}/index") {
1483 system("ikiwiki-transition", "indexdb", $config{srcdir});
1484 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1491 my $index=Storable::fd_retrieve($in);
1492 if (! defined $index) {
1497 if (exists $index->{version} && ! ref $index->{version}) {
1498 $pages=$index->{page};
1499 %wikistate=%{$index->{state}};
1506 foreach my $src (keys %$pages) {
1507 my $d=$pages->{$src};
1508 my $page=pagename($src);
1509 $pagectime{$page}=$d->{ctime};
1510 if (! $config{rebuild}) {
1511 $pagesources{$page}=$src;
1512 $pagemtime{$page}=$d->{mtime};
1513 $renderedfiles{$page}=$d->{dest};
1514 if (exists $d->{links} && ref $d->{links}) {
1515 $links{$page}=$d->{links};
1516 $oldlinks{$page}=[@{$d->{links}}];
1518 if (exists $d->{dependslist}) {
1520 map { $_ => 1 } @{$d->{dependslist}}
1523 elsif (exists $d->{depends}) {
1524 $depends{$page}={$d->{depends} => 1};
1526 if (exists $d->{state}) {
1527 $pagestate{$page}=$d->{state};
1530 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1532 foreach my $page (keys %pagesources) {
1533 $pagecase{lc $page}=$page;
1535 foreach my $page (keys %renderedfiles) {
1536 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1542 run_hooks(savestate => sub { shift->() });
1545 foreach my $type (keys %hooks) {
1546 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1548 my @hookids=keys %hookids;
1550 if (! -d $config{wikistatedir}) {
1551 mkdir($config{wikistatedir});
1553 my $newfile="$config{wikistatedir}/indexdb.new";
1554 my $cleanup = sub { unlink($newfile) };
1555 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1558 foreach my $page (keys %pagemtime) {
1559 next unless $pagemtime{$page};
1560 my $src=$pagesources{$page};
1562 $index{page}{$src}={
1563 ctime => $pagectime{$page},
1564 mtime => $pagemtime{$page},
1565 dest => $renderedfiles{$page},
1566 links => $links{$page},
1569 if (exists $depends{$page}) {
1570 $index{page}{$src}{dependslist} = [ keys %{$depends{$page}} ];
1573 if (exists $pagestate{$page}) {
1574 foreach my $id (@hookids) {
1575 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1576 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1583 foreach my $id (@hookids) {
1584 foreach my $key (keys %{$wikistate{$id}}) {
1585 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1589 $index{version}="3";
1590 my $ret=Storable::nstore_fd(\%index, $out);
1591 return if ! defined $ret || ! $ret;
1592 close $out || error("failed saving to $newfile: $!", $cleanup);
1593 rename($newfile, "$config{wikistatedir}/indexdb") ||
1594 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1599 sub template_file ($) {
1602 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1603 return "$dir/$template" if -e "$dir/$template";
1608 sub template_params (@) {
1609 my $filename=template_file(shift);
1611 if (! defined $filename) {
1612 return if wantarray;
1618 my $text_ref = shift;
1619 ${$text_ref} = decode_utf8(${$text_ref});
1621 filename => $filename,
1622 loop_context_vars => 1,
1623 die_on_bad_params => 0,
1626 return wantarray ? @ret : {@ret};
1629 sub template ($;@) {
1630 require HTML::Template;
1631 return HTML::Template->new(template_params(@_));
1634 sub misctemplate ($$;@) {
1638 my $template=template("misc.tmpl");
1641 indexlink => indexlink(),
1642 wikiname => $config{wikiname},
1643 pagebody => $pagebody,
1644 baseurl => baseurl(),
1647 run_hooks(pagetemplate => sub {
1648 shift->(page => "", destpage => "", template => $template);
1650 return $template->output;
1656 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1657 error 'hook requires type, call, and id parameters';
1660 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1662 $hooks{$param{type}}{$param{id}}=\%param;
1666 sub run_hooks ($$) {
1667 # Calls the given sub for each hook of the given type,
1668 # passing it the hook function to call.
1672 if (exists $hooks{$type}) {
1673 my (@first, @middle, @last);
1674 foreach my $id (keys %{$hooks{$type}}) {
1675 if ($hooks{$type}{$id}{first}) {
1678 elsif ($hooks{$type}{$id}{last}) {
1685 foreach my $id (@first, @middle, @last) {
1686 $sub->($hooks{$type}{$id}{call});
1694 $hooks{rcs}{rcs_update}{call}->(@_);
1697 sub rcs_prepedit ($) {
1698 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1701 sub rcs_commit ($$$;$$) {
1702 $hooks{rcs}{rcs_commit}{call}->(@_);
1705 sub rcs_commit_staged ($$$) {
1706 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1710 $hooks{rcs}{rcs_add}{call}->(@_);
1713 sub rcs_remove ($) {
1714 $hooks{rcs}{rcs_remove}{call}->(@_);
1717 sub rcs_rename ($$) {
1718 $hooks{rcs}{rcs_rename}{call}->(@_);
1721 sub rcs_recentchanges ($) {
1722 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1726 $hooks{rcs}{rcs_diff}{call}->(@_);
1729 sub rcs_getctime ($) {
1730 $hooks{rcs}{rcs_getctime}{call}->(@_);
1733 sub rcs_receive () {
1734 $hooks{rcs}{rcs_receive}{call}->();
1737 sub add_depends ($$) {
1741 return unless pagespec_valid($pagespec);
1743 $depends{$page}{$pagespec} = 1;
1747 sub file_pruned ($$) {
1749 my $file=File::Spec->canonpath(shift);
1750 my $base=File::Spec->canonpath(shift);
1751 $file =~ s#^\Q$base\E/+##;
1753 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1754 return $file =~ m/$regexp/ && $file ne $base;
1757 sub define_gettext () {
1758 # If translation is needed, redefine the gettext function to do it.
1759 # Otherwise, it becomes a quick no-op.
1760 no warnings 'redefine';
1761 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1762 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1763 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1765 my $gettext_obj=eval q{
1766 use Locale::gettext q{textdomain};
1767 Locale::gettext->domain('ikiwiki')
1771 $gettext_obj->get(shift);
1779 *gettext=sub { return shift };
1791 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1795 # Injects a new function into the symbol table to replace an
1796 # exported function.
1799 # This is deep ugly perl foo, beware.
1802 if (! defined $params{parent}) {
1803 $params{parent}='::';
1804 $params{old}=\&{$params{name}};
1805 $params{name}=~s/.*:://;
1807 my $parent=$params{parent};
1808 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1809 $ns = $params{parent} . $ns;
1810 inject(%params, parent => $ns) unless $ns eq '::main::';
1811 *{$ns . $params{name}} = $params{call}
1812 if exists ${$ns}{$params{name}} &&
1813 \&{${$ns}{$params{name}}} == $params{old};
1823 push @{$links{$page}}, $link
1824 unless grep { $_ eq $link } @{$links{$page}};
1827 sub pagespec_translate ($) {
1830 # Convert spec to perl code.
1834 \s* # ignore whitespace
1835 ( # 1: match a single word
1842 \w+\([^\)]*\) # command(params)
1844 [^\s()]+ # any other text
1846 \s* # ignore whitespace
1849 if (lc $word eq 'and') {
1852 elsif (lc $word eq 'or') {
1855 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1858 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1859 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1861 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
1864 push @data, qq{unknown function in pagespec "$word"};
1865 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
1870 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
1874 if (! length $code) {
1875 $code="IkiWiki::FailReason->new('empty pagespec')";
1879 return eval 'sub { my $page=shift; '.$code.' }';
1882 sub pagespec_match ($$;@) {
1887 # Backwards compatability with old calling convention.
1889 unshift @params, 'location';
1892 my $sub=pagespec_translate($spec);
1893 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
1894 if $@ || ! defined $sub;
1895 return $sub->($page, @params);
1898 sub pagespec_match_list ($$;@) {
1903 my $sub=pagespec_translate($spec);
1904 error "syntax error in pagespec \"$spec\""
1905 if $@ || ! defined $sub;
1909 foreach my $page (@$pages) {
1910 $r=$sub->($page, @params);
1911 push @ret, $page if $r;
1914 if (! @ret && defined $r && $r->isa("IkiWiki::ErrorReason")) {
1915 error(sprintf(gettext("cannot match pages: %s"), $r));
1922 sub pagespec_valid ($) {
1925 my $sub=pagespec_translate($spec);
1930 my $re=quotemeta(shift);
1936 package IkiWiki::FailReason;
1939 '""' => sub { ${$_[0]} },
1941 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1948 return bless \$value, $class;
1951 package IkiWiki::ErrorReason;
1953 our @ISA = 'IkiWiki::FailReason';
1955 package IkiWiki::SuccessReason;
1958 '""' => sub { ${$_[0]} },
1960 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1967 return bless \$value, $class;
1970 package IkiWiki::PageSpec;
1976 if ($path =~ m!^\./!) {
1977 $from=~s#/?[^/]+$## if defined $from;
1979 $path="$from/$path" if length $from;
1985 sub match_glob ($$;@) {
1990 $glob=derel($glob, $params{location});
1992 my $regexp=IkiWiki::glob2re($glob);
1993 if ($page=~/^$regexp$/i) {
1994 if (! IkiWiki::isinternal($page) || $params{internal}) {
1995 return IkiWiki::SuccessReason->new("$glob matches $page");
1998 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2002 return IkiWiki::FailReason->new("$glob does not match $page");
2006 sub match_internal ($$;@) {
2007 return match_glob($_[0], $_[1], @_, internal => 1)
2010 sub match_link ($$;@) {
2015 $link=derel($link, $params{location});
2016 my $from=exists $params{location} ? $params{location} : '';
2018 my $links = $IkiWiki::links{$page};
2019 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
2020 my $bestlink = IkiWiki::bestlink($from, $link);
2021 foreach my $p (@{$links}) {
2022 if (length $bestlink) {
2023 return IkiWiki::SuccessReason->new("$page links to $link")
2024 if $bestlink eq IkiWiki::bestlink($page, $p);
2027 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
2028 if match_glob($p, $link, %params);
2031 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
2032 if match_glob($p, $link, %params);
2035 return IkiWiki::FailReason->new("$page does not link to $link");
2038 sub match_backlink ($$;@) {
2039 return match_link($_[1], $_[0], @_);
2042 sub match_created_before ($$;@) {
2047 $testpage=derel($testpage, $params{location});
2049 if (exists $IkiWiki::pagectime{$testpage}) {
2050 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2051 return IkiWiki::SuccessReason->new("$page created before $testpage");
2054 return IkiWiki::FailReason->new("$page not created before $testpage");
2058 return IkiWiki::ErrorReason->new("$testpage does not exist");
2062 sub match_created_after ($$;@) {
2067 $testpage=derel($testpage, $params{location});
2069 if (exists $IkiWiki::pagectime{$testpage}) {
2070 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2071 return IkiWiki::SuccessReason->new("$page created after $testpage");
2074 return IkiWiki::FailReason->new("$page not created after $testpage");
2078 return IkiWiki::ErrorReason->new("$testpage does not exist");
2082 sub match_creation_day ($$;@) {
2083 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2084 return IkiWiki::SuccessReason->new('creation_day matched');
2087 return IkiWiki::FailReason->new('creation_day did not match');
2091 sub match_creation_month ($$;@) {
2092 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2093 return IkiWiki::SuccessReason->new('creation_month matched');
2096 return IkiWiki::FailReason->new('creation_month did not match');
2100 sub match_creation_year ($$;@) {
2101 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2102 return IkiWiki::SuccessReason->new('creation_year matched');
2105 return IkiWiki::FailReason->new('creation_year did not match');
2109 sub match_user ($$;@) {
2114 if (! exists $params{user}) {
2115 return IkiWiki::ErrorReason->new("no user specified");
2118 if (defined $params{user} && lc $params{user} eq lc $user) {
2119 return IkiWiki::SuccessReason->new("user is $user");
2121 elsif (! defined $params{user}) {
2122 return IkiWiki::FailReason->new("not logged in");
2125 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2129 sub match_admin ($$;@) {
2134 if (! exists $params{user}) {
2135 return IkiWiki::ErrorReason->new("no user specified");
2138 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2139 return IkiWiki::SuccessReason->new("user is an admin");
2141 elsif (! defined $params{user}) {
2142 return IkiWiki::FailReason->new("not logged in");
2145 return IkiWiki::FailReason->new("user is not an admin");
2149 sub match_ip ($$;@) {
2154 if (! exists $params{ip}) {
2155 return IkiWiki::ErrorReason->new("no IP specified");
2158 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2159 return IkiWiki::SuccessReason->new("IP is $ip");
2162 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");