9 use URI::Escape q{uri_escape_utf8};
12 use open qw{:utf8 :std};
14 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
15 %pagestate %wikistate %renderedfiles %oldrenderedfiles
16 %pagesources %destsources %depends %depends_simple %hooks
17 %forcerebuild %loaded_plugins};
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
21 pagespec_match_list bestlink htmllink readfile writefile
22 pagetype srcfile pagename displaytime will_render gettext urlto
23 targetpage add_underlay pagetitle titlepage linkpage
24 newpagefile inject add_link
25 %config %links %pagestate %wikistate %renderedfiles
26 %pagesources %destsources);
27 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
28 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
29 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
34 memoize("pagespec_translate");
35 memoize("file_pruned");
36 memoize("template_file");
42 description => "name of the wiki",
49 example => 'me@example.com',
50 description => "contact email for wiki",
57 description => "users who are wiki admins",
64 description => "users who are banned from the wiki",
71 example => "$ENV{HOME}/wiki",
72 description => "where the source of the wiki is located",
79 example => "/var/www/wiki",
80 description => "where to build the wiki",
87 example => "http://example.com/wiki",
88 description => "base url to the wiki",
95 example => "http://example.com/wiki/ikiwiki.cgi",
96 description => "url to the ikiwiki.cgi",
103 example => "/var/www/wiki/ikiwiki.cgi",
104 description => "filename of cgi wrapper to generate",
111 description => "mode for cgi_wrapper (can safely be made suid)",
118 description => "rcs backend to use",
119 safe => 0, # don't allow overriding
124 default => [qw{mdwn link inline meta htmlscrubber passwordauth
125 openid signinedit lockedit conditional
126 recentchanges parentlinks editpage}],
127 description => "plugins to enable by default",
134 description => "plugins to add to the default configuration",
141 description => "plugins to disable",
147 default => "$installdir/share/ikiwiki/templates",
148 description => "location of template files",
155 default => "$installdir/share/ikiwiki/basewiki",
156 description => "base wiki source location",
163 default => "$installdir/share/ikiwiki",
164 description => "parent directory containing additional underlays",
171 description => "wrappers to generate",
178 description => "additional underlays to use",
185 description => "display verbose messages?",
192 description => "log to syslog?",
199 description => "create output files named page/index.html?",
200 safe => 0, # changing requires manual transition
203 prefix_directives => {
206 description => "use '!'-prefixed preprocessor directives?",
207 safe => 0, # changing requires manual transition
213 description => "use page/index.mdwn source files",
220 description => "enable Discussion pages?",
226 default => gettext("Discussion"),
227 description => "name of Discussion pages",
234 description => "only send cookies over SSL connections?",
242 description => "extension to use for new pages",
243 safe => 0, # not sanitized
249 description => "extension to use for html files",
250 safe => 0, # not sanitized
256 description => "strftime format string to display date",
264 example => "en_US.UTF-8",
265 description => "UTF-8 locale to use",
274 description => "put user pages below specified page",
281 description => "how many backlinks to show before hiding excess (0 to show all)",
288 description => "attempt to hardlink source files? (optimisation for large files)",
290 safe => 0, # paranoia
296 description => "force ikiwiki to use a particular umask",
298 safe => 0, # paranoia
303 example => "ikiwiki",
304 description => "group for wrappers to run in",
306 safe => 0, # paranoia
312 example => "$ENV{HOME}/.ikiwiki/",
313 description => "extra library and plugin directory",
315 safe => 0, # directory
321 description => "environment variables",
322 safe => 0, # paranoia
329 description => "regexp of source files to ignore",
334 wiki_file_prune_regexps => {
336 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
337 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
338 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
339 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
341 description => "regexps of source files to ignore",
347 description => "specifies the characters that are allowed in source filenames",
348 default => "-[:alnum:]+/.:_",
352 wiki_file_regexp => {
354 description => "regexp of legal source files",
358 web_commit_regexp => {
360 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
361 description => "regexp to parse web commits from logs",
368 description => "run as a cgi",
372 cgi_disable_uploads => {
375 description => "whether CGI should accept file uploads",
382 description => "run as a post-commit hook",
389 description => "running in rebuild mode",
396 description => "running in setup mode",
403 description => "running in refresh mode",
410 description => "running in receive test mode",
417 description => "running in getctime mode",
424 description => "running in w3mmode",
431 description => "path to the .ikiwiki directory holding ikiwiki state",
438 description => "path to setup file",
442 allow_symlinks_before_srcdir => {
445 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
451 sub defaultconfig () {
454 foreach my $key (keys %s) {
455 push @ret, $key, $s{$key}->{default};
462 # locale stuff; avoid LC_ALL since it overrides everything
463 if (defined $ENV{LC_ALL}) {
464 $ENV{LANG} = $ENV{LC_ALL};
467 if (defined $config{locale}) {
468 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
469 $ENV{LANG}=$config{locale};
474 if (! defined $config{wiki_file_regexp}) {
475 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
478 if (ref $config{ENV} eq 'HASH') {
479 foreach my $val (keys %{$config{ENV}}) {
480 $ENV{$val}=$config{ENV}{$val};
484 if ($config{w3mmode}) {
485 eval q{use Cwd q{abs_path}};
487 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
488 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
489 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
490 unless $config{cgiurl} =~ m!file:///!;
491 $config{url}="file://".$config{destdir};
494 if ($config{cgi} && ! length $config{url}) {
495 error(gettext("Must specify url to wiki with --url when using --cgi"));
498 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
499 unless exists $config{wikistatedir} && defined $config{wikistatedir};
501 if (defined $config{umask}) {
502 umask(possibly_foolish_untaint($config{umask}));
505 run_hooks(checkconfig => sub { shift->() });
513 foreach my $dir (@INC, $config{libdir}) {
514 next unless defined $dir && length $dir;
515 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
516 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
520 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
521 next unless defined $dir && length $dir;
522 foreach my $file (glob("$dir/plugins/*")) {
523 $ret{basename($file)}=1 if -x $file;
531 if (defined $config{libdir} && length $config{libdir}) {
532 unshift @INC, possibly_foolish_untaint($config{libdir});
535 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
540 if (exists $IkiWiki::hooks{rcs}) {
541 error(gettext("cannot use multiple rcs plugins"));
543 loadplugin($config{rcs});
545 if (! exists $IkiWiki::hooks{rcs}) {
549 run_hooks(getopt => sub { shift->() });
550 if (grep /^-/, @ARGV) {
551 print STDERR "Unknown option (or missing parameter): $_\n"
552 foreach grep /^-/, @ARGV;
562 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
564 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
565 "$installdir/lib/ikiwiki") {
566 if (defined $dir && -x "$dir/plugins/$plugin") {
567 eval { require IkiWiki::Plugin::external };
570 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
572 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
573 $loaded_plugins{$plugin}=1;
578 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
581 error("Failed to load plugin $mod: $@");
583 $loaded_plugins{$plugin}=1;
590 log_message('err' => $message) if $config{syslog};
591 if (defined $cleaner) {
598 return unless $config{verbose};
599 return log_message(debug => @_);
603 sub log_message ($$) {
606 if ($config{syslog}) {
609 Sys::Syslog::setlogsock('unix');
610 Sys::Syslog::openlog('ikiwiki', '', 'user');
614 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
617 elsif (! $config{cgi}) {
621 return print STDERR "@_\n";
625 sub possibly_foolish_untaint ($) {
627 my ($untainted)=$tainted=~/(.*)/s;
647 return exists $pagesources{$page} &&
648 $pagesources{$page} =~ /\._([^.]+)$/;
654 if ($file =~ /\.([^.]+)$/) {
655 return $1 if exists $hooks{htmlize}{$1};
657 my $base=basename($file);
658 if (exists $hooks{htmlize}{$base} &&
659 $hooks{htmlize}{$base}{noextension}) {
670 if (exists $pagename_cache{$file}) {
671 return $pagename_cache{$file};
674 my $type=pagetype($file);
676 $page=~s/\Q.$type\E*$//
677 if defined $type && !$hooks{htmlize}{$type}{keepextension}
678 && !$hooks{htmlize}{$type}{noextension};
679 if ($config{indexpages} && $page=~/(.*)\/index$/) {
683 $pagename_cache{$file} = $page;
687 sub newpagefile ($$) {
691 if (! $config{indexpages} || $page eq 'index') {
692 return $page.".".$type;
695 return $page."/index.".$type;
699 sub targetpage ($$;$) {
704 if (defined $filename) {
705 return $page."/".$filename.".".$ext;
707 elsif (! $config{usedirs} || $page eq 'index') {
708 return $page.".".$ext;
711 return $page."/index.".$ext;
718 return targetpage($page, $config{htmlext});
725 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
726 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
727 return "$dir/$file", stat(_) if -e "$dir/$file";
729 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
734 return (srcfile_stat(@_))[0];
737 sub add_underlay ($) {
741 $dir="$config{underlaydirbase}/$dir";
744 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
745 unshift @{$config{underlaydirs}}, $dir;
751 sub readfile ($;$$) {
757 error("cannot read a symlink ($file)");
761 open (my $in, "<", $file) || error("failed to read $file: $!");
762 binmode($in) if ($binary);
763 return \*$in if $wantfd;
765 # check for invalid utf-8, and toss it back to avoid crashes
766 if (! utf8::valid($ret)) {
767 $ret=encode_utf8($ret);
769 close $in || error("failed to read $file: $!");
773 sub prep_writefile ($$) {
778 while (length $test) {
779 if (-l "$destdir/$test") {
780 error("cannot write to a symlink ($test)");
782 $test=dirname($test);
785 my $dir=dirname("$destdir/$file");
788 foreach my $s (split(m!/+!, $dir)) {
791 mkdir($d) || error("failed to create directory $d: $!");
799 sub writefile ($$$;$$) {
800 my $file=shift; # can include subdirs
801 my $destdir=shift; # directory to put file in
806 prep_writefile($file, $destdir);
808 my $newfile="$destdir/$file.ikiwiki-new";
810 error("cannot write to a symlink ($newfile)");
813 my $cleanup = sub { unlink($newfile) };
814 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
815 binmode($out) if ($binary);
817 $writer->(\*$out, $cleanup);
820 print $out $content or error("failed writing to $newfile: $!", $cleanup);
822 close $out || error("failed saving $newfile: $!", $cleanup);
823 rename($newfile, "$destdir/$file") ||
824 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
830 sub will_render ($$;$) {
835 # Important security check.
836 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
837 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
838 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
841 if (! $clear || $cleared{$page}) {
842 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
845 foreach my $old (@{$renderedfiles{$page}}) {
846 delete $destsources{$old};
848 $renderedfiles{$page}=[$dest];
851 $destsources{$dest}=$page;
861 if ($link=~s/^\/+//) {
869 $l.="/" if length $l;
872 if (exists $links{$l}) {
875 elsif (exists $pagecase{lc $l}) {
876 return $pagecase{lc $l};
878 } while $cwd=~s{/?[^/]+$}{};
880 if (length $config{userdir}) {
881 my $l = "$config{userdir}/".lc($link);
882 if (exists $links{$l}) {
885 elsif (exists $pagecase{lc $l}) {
886 return $pagecase{lc $l};
890 #print STDERR "warning: page $page, broken link: $link\n";
894 sub isinlinableimage ($) {
897 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
900 sub pagetitle ($;$) {
905 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
908 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
916 # support use w/o %config set
917 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
918 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
924 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
925 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
932 return $config{cgiurl}."?".
933 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
939 return "$config{url}/" if ! defined $page;
941 $page=htmlpage($page);
943 $page=~s/[^\/]+\//..\//g;
948 # Work around very innefficient behavior in File::Spec if abs2rel
949 # is passed two relative paths. It's much faster if paths are
950 # absolute! (Debian bug #376658; fixed in debian unstable now)
955 my $ret=File::Spec->abs2rel($path, $base);
956 $ret=~s/^// if defined $ret;
960 sub displaytime ($;$) {
961 # Plugins can override this function to mark up the time to
963 return '<span class="date">'.formattime(@_).'</span>';
966 sub formattime ($;$) {
967 # Plugins can override this function to format the time.
970 if (! defined $format) {
971 $format=$config{timeformat};
974 # strftime doesn't know about encodings, so make sure
975 # its output is properly treated as utf8
976 return decode_utf8(POSIX::strftime($format, localtime($time)));
979 sub beautify_urlpath ($) {
982 # Ensure url is not an empty link, and if necessary,
983 # add ./ to avoid colon confusion.
984 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
988 if ($config{usedirs}) {
989 $url =~ s!/index.$config{htmlext}$!/!;
1001 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1004 if (! $destsources{$to}) {
1009 return $config{url}.beautify_urlpath("/".$to);
1012 my $link = abs2rel($to, dirname(htmlpage($from)));
1014 return beautify_urlpath($link);
1017 sub htmllink ($$$;@) {
1018 my $lpage=shift; # the page doing the linking
1019 my $page=shift; # the page that will contain the link (different for inline)
1026 if (! $opts{forcesubpage}) {
1027 $bestlink=bestlink($lpage, $link);
1030 $bestlink="$lpage/".lc($link);
1034 if (defined $opts{linktext}) {
1035 $linktext=$opts{linktext};
1038 $linktext=pagetitle(basename($link));
1041 return "<span class=\"selflink\">$linktext</span>"
1042 if length $bestlink && $page eq $bestlink &&
1043 ! defined $opts{anchor};
1045 if (! $destsources{$bestlink}) {
1046 $bestlink=htmlpage($bestlink);
1048 if (! $destsources{$bestlink}) {
1049 return $linktext unless length $config{cgiurl};
1050 return "<span class=\"createlink\"><a href=\"".
1056 "\" rel=\"nofollow\">?</a>$linktext</span>"
1060 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1061 $bestlink=beautify_urlpath($bestlink);
1063 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1064 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1067 if (defined $opts{anchor}) {
1068 $bestlink.="#".$opts{anchor};
1072 if (defined $opts{rel}) {
1073 push @attrs, ' rel="'.$opts{rel}.'"';
1075 if (defined $opts{class}) {
1076 push @attrs, ' class="'.$opts{class}.'"';
1079 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1082 sub openiduser ($) {
1085 if ($user =~ m!^https?://! &&
1086 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1089 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1090 # this works in at least 2.x
1091 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1094 # this only works in 1.x
1095 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1096 $display=$oid->display;
1099 # Convert "user.somehost.com" to "user [somehost.com]"
1100 # (also "user.somehost.co.uk")
1101 if ($display !~ /\[/) {
1102 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1104 # Convert "http://somehost.com/user" to "user [somehost.com]".
1105 # (also "https://somehost.com/user/")
1106 if ($display !~ /\[/) {
1107 $display=~s/^https?:\/\/(.+)\/([^\/]+)\/?$/$2 [$1]/;
1109 $display=~s!^https?://!!; # make sure this is removed
1110 eval q{use CGI 'escapeHTML'};
1112 return escapeHTML($display);
1120 my $oiduser=eval { openiduser($user) };
1121 if (defined $oiduser) {
1122 return "<a href=\"$user\">$oiduser</a>";
1125 eval q{use CGI 'escapeHTML'};
1128 return htmllink("", "", escapeHTML(
1129 length $config{userdir} ? $config{userdir}."/".$user : $user
1130 ), noimageinline => 1);
1134 sub htmlize ($$$$) {
1140 my $oneline = $content !~ /\n/;
1142 if (exists $hooks{htmlize}{$type}) {
1143 $content=$hooks{htmlize}{$type}{call}->(
1145 content => $content,
1149 error("htmlization of $type not supported");
1152 run_hooks(sanitize => sub {
1155 destpage => $destpage,
1156 content => $content,
1161 # hack to get rid of enclosing junk added by markdown
1162 # and other htmlizers
1163 $content=~s/^<p>//i;
1164 $content=~s/<\/p>$//i;
1176 run_hooks(linkify => sub {
1179 destpage => $destpage,
1180 content => $content,
1188 our $preprocess_preview=0;
1189 sub preprocess ($$$;$$) {
1190 my $page=shift; # the page the data comes from
1191 my $destpage=shift; # the page the data will appear in (different for inline)
1196 # Using local because it needs to be set within any nested calls
1198 local $preprocess_preview=$preview if defined $preview;
1205 $params="" if ! defined $params;
1207 if (length $escape) {
1208 return "[[$prefix$command $params]]";
1210 elsif (exists $hooks{preprocess}{$command}) {
1211 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1212 # Note: preserve order of params, some plugins may
1213 # consider it significant.
1215 while ($params =~ m{
1216 (?:([-\w]+)=)? # 1: named parameter key?
1218 """(.*?)""" # 2: triple-quoted value
1220 "([^"]+)" # 3: single-quoted value
1222 (\S+) # 4: unquoted value
1224 (?:\s+|$) # delimiter to next param
1234 elsif (defined $3) {
1237 elsif (defined $4) {
1242 push @params, $key, $val;
1245 push @params, $val, '';
1248 if ($preprocessing{$page}++ > 3) {
1249 # Avoid loops of preprocessed pages preprocessing
1250 # other pages that preprocess them, etc.
1251 return "[[!$command <span class=\"error\">".
1252 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1253 $page, $preprocessing{$page}).
1259 $hooks{preprocess}{$command}{call}->(
1262 destpage => $destpage,
1263 preview => $preprocess_preview,
1269 $ret="[[!$command <span class=\"error\">".
1270 gettext("Error").": $error"."</span>]]";
1274 # use void context during scan pass
1276 $hooks{preprocess}{$command}{call}->(
1279 destpage => $destpage,
1280 preview => $preprocess_preview,
1285 $preprocessing{$page}--;
1289 return "[[$prefix$command $params]]";
1294 if ($config{prefix_directives}) {
1297 \[\[(!) # directive open; 2: prefix
1298 ([-\w]+) # 3: command
1299 ( # 4: the parameters..
1300 \s+ # Must have space if parameters present
1302 (?:[-\w]+=)? # named parameter key?
1304 """.*?""" # triple-quoted value
1306 "[^"]+" # single-quoted value
1308 [^"\s\]]+ # unquoted value
1310 \s* # whitespace or end
1313 *)? # 0 or more parameters
1314 \]\] # directive closed
1320 \[\[(!?) # directive open; 2: optional prefix
1321 ([-\w]+) # 3: command
1323 ( # 4: the parameters..
1325 (?:[-\w]+=)? # named parameter key?
1327 """.*?""" # triple-quoted value
1329 "[^"]+" # single-quoted value
1331 [^"\s\]]+ # unquoted value
1333 \s* # whitespace or end
1336 *) # 0 or more parameters
1337 \]\] # directive closed
1341 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1350 run_hooks(filter => sub {
1351 $content=shift->(page => $page, destpage => $destpage,
1352 content => $content);
1359 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1362 sub check_canedit ($$$;$) {
1369 run_hooks(canedit => sub {
1370 return if defined $canedit;
1371 my $ret=shift->($page, $q, $session);
1376 elsif (ref $ret eq 'CODE') {
1377 $ret->() unless $nonfatal;
1380 elsif (defined $ret) {
1381 error($ret) unless $nonfatal;
1386 return defined $canedit ? $canedit : 1;
1389 sub check_content (@) {
1392 return 1 if ! exists $hooks{checkcontent}; # optimisation
1394 if (exists $pagesources{$params{page}}) {
1396 my %old=map { $_ => 1 }
1397 split("\n", readfile(srcfile($pagesources{$params{page}})));
1398 foreach my $line (split("\n", $params{content})) {
1399 push @diff, $line if ! exists $old{$_};
1401 $params{diff}=join("\n", @diff);
1405 run_hooks(checkcontent => sub {
1406 return if defined $ok;
1407 my $ret=shift->(%params);
1412 elsif (ref $ret eq 'CODE') {
1413 $ret->() unless $params{nonfatal};
1416 elsif (defined $ret) {
1417 error($ret) unless $params{nonfatal};
1423 return defined $ok ? $ok : 1;
1429 # Take an exclusive lock on the wiki to prevent multiple concurrent
1430 # run issues. The lock will be dropped on program exit.
1431 if (! -d $config{wikistatedir}) {
1432 mkdir($config{wikistatedir});
1434 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1435 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1436 if (! flock($wikilock, 2)) { # LOCK_EX
1437 error("failed to get lock");
1443 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1444 return close($wikilock) if $wikilock;
1450 sub commit_hook_enabled () {
1451 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1452 error("cannot write to $config{wikistatedir}/commitlock: $!");
1453 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1454 close($commitlock) || error("failed closing commitlock: $!");
1457 close($commitlock) || error("failed closing commitlock: $!");
1461 sub disable_commit_hook () {
1462 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1463 error("cannot write to $config{wikistatedir}/commitlock: $!");
1464 if (! flock($commitlock, 2)) { # LOCK_EX
1465 error("failed to get commit lock");
1470 sub enable_commit_hook () {
1471 return close($commitlock) if $commitlock;
1476 %oldrenderedfiles=%pagectime=();
1477 if (! $config{rebuild}) {
1478 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1479 %destsources=%renderedfiles=%pagecase=%pagestate=
1483 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1484 if (-e "$config{wikistatedir}/index") {
1485 system("ikiwiki-transition", "indexdb", $config{srcdir});
1486 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1493 my $index=Storable::fd_retrieve($in);
1494 if (! defined $index) {
1499 if (exists $index->{version} && ! ref $index->{version}) {
1500 $pages=$index->{page};
1501 %wikistate=%{$index->{state}};
1508 foreach my $src (keys %$pages) {
1509 my $d=$pages->{$src};
1510 my $page=pagename($src);
1511 $pagectime{$page}=$d->{ctime};
1512 if (! $config{rebuild}) {
1513 $pagesources{$page}=$src;
1514 $pagemtime{$page}=$d->{mtime};
1515 $renderedfiles{$page}=$d->{dest};
1516 if (exists $d->{links} && ref $d->{links}) {
1517 $links{$page}=$d->{links};
1518 $oldlinks{$page}=[@{$d->{links}}];
1520 if (exists $d->{depends_simple}) {
1521 $depends_simple{$page}={
1522 map { $_ => 1 } @{$d->{depends_simple}}
1525 if (exists $d->{dependslist}) {
1527 map { $_ => 1 } @{$d->{dependslist}}
1530 elsif (exists $d->{depends}) {
1531 $depends{$page}={$d->{depends} => 1};
1533 if (exists $d->{state}) {
1534 $pagestate{$page}=$d->{state};
1537 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1539 foreach my $page (keys %pagesources) {
1540 $pagecase{lc $page}=$page;
1542 foreach my $page (keys %renderedfiles) {
1543 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1549 run_hooks(savestate => sub { shift->() });
1552 foreach my $type (keys %hooks) {
1553 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1555 my @hookids=keys %hookids;
1557 if (! -d $config{wikistatedir}) {
1558 mkdir($config{wikistatedir});
1560 my $newfile="$config{wikistatedir}/indexdb.new";
1561 my $cleanup = sub { unlink($newfile) };
1562 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1565 foreach my $page (keys %pagemtime) {
1566 next unless $pagemtime{$page};
1567 my $src=$pagesources{$page};
1569 $index{page}{$src}={
1570 ctime => $pagectime{$page},
1571 mtime => $pagemtime{$page},
1572 dest => $renderedfiles{$page},
1573 links => $links{$page},
1576 if (exists $depends{$page}) {
1577 $index{page}{$src}{dependslist} = [ keys %{$depends{$page}} ];
1580 if (exists $depends_simple{$page}) {
1581 $index{page}{$src}{depends_simple} = [ keys %{$depends_simple{$page}} ];
1584 if (exists $pagestate{$page}) {
1585 foreach my $id (@hookids) {
1586 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1587 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1594 foreach my $id (@hookids) {
1595 foreach my $key (keys %{$wikistate{$id}}) {
1596 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1600 $index{version}="3";
1601 my $ret=Storable::nstore_fd(\%index, $out);
1602 return if ! defined $ret || ! $ret;
1603 close $out || error("failed saving to $newfile: $!", $cleanup);
1604 rename($newfile, "$config{wikistatedir}/indexdb") ||
1605 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1610 sub template_file ($) {
1613 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1614 return "$dir/$template" if -e "$dir/$template";
1619 sub template_params (@) {
1620 my $filename=template_file(shift);
1622 if (! defined $filename) {
1623 return if wantarray;
1629 my $text_ref = shift;
1630 ${$text_ref} = decode_utf8(${$text_ref});
1632 filename => $filename,
1633 loop_context_vars => 1,
1634 die_on_bad_params => 0,
1637 return wantarray ? @ret : {@ret};
1640 sub template ($;@) {
1641 require HTML::Template;
1642 return HTML::Template->new(template_params(@_));
1645 sub misctemplate ($$;@) {
1649 my $template=template("misc.tmpl");
1652 indexlink => indexlink(),
1653 wikiname => $config{wikiname},
1654 pagebody => $pagebody,
1655 baseurl => baseurl(),
1658 run_hooks(pagetemplate => sub {
1659 shift->(page => "", destpage => "", template => $template);
1661 return $template->output;
1667 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1668 error 'hook requires type, call, and id parameters';
1671 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1673 $hooks{$param{type}}{$param{id}}=\%param;
1677 sub run_hooks ($$) {
1678 # Calls the given sub for each hook of the given type,
1679 # passing it the hook function to call.
1683 if (exists $hooks{$type}) {
1684 my (@first, @middle, @last);
1685 foreach my $id (keys %{$hooks{$type}}) {
1686 if ($hooks{$type}{$id}{first}) {
1689 elsif ($hooks{$type}{$id}{last}) {
1696 foreach my $id (@first, @middle, @last) {
1697 $sub->($hooks{$type}{$id}{call});
1705 $hooks{rcs}{rcs_update}{call}->(@_);
1708 sub rcs_prepedit ($) {
1709 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1712 sub rcs_commit ($$$;$$) {
1713 $hooks{rcs}{rcs_commit}{call}->(@_);
1716 sub rcs_commit_staged ($$$) {
1717 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1721 $hooks{rcs}{rcs_add}{call}->(@_);
1724 sub rcs_remove ($) {
1725 $hooks{rcs}{rcs_remove}{call}->(@_);
1728 sub rcs_rename ($$) {
1729 $hooks{rcs}{rcs_rename}{call}->(@_);
1732 sub rcs_recentchanges ($) {
1733 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1737 $hooks{rcs}{rcs_diff}{call}->(@_);
1740 sub rcs_getctime ($) {
1741 $hooks{rcs}{rcs_getctime}{call}->(@_);
1744 sub rcs_receive () {
1745 $hooks{rcs}{rcs_receive}{call}->();
1748 sub add_depends ($$) {
1752 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1753 $pagespec !~ /[\s*?()!]/) {
1754 # a simple dependency, which can be matched by string eq
1755 $depends_simple{$page}{lc $pagespec} = 1;
1759 return unless pagespec_valid($pagespec);
1761 $depends{$page}{$pagespec} = 1;
1765 sub file_pruned ($$) {
1767 my $file=File::Spec->canonpath(shift);
1768 my $base=File::Spec->canonpath(shift);
1769 $file =~ s#^\Q$base\E/+##;
1771 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1772 return $file =~ m/$regexp/ && $file ne $base;
1775 sub define_gettext () {
1776 # If translation is needed, redefine the gettext function to do it.
1777 # Otherwise, it becomes a quick no-op.
1778 no warnings 'redefine';
1779 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1780 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1781 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1783 my $gettext_obj=eval q{
1784 use Locale::gettext q{textdomain};
1785 Locale::gettext->domain('ikiwiki')
1789 $gettext_obj->get(shift);
1797 *gettext=sub { return shift };
1809 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1813 # Injects a new function into the symbol table to replace an
1814 # exported function.
1817 # This is deep ugly perl foo, beware.
1820 if (! defined $params{parent}) {
1821 $params{parent}='::';
1822 $params{old}=\&{$params{name}};
1823 $params{name}=~s/.*:://;
1825 my $parent=$params{parent};
1826 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1827 $ns = $params{parent} . $ns;
1828 inject(%params, parent => $ns) unless $ns eq '::main::';
1829 *{$ns . $params{name}} = $params{call}
1830 if exists ${$ns}{$params{name}} &&
1831 \&{${$ns}{$params{name}}} == $params{old};
1841 push @{$links{$page}}, $link
1842 unless grep { $_ eq $link } @{$links{$page}};
1845 sub pagespec_translate ($) {
1848 # Convert spec to perl code.
1852 \s* # ignore whitespace
1853 ( # 1: match a single word
1860 \w+\([^\)]*\) # command(params)
1862 [^\s()]+ # any other text
1864 \s* # ignore whitespace
1867 if (lc $word eq 'and') {
1870 elsif (lc $word eq 'or') {
1873 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1876 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1877 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1879 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
1882 push @data, qq{unknown function in pagespec "$word"};
1883 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
1888 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
1892 if (! length $code) {
1893 $code="IkiWiki::FailReason->new('empty pagespec')";
1897 return eval 'sub { my $page=shift; '.$code.' }';
1900 sub pagespec_match ($$;@) {
1905 # Backwards compatability with old calling convention.
1907 unshift @params, 'location';
1910 my $sub=pagespec_translate($spec);
1911 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
1912 if $@ || ! defined $sub;
1913 return $sub->($page, @params);
1916 sub pagespec_match_list ($$;@) {
1921 my $sub=pagespec_translate($spec);
1922 error "syntax error in pagespec \"$spec\""
1923 if $@ || ! defined $sub;
1927 foreach my $page (@$pages) {
1928 $r=$sub->($page, @params);
1929 push @ret, $page if $r;
1932 if (! @ret && defined $r && $r->isa("IkiWiki::ErrorReason")) {
1933 error(sprintf(gettext("cannot match pages: %s"), $r));
1940 sub pagespec_valid ($) {
1943 my $sub=pagespec_translate($spec);
1948 my $re=quotemeta(shift);
1954 package IkiWiki::FailReason;
1957 '""' => sub { ${$_[0]} },
1959 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1966 return bless \$value, $class;
1969 package IkiWiki::ErrorReason;
1971 our @ISA = 'IkiWiki::FailReason';
1973 package IkiWiki::SuccessReason;
1976 '""' => sub { ${$_[0]} },
1978 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1985 return bless \$value, $class;
1988 package IkiWiki::PageSpec;
1994 if ($path =~ m!^\./!) {
1995 $from=~s#/?[^/]+$## if defined $from;
1997 $path="$from/$path" if length $from;
2003 sub match_glob ($$;@) {
2008 $glob=derel($glob, $params{location});
2010 my $regexp=IkiWiki::glob2re($glob);
2011 if ($page=~/^$regexp$/i) {
2012 if (! IkiWiki::isinternal($page) || $params{internal}) {
2013 return IkiWiki::SuccessReason->new("$glob matches $page");
2016 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2020 return IkiWiki::FailReason->new("$glob does not match $page");
2024 sub match_internal ($$;@) {
2025 return match_glob($_[0], $_[1], @_, internal => 1)
2028 sub match_link ($$;@) {
2033 $link=derel($link, $params{location});
2034 my $from=exists $params{location} ? $params{location} : '';
2036 my $links = $IkiWiki::links{$page};
2037 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
2038 my $bestlink = IkiWiki::bestlink($from, $link);
2039 foreach my $p (@{$links}) {
2040 if (length $bestlink) {
2041 return IkiWiki::SuccessReason->new("$page links to $link")
2042 if $bestlink eq IkiWiki::bestlink($page, $p);
2045 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
2046 if match_glob($p, $link, %params);
2049 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
2050 if match_glob($p, $link, %params);
2053 return IkiWiki::FailReason->new("$page does not link to $link");
2056 sub match_backlink ($$;@) {
2057 return match_link($_[1], $_[0], @_);
2060 sub match_created_before ($$;@) {
2065 $testpage=derel($testpage, $params{location});
2067 if (exists $IkiWiki::pagectime{$testpage}) {
2068 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2069 return IkiWiki::SuccessReason->new("$page created before $testpage");
2072 return IkiWiki::FailReason->new("$page not created before $testpage");
2076 return IkiWiki::ErrorReason->new("$testpage does not exist");
2080 sub match_created_after ($$;@) {
2085 $testpage=derel($testpage, $params{location});
2087 if (exists $IkiWiki::pagectime{$testpage}) {
2088 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2089 return IkiWiki::SuccessReason->new("$page created after $testpage");
2092 return IkiWiki::FailReason->new("$page not created after $testpage");
2096 return IkiWiki::ErrorReason->new("$testpage does not exist");
2100 sub match_creation_day ($$;@) {
2101 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2102 return IkiWiki::SuccessReason->new('creation_day matched');
2105 return IkiWiki::FailReason->new('creation_day did not match');
2109 sub match_creation_month ($$;@) {
2110 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2111 return IkiWiki::SuccessReason->new('creation_month matched');
2114 return IkiWiki::FailReason->new('creation_month did not match');
2118 sub match_creation_year ($$;@) {
2119 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2120 return IkiWiki::SuccessReason->new('creation_year matched');
2123 return IkiWiki::FailReason->new('creation_year did not match');
2127 sub match_user ($$;@) {
2132 if (! exists $params{user}) {
2133 return IkiWiki::ErrorReason->new("no user specified");
2136 if (defined $params{user} && lc $params{user} eq lc $user) {
2137 return IkiWiki::SuccessReason->new("user is $user");
2139 elsif (! defined $params{user}) {
2140 return IkiWiki::FailReason->new("not logged in");
2143 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2147 sub match_admin ($$;@) {
2152 if (! exists $params{user}) {
2153 return IkiWiki::ErrorReason->new("no user specified");
2156 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2157 return IkiWiki::SuccessReason->new("user is an admin");
2159 elsif (! defined $params{user}) {
2160 return IkiWiki::FailReason->new("not logged in");
2163 return IkiWiki::FailReason->new("user is not an admin");
2167 sub match_ip ($$;@) {
2172 if (! exists $params{ip}) {
2173 return IkiWiki::ErrorReason->new("no IP specified");
2176 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2177 return IkiWiki::SuccessReason->new("IP is $ip");
2180 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");