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
17 $gettext_obj %loaded_plugins};
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
21 bestlink htmllink readfile writefile pagetype srcfile pagename
22 displaytime will_render gettext urlto targetpage
23 add_underlay pagetitle titlepage linkpage
24 %config %links %pagestate %wikistate %renderedfiles
25 %pagesources %destsources);
26 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
27 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
28 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
33 memoize("pagespec_translate");
34 memoize("file_pruned");
36 sub getsetup () { #{{{
40 description => "name of the wiki",
47 example => 'me@example.com',
48 description => "contact email for wiki",
55 description => "users who are wiki admins",
62 description => "users who are banned from the wiki",
69 example => "$ENV{HOME}/wiki",
70 description => "where the source of the wiki is located",
77 example => "/var/www/wiki",
78 description => "where to build the wiki",
85 example => "http://example.com/wiki",
86 description => "base url to the wiki",
93 example => "http://example.com/wiki/ikiwiki.cgi",
94 description => "url to the ikiwiki.cgi",
101 example => "/var/www/wiki/ikiwiki.cgi",
102 description => "cgi wrapper to generate",
109 description => "mode for cgi_wrapper (can safely be made suid)",
116 description => "rcs backend to use",
117 safe => 0, # don't allow overriding
122 default => [qw{mdwn link inline htmlscrubber passwordauth
123 openid signinedit lockedit conditional
124 recentchanges parentlinks editpage}],
125 description => "plugins to enable by default",
132 description => "plugins to add to the default configuration",
139 description => "plugins to disable",
145 default => "$installdir/share/ikiwiki/templates",
146 description => "location of template files",
153 default => "$installdir/share/ikiwiki/basewiki",
154 description => "base wiki source location",
162 description => "wrappers to generate",
169 description => "additional underlays to use",
176 description => "display verbose messages when building?",
183 description => "log to syslog?",
190 description => "create output files named page/index.html?",
191 safe => 0, # changing requires manual transition
194 prefix_directives => {
197 description => "use '!'-prefixed preprocessor directives?",
198 safe => 0, # changing requires manual transition
204 description => "use page/index.mdwn source files",
211 description => "enable Discussion pages?",
218 description => "only send cookies over SSL connections?",
226 description => "extension to use for new pages",
227 safe => 0, # not sanitized
233 description => "extension to use for html files",
234 safe => 0, # not sanitized
240 description => "strftime format string to display date",
248 example => "en_US.UTF-8",
249 description => "UTF-8 locale to use",
258 description => "put user pages below specified page",
265 description => "how many backlinks to show before hiding excess (0 to show all)",
272 description => "attempt to hardlink source files? (optimisation for large files)",
274 safe => 0, # paranoia
281 description => "force ikiwiki to use a particular umask",
283 safe => 0, # paranoia
289 example => "$ENV{HOME}/.ikiwiki/",
290 description => "extra library and plugin directory",
292 safe => 0, # directory
298 description => "environment variables",
299 safe => 0, # paranoia
306 description => "regexp of source files to ignore",
311 wiki_file_prune_regexps => {
313 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
314 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
315 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
318 description => "regexps of source files to ignore",
324 description => "specifies the characters that are allowed in source filenames",
325 default => "-[:alnum:]+/.:_",
329 wiki_file_regexp => {
331 description => "regexp of legal source files",
335 web_commit_regexp => {
337 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
338 description => "regexp to parse web commits from logs",
345 description => "run as a cgi",
349 cgi_disable_uploads => {
352 description => "whether CGI should accept file uploads",
359 description => "run as a post-commit hook",
366 description => "running in rebuild mode",
373 description => "running in setup mode",
380 description => "running in refresh mode",
387 description => "running in getctime mode",
394 description => "running in w3mmode",
401 description => "path to setup file",
405 allow_symlinks_before_srcdir => {
408 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
414 sub defaultconfig () { #{{{
417 foreach my $key (keys %s) {
418 push @ret, $key, $s{$key}->{default};
424 sub checkconfig () { #{{{
425 # locale stuff; avoid LC_ALL since it overrides everything
426 if (defined $ENV{LC_ALL}) {
427 $ENV{LANG} = $ENV{LC_ALL};
430 if (defined $config{locale}) {
431 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
432 $ENV{LANG}=$config{locale};
437 if (! defined $config{wiki_file_regexp}) {
438 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
441 if (ref $config{ENV} eq 'HASH') {
442 foreach my $val (keys %{$config{ENV}}) {
443 $ENV{$val}=$config{ENV}{$val};
447 if ($config{w3mmode}) {
448 eval q{use Cwd q{abs_path}};
450 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
451 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
452 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
453 unless $config{cgiurl} =~ m!file:///!;
454 $config{url}="file://".$config{destdir};
457 if ($config{cgi} && ! length $config{url}) {
458 error(gettext("Must specify url to wiki with --url when using --cgi"));
461 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
462 unless exists $config{wikistatedir};
464 if (defined $config{umask}) {
465 umask(possibly_foolish_untaint($config{umask}));
468 run_hooks(checkconfig => sub { shift->() });
473 sub listplugins () { #{{{
476 foreach my $dir (@INC, $config{libdir}) {
477 next unless defined $dir && length $dir;
478 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
479 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
483 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
484 next unless defined $dir && length $dir;
485 foreach my $file (glob("$dir/plugins/*")) {
486 $ret{basename($file)}=1 if -x $file;
493 sub loadplugins () { #{{{
494 if (defined $config{libdir} && length $config{libdir}) {
495 unshift @INC, possibly_foolish_untaint($config{libdir});
498 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
503 if (exists $IkiWiki::hooks{rcs}) {
504 error(gettext("cannot use multiple rcs plugins"));
506 loadplugin($config{rcs});
508 if (! exists $IkiWiki::hooks{rcs}) {
512 run_hooks(getopt => sub { shift->() });
513 if (grep /^-/, @ARGV) {
514 print STDERR "Unknown option: $_\n"
515 foreach grep /^-/, @ARGV;
522 sub loadplugin ($) { #{{{
525 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
527 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
528 "$installdir/lib/ikiwiki") {
529 if (defined $dir && -x "$dir/plugins/$plugin") {
530 eval { require IkiWiki::Plugin::external };
533 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
535 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
536 $loaded_plugins{$plugin}=1;
541 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
544 error("Failed to load plugin $mod: $@");
546 $loaded_plugins{$plugin}=1;
550 sub error ($;$) { #{{{
553 log_message('err' => $message) if $config{syslog};
554 if (defined $cleaner) {
561 return unless $config{verbose};
562 return log_message(debug => @_);
566 sub log_message ($$) { #{{{
569 if ($config{syslog}) {
572 Sys::Syslog::setlogsock('unix');
573 Sys::Syslog::openlog('ikiwiki', '', 'user');
577 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
580 elsif (! $config{cgi}) {
584 return print STDERR "@_\n";
588 sub possibly_foolish_untaint ($) { #{{{
590 my ($untainted)=$tainted=~/(.*)/s;
594 sub basename ($) { #{{{
601 sub dirname ($) { #{{{
608 sub pagetype ($) { #{{{
611 if ($page =~ /\.([^.]+)$/) {
612 return $1 if exists $hooks{htmlize}{$1};
617 sub isinternal ($) { #{{{
619 return exists $pagesources{$page} &&
620 $pagesources{$page} =~ /\._([^.]+)$/;
623 sub pagename ($) { #{{{
626 my $type=pagetype($file);
628 $page=~s/\Q.$type\E*$// if defined $type && !$hooks{htmlize}{$type}{keepextension};
629 if ($config{indexpages} && $page=~/(.*)\/index$/) {
635 sub targetpage ($$) { #{{{
639 if (! $config{usedirs} || $page =~ /^index$/ ) {
640 return $page.".".$ext;
642 return $page."/index.".$ext;
646 sub htmlpage ($) { #{{{
649 return targetpage($page, $config{htmlext});
652 sub srcfile_stat { #{{{
656 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
657 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
658 return "$dir/$file", stat(_) if -e "$dir/$file";
660 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
664 sub srcfile ($;$) { #{{{
665 return (srcfile_stat(@_))[0];
668 sub add_underlay ($) { #{{{
672 unshift @{$config{underlaydirs}}, $dir;
675 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
681 sub readfile ($;$$) { #{{{
687 error("cannot read a symlink ($file)");
691 open (my $in, "<", $file) || error("failed to read $file: $!");
692 binmode($in) if ($binary);
693 return \*$in if $wantfd;
695 close $in || error("failed to read $file: $!");
699 sub prep_writefile ($$) { #{{{
704 while (length $test) {
705 if (-l "$destdir/$test") {
706 error("cannot write to a symlink ($test)");
708 $test=dirname($test);
711 my $dir=dirname("$destdir/$file");
714 foreach my $s (split(m!/+!, $dir)) {
717 mkdir($d) || error("failed to create directory $d: $!");
725 sub writefile ($$$;$$) { #{{{
726 my $file=shift; # can include subdirs
727 my $destdir=shift; # directory to put file in
732 prep_writefile($file, $destdir);
734 my $newfile="$destdir/$file.ikiwiki-new";
736 error("cannot write to a symlink ($newfile)");
739 my $cleanup = sub { unlink($newfile) };
740 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
741 binmode($out) if ($binary);
743 $writer->(\*$out, $cleanup);
746 print $out $content or error("failed writing to $newfile: $!", $cleanup);
748 close $out || error("failed saving $newfile: $!", $cleanup);
749 rename($newfile, "$destdir/$file") ||
750 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
756 sub will_render ($$;$) { #{{{
761 # Important security check.
762 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
763 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
764 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
767 if (! $clear || $cleared{$page}) {
768 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
771 foreach my $old (@{$renderedfiles{$page}}) {
772 delete $destsources{$old};
774 $renderedfiles{$page}=[$dest];
777 $destsources{$dest}=$page;
782 sub bestlink ($$) { #{{{
787 if ($link=~s/^\/+//) {
795 $l.="/" if length $l;
798 if (exists $links{$l}) {
801 elsif (exists $pagecase{lc $l}) {
802 return $pagecase{lc $l};
804 } while $cwd=~s{/?[^/]+$}{};
806 if (length $config{userdir}) {
807 my $l = "$config{userdir}/".lc($link);
808 if (exists $links{$l}) {
811 elsif (exists $pagecase{lc $l}) {
812 return $pagecase{lc $l};
816 #print STDERR "warning: page $page, broken link: $link\n";
820 sub isinlinableimage ($) { #{{{
823 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
826 sub pagetitle ($;$) { #{{{
831 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
834 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
840 sub titlepage ($) { #{{{
842 # support use w/o %config set
843 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
844 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
848 sub linkpage ($) { #{{{
850 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
851 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
855 sub cgiurl (@) { #{{{
858 return $config{cgiurl}."?".
859 join("&", map $_."=".uri_escape_utf8($params{$_}), keys %params);
862 sub baseurl (;$) { #{{{
865 return "$config{url}/" if ! defined $page;
867 $page=htmlpage($page);
869 $page=~s/[^\/]+\//..\//g;
873 sub abs2rel ($$) { #{{{
874 # Work around very innefficient behavior in File::Spec if abs2rel
875 # is passed two relative paths. It's much faster if paths are
876 # absolute! (Debian bug #376658; fixed in debian unstable now)
881 my $ret=File::Spec->abs2rel($path, $base);
882 $ret=~s/^// if defined $ret;
886 sub displaytime ($;$) { #{{{
889 if (! defined $format) {
890 $format=$config{timeformat};
893 # strftime doesn't know about encodings, so make sure
894 # its output is properly treated as utf8
895 return decode_utf8(POSIX::strftime($format, localtime($time)));
898 sub beautify_urlpath ($) { #{{{
901 if ($config{usedirs}) {
902 $url =~ s!/index.$config{htmlext}$!/!;
905 # Ensure url is not an empty link, and
906 # if it's relative, make that explicit to avoid colon confusion.
914 sub urlto ($$;$) { #{{{
920 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
923 if (! $destsources{$to}) {
928 return $config{url}.beautify_urlpath("/".$to);
931 my $link = abs2rel($to, dirname(htmlpage($from)));
933 return beautify_urlpath($link);
936 sub htmllink ($$$;@) { #{{{
937 my $lpage=shift; # the page doing the linking
938 my $page=shift; # the page that will contain the link (different for inline)
945 if (! $opts{forcesubpage}) {
946 $bestlink=bestlink($lpage, $link);
949 $bestlink="$lpage/".lc($link);
953 if (defined $opts{linktext}) {
954 $linktext=$opts{linktext};
957 $linktext=pagetitle(basename($link));
960 return "<span class=\"selflink\">$linktext</span>"
961 if length $bestlink && $page eq $bestlink &&
962 ! defined $opts{anchor};
964 if (! $destsources{$bestlink}) {
965 $bestlink=htmlpage($bestlink);
967 if (! $destsources{$bestlink}) {
968 return $linktext unless length $config{cgiurl};
969 return "<span class=\"createlink\"><a href=\"".
975 "\" rel=\"nofollow\">?</a>$linktext</span>"
979 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
980 $bestlink=beautify_urlpath($bestlink);
982 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
983 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
986 if (defined $opts{anchor}) {
987 $bestlink.="#".$opts{anchor};
991 if (defined $opts{rel}) {
992 push @attrs, ' rel="'.$opts{rel}.'"';
994 if (defined $opts{class}) {
995 push @attrs, ' class="'.$opts{class}.'"';
998 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1001 sub userlink ($) { #{{{
1004 my $oiduser=eval { openiduser($user) };
1005 if (defined $oiduser) {
1006 return "<a href=\"$user\">$oiduser</a>";
1009 eval q{use CGI 'escapeHTML'};
1012 return htmllink("", "", escapeHTML(
1013 length $config{userdir} ? $config{userdir}."/".$user : $user
1014 ), noimageinline => 1);
1018 sub htmlize ($$$$) { #{{{
1024 my $oneline = $content !~ /\n/;
1026 if (exists $hooks{htmlize}{$type}) {
1027 $content=$hooks{htmlize}{$type}{call}->(
1029 content => $content,
1033 error("htmlization of $type not supported");
1036 run_hooks(sanitize => sub {
1039 destpage => $destpage,
1040 content => $content,
1045 # hack to get rid of enclosing junk added by markdown
1046 # and other htmlizers
1047 $content=~s/^<p>//i;
1048 $content=~s/<\/p>$//i;
1055 sub linkify ($$$) { #{{{
1060 run_hooks(linkify => sub {
1063 destpage => $destpage,
1064 content => $content,
1072 our $preprocess_preview=0;
1073 sub preprocess ($$$;$$) { #{{{
1074 my $page=shift; # the page the data comes from
1075 my $destpage=shift; # the page the data will appear in (different for inline)
1080 # Using local because it needs to be set within any nested calls
1082 local $preprocess_preview=$preview if defined $preview;
1089 $params="" if ! defined $params;
1091 if (length $escape) {
1092 return "[[$prefix$command $params]]";
1094 elsif (exists $hooks{preprocess}{$command}) {
1095 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1096 # Note: preserve order of params, some plugins may
1097 # consider it significant.
1099 while ($params =~ m{
1100 (?:([-\w]+)=)? # 1: named parameter key?
1102 """(.*?)""" # 2: triple-quoted value
1104 "([^"]+)" # 3: single-quoted value
1106 (\S+) # 4: unquoted value
1108 (?:\s+|$) # delimiter to next param
1118 elsif (defined $3) {
1121 elsif (defined $4) {
1126 push @params, $key, $val;
1129 push @params, $val, '';
1132 if ($preprocessing{$page}++ > 3) {
1133 # Avoid loops of preprocessed pages preprocessing
1134 # other pages that preprocess them, etc.
1135 return "[[!$command <span class=\"error\">".
1136 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1137 $page, $preprocessing{$page}).
1143 $hooks{preprocess}{$command}{call}->(
1146 destpage => $destpage,
1147 preview => $preprocess_preview,
1152 $ret="[[!$command <span class=\"error\">".
1153 gettext("Error").": $@"."</span>]]";
1157 # use void context during scan pass
1159 $hooks{preprocess}{$command}{call}->(
1162 destpage => $destpage,
1163 preview => $preprocess_preview,
1168 $preprocessing{$page}--;
1172 return "[[$prefix$command $params]]";
1177 if ($config{prefix_directives}) {
1180 \[\[(!) # directive open; 2: prefix
1181 ([-\w]+) # 3: command
1182 ( # 4: the parameters..
1183 \s+ # Must have space if parameters present
1185 (?:[-\w]+=)? # named parameter key?
1187 """.*?""" # triple-quoted value
1189 "[^"]+" # single-quoted value
1191 [^\s\]]+ # unquoted value
1193 \s* # whitespace or end
1196 *)? # 0 or more parameters
1197 \]\] # directive closed
1203 \[\[(!?) # directive open; 2: optional prefix
1204 ([-\w]+) # 3: command
1206 ( # 4: the parameters..
1208 (?:[-\w]+=)? # named parameter key?
1210 """.*?""" # triple-quoted value
1212 "[^"]+" # single-quoted value
1214 [^\s\]]+ # unquoted value
1216 \s* # whitespace or end
1219 *) # 0 or more parameters
1220 \]\] # directive closed
1224 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1228 sub filter ($$$) { #{{{
1233 run_hooks(filter => sub {
1234 $content=shift->(page => $page, destpage => $destpage,
1235 content => $content);
1241 sub indexlink () { #{{{
1242 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1247 sub lockwiki (;$) { #{{{
1248 my $wait=@_ ? shift : 1;
1249 # Take an exclusive lock on the wiki to prevent multiple concurrent
1250 # run issues. The lock will be dropped on program exit.
1251 if (! -d $config{wikistatedir}) {
1252 mkdir($config{wikistatedir});
1254 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1255 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1256 if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1258 debug("wiki seems to be locked, waiting for lock");
1259 my $wait=600; # arbitrary, but don't hang forever to
1260 # prevent process pileup
1262 return if flock($wikilock, 2 | 4);
1265 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1274 sub unlockwiki () { #{{{
1275 return close($wikilock) if $wikilock;
1281 sub commit_hook_enabled () { #{{{
1282 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1283 error("cannot write to $config{wikistatedir}/commitlock: $!");
1284 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1285 close($commitlock) || error("failed closing commitlock: $!");
1288 close($commitlock) || error("failed closing commitlock: $!");
1292 sub disable_commit_hook () { #{{{
1293 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1294 error("cannot write to $config{wikistatedir}/commitlock: $!");
1295 if (! flock($commitlock, 2)) { # LOCK_EX
1296 error("failed to get commit lock");
1301 sub enable_commit_hook () { #{{{
1302 return close($commitlock) if $commitlock;
1306 sub loadindex () { #{{{
1307 %oldrenderedfiles=%pagectime=();
1308 if (! $config{rebuild}) {
1309 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1310 %destsources=%renderedfiles=%pagecase=%pagestate=();
1313 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1314 if (-e "$config{wikistatedir}/index") {
1315 system("ikiwiki-transition", "indexdb", $config{srcdir});
1316 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1323 my $index=Storable::fd_retrieve($in);
1324 if (! defined $index) {
1329 if (exists $index->{version} && ! ref $index->{version}) {
1330 $pages=$index->{page};
1331 %wikistate=%{$index->{state}};
1338 foreach my $src (keys %$pages) {
1339 my $d=$pages->{$src};
1340 my $page=pagename($src);
1341 $pagectime{$page}=$d->{ctime};
1342 if (! $config{rebuild}) {
1343 $pagesources{$page}=$src;
1344 $pagemtime{$page}=$d->{mtime};
1345 $renderedfiles{$page}=$d->{dest};
1346 if (exists $d->{links} && ref $d->{links}) {
1347 $links{$page}=$d->{links};
1348 $oldlinks{$page}=[@{$d->{links}}];
1350 if (exists $d->{depends}) {
1351 $depends{$page}=$d->{depends};
1353 if (exists $d->{state}) {
1354 $pagestate{$page}=$d->{state};
1357 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1359 foreach my $page (keys %pagesources) {
1360 $pagecase{lc $page}=$page;
1362 foreach my $page (keys %renderedfiles) {
1363 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1368 sub saveindex () { #{{{
1369 run_hooks(savestate => sub { shift->() });
1372 foreach my $type (keys %hooks) {
1373 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1375 my @hookids=keys %hookids;
1377 if (! -d $config{wikistatedir}) {
1378 mkdir($config{wikistatedir});
1380 my $newfile="$config{wikistatedir}/indexdb.new";
1381 my $cleanup = sub { unlink($newfile) };
1382 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1385 foreach my $page (keys %pagemtime) {
1386 next unless $pagemtime{$page};
1387 my $src=$pagesources{$page};
1389 $index{page}{$src}={
1390 ctime => $pagectime{$page},
1391 mtime => $pagemtime{$page},
1392 dest => $renderedfiles{$page},
1393 links => $links{$page},
1396 if (exists $depends{$page}) {
1397 $index{page}{$src}{depends} = $depends{$page};
1400 if (exists $pagestate{$page}) {
1401 foreach my $id (@hookids) {
1402 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1403 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1410 foreach my $id (@hookids) {
1411 foreach my $key (keys %{$wikistate{$id}}) {
1412 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1416 $index{version}="3";
1417 my $ret=Storable::nstore_fd(\%index, $out);
1418 return if ! defined $ret || ! $ret;
1419 close $out || error("failed saving to $newfile: $!", $cleanup);
1420 rename($newfile, "$config{wikistatedir}/indexdb") ||
1421 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1426 sub template_file ($) { #{{{
1429 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1430 return "$dir/$template" if -e "$dir/$template";
1435 sub template_params (@) { #{{{
1436 my $filename=template_file(shift);
1438 if (! defined $filename) {
1439 return if wantarray;
1445 my $text_ref = shift;
1446 ${$text_ref} = decode_utf8(${$text_ref});
1448 filename => $filename,
1449 loop_context_vars => 1,
1450 die_on_bad_params => 0,
1453 return wantarray ? @ret : {@ret};
1456 sub template ($;@) { #{{{
1457 require HTML::Template;
1458 return HTML::Template->new(template_params(@_));
1461 sub misctemplate ($$;@) { #{{{
1465 my $template=template("misc.tmpl");
1468 indexlink => indexlink(),
1469 wikiname => $config{wikiname},
1470 pagebody => $pagebody,
1471 baseurl => baseurl(),
1474 run_hooks(pagetemplate => sub {
1475 shift->(page => "", destpage => "", template => $template);
1477 return $template->output;
1480 sub hook (@) { # {{{
1483 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1484 error 'hook requires type, call, and id parameters';
1487 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1489 $hooks{$param{type}}{$param{id}}=\%param;
1493 sub run_hooks ($$) { # {{{
1494 # Calls the given sub for each hook of the given type,
1495 # passing it the hook function to call.
1499 if (exists $hooks{$type}) {
1501 foreach my $id (keys %{$hooks{$type}}) {
1502 if ($hooks{$type}{$id}{last}) {
1503 push @deferred, $id;
1506 $sub->($hooks{$type}{$id}{call});
1508 foreach my $id (@deferred) {
1509 $sub->($hooks{$type}{$id}{call});
1516 sub rcs_update () { #{{{
1517 $hooks{rcs}{rcs_update}{call}->(@_);
1520 sub rcs_prepedit ($) { #{{{
1521 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1524 sub rcs_commit ($$$;$$) { #{{{
1525 $hooks{rcs}{rcs_commit}{call}->(@_);
1528 sub rcs_commit_staged ($$$) { #{{{
1529 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1532 sub rcs_add ($) { #{{{
1533 $hooks{rcs}{rcs_add}{call}->(@_);
1536 sub rcs_remove ($) { #{{{
1537 $hooks{rcs}{rcs_remove}{call}->(@_);
1540 sub rcs_rename ($$) { #{{{
1541 $hooks{rcs}{rcs_rename}{call}->(@_);
1544 sub rcs_recentchanges ($) { #{{{
1545 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1548 sub rcs_diff ($) { #{{{
1549 $hooks{rcs}{rcs_diff}{call}->(@_);
1552 sub rcs_getctime ($) { #{{{
1553 $hooks{rcs}{rcs_getctime}{call}->(@_);
1556 sub globlist_to_pagespec ($) { #{{{
1557 my @globlist=split(' ', shift);
1560 foreach my $glob (@globlist) {
1561 if ($glob=~/^!(.*)/) {
1569 my $spec=join(' or ', @spec);
1571 my $skip=join(' and ', @skip);
1573 $spec="$skip and ($spec)";
1582 sub is_globlist ($) { #{{{
1584 return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1587 sub safequote ($) { #{{{
1593 sub add_depends ($$) { #{{{
1597 return unless pagespec_valid($pagespec);
1599 if (! exists $depends{$page}) {
1600 $depends{$page}=$pagespec;
1603 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1609 sub file_pruned ($$) { #{{{
1611 my $file=File::Spec->canonpath(shift);
1612 my $base=File::Spec->canonpath(shift);
1613 $file =~ s#^\Q$base\E/+##;
1615 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1616 return $file =~ m/$regexp/ && $file ne $base;
1620 # Only use gettext in the rare cases it's needed.
1621 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1622 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1623 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1624 if (! $gettext_obj) {
1625 $gettext_obj=eval q{
1626 use Locale::gettext q{textdomain};
1627 Locale::gettext->domain('ikiwiki')
1635 return $gettext_obj->get(shift);
1642 sub yesno ($) { #{{{
1645 return (defined $val && lc($val) eq gettext("yes"));
1648 sub pagespec_merge ($$) { #{{{
1652 return $a if $a eq $b;
1654 # Support for old-style GlobLists.
1655 if (is_globlist($a)) {
1656 $a=globlist_to_pagespec($a);
1658 if (is_globlist($b)) {
1659 $b=globlist_to_pagespec($b);
1662 return "($a) or ($b)";
1665 sub pagespec_translate ($) { #{{{
1668 # Support for old-style GlobLists.
1669 if (is_globlist($spec)) {
1670 $spec=globlist_to_pagespec($spec);
1673 # Convert spec to perl code.
1676 \s* # ignore whitespace
1677 ( # 1: match a single word
1684 \w+\([^\)]*\) # command(params)
1686 [^\s()]+ # any other text
1688 \s* # ignore whitespace
1691 if (lc $word eq 'and') {
1694 elsif (lc $word eq 'or') {
1697 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1700 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1701 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1702 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1709 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1713 if (! length $code) {
1718 return eval 'sub { my $page=shift; '.$code.' }';
1721 sub pagespec_match ($$;@) { #{{{
1726 # Backwards compatability with old calling convention.
1728 unshift @params, 'location';
1731 my $sub=pagespec_translate($spec);
1732 return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1733 return $sub->($page, @params);
1736 sub pagespec_valid ($) { #{{{
1739 my $sub=pagespec_translate($spec);
1743 sub glob2re ($) { #{{{
1744 my $re=quotemeta(shift);
1750 package IkiWiki::FailReason;
1753 '""' => sub { ${$_[0]} },
1755 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1762 return bless \$value, $class;
1765 package IkiWiki::SuccessReason;
1768 '""' => sub { ${$_[0]} },
1770 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1777 return bless \$value, $class;
1780 package IkiWiki::PageSpec;
1782 sub match_glob ($$;@) { #{{{
1787 my $from=exists $params{location} ? $params{location} : '';
1790 if ($glob =~ m!^\./!) {
1791 $from=~s#/?[^/]+$##;
1793 $glob="$from/$glob" if length $from;
1796 my $regexp=IkiWiki::glob2re($glob);
1797 if ($page=~/^$regexp$/i) {
1798 if (! IkiWiki::isinternal($page) || $params{internal}) {
1799 return IkiWiki::SuccessReason->new("$glob matches $page");
1802 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1806 return IkiWiki::FailReason->new("$glob does not match $page");
1810 sub match_internal ($$;@) { #{{{
1811 return match_glob($_[0], $_[1], @_, internal => 1)
1814 sub match_link ($$;@) { #{{{
1819 my $from=exists $params{location} ? $params{location} : '';
1822 if ($link =~ m!^\.! && defined $from) {
1823 $from=~s#/?[^/]+$##;
1825 $link="$from/$link" if length $from;
1828 my $links = $IkiWiki::links{$page};
1829 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1830 my $bestlink = IkiWiki::bestlink($from, $link);
1831 foreach my $p (@{$links}) {
1832 if (length $bestlink) {
1833 return IkiWiki::SuccessReason->new("$page links to $link")
1834 if $bestlink eq IkiWiki::bestlink($page, $p);
1837 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1838 if match_glob($p, $link, %params);
1841 return IkiWiki::FailReason->new("$page does not link to $link");
1844 sub match_backlink ($$;@) { #{{{
1845 return match_link($_[1], $_[0], @_);
1848 sub match_created_before ($$;@) { #{{{
1852 if (exists $IkiWiki::pagectime{$testpage}) {
1853 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1854 return IkiWiki::SuccessReason->new("$page created before $testpage");
1857 return IkiWiki::FailReason->new("$page not created before $testpage");
1861 return IkiWiki::FailReason->new("$testpage has no ctime");
1865 sub match_created_after ($$;@) { #{{{
1869 if (exists $IkiWiki::pagectime{$testpage}) {
1870 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1871 return IkiWiki::SuccessReason->new("$page created after $testpage");
1874 return IkiWiki::FailReason->new("$page not created after $testpage");
1878 return IkiWiki::FailReason->new("$testpage has no ctime");
1882 sub match_creation_day ($$;@) { #{{{
1883 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1884 return IkiWiki::SuccessReason->new('creation_day matched');
1887 return IkiWiki::FailReason->new('creation_day did not match');
1891 sub match_creation_month ($$;@) { #{{{
1892 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1893 return IkiWiki::SuccessReason->new('creation_month matched');
1896 return IkiWiki::FailReason->new('creation_month did not match');
1900 sub match_creation_year ($$;@) { #{{{
1901 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1902 return IkiWiki::SuccessReason->new('creation_year matched');
1905 return IkiWiki::FailReason->new('creation_year did not match');