* Fix a bug that caused link(foo) to succeed if page foo did not exist.
[ikiwiki] / IkiWiki.pm
1 #!/usr/bin/perl
2
3 package IkiWiki;
4 use warnings;
5 use strict;
6 use Encode;
7 use HTML::Entities;
8 use URI::Escape q{uri_escape_utf8};
9 use open qw{:utf8 :std};
10
11 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
12             %renderedfiles %oldrenderedfiles %pagesources %depends %hooks
13             %forcerebuild $gettext_obj};
14
15 use Exporter q{import};
16 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
17                  bestlink htmllink readfile writefile pagetype srcfile pagename
18                  displaytime will_render gettext urlto targetpage
19                  %config %links %renderedfiles %pagesources);
20 our $VERSION = 1.02; # plugin interface version, next is ikiwiki version
21 our $version="1.45";my $installdir="/usr";
22 # Optimisation.
23 use Memoize;
24 memoize("abs2rel");
25 memoize("pagespec_translate");
26 memoize("file_pruned");
27
28 sub defaultconfig () { #{{{
29         wiki_file_prune_regexps => [qr/\.\./, qr/^\./, qr/\/\./,
30                 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
31                 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//],
32         wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]#]+)(?:#([^\s\]]+))?\]\]/,
33         wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
34         web_commit_regexp => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
35         verbose => 0,
36         syslog => 0,
37         wikiname => "wiki",
38         default_pageext => "mdwn",
39         cgi => 0,
40         post_commit => 0,
41         rcs => '',
42         notify => 0,
43         url => '',
44         cgiurl => '',
45         historyurl => '',
46         diffurl => '',
47         rss => 0,
48         atom => 0,
49         discussion => 1,
50         rebuild => 0,
51         refresh => 0,
52         getctime => 0,
53         w3mmode => 0,
54         wrapper => undef,
55         wrappermode => undef,
56         svnrepo => undef,
57         svnpath => "trunk",
58         gitorigin_branch => "origin",
59         gitmaster_branch => "master",
60         srcdir => undef,
61         destdir => undef,
62         pingurl => [],
63         templatedir => "$installdir/share/ikiwiki/templates",
64         underlaydir => "$installdir/share/ikiwiki/basewiki",
65         setup => undef,
66         adminuser => undef,
67         adminemail => undef,
68         plugin => [qw{mdwn inline htmlscrubber passwordauth signinedit
69                       lockedit conditional}],
70         timeformat => '%c',
71         locale => undef,
72         sslcookie => 0,
73         httpauth => 0,
74         userdir => "",
75         usedirs => 0,
76         numbacklinks => 10,
77 } #}}}
78    
79 sub checkconfig () { #{{{
80         # locale stuff; avoid LC_ALL since it overrides everything
81         if (defined $ENV{LC_ALL}) {
82                 $ENV{LANG} = $ENV{LC_ALL};
83                 delete $ENV{LC_ALL};
84         }
85         if (defined $config{locale}) {
86                 eval q{use POSIX};
87                 error($@) if $@;
88                 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
89                         $ENV{LANG}=$config{locale};
90                         $gettext_obj=undef;
91                 }
92         }
93
94         if ($config{w3mmode}) {
95                 eval q{use Cwd q{abs_path}};
96                 error($@) if $@;
97                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
98                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
99                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
100                         unless $config{cgiurl} =~ m!file:///!;
101                 $config{url}="file://".$config{destdir};
102         }
103
104         if ($config{cgi} && ! length $config{url}) {
105                 error(gettext("Must specify url to wiki with --url when using --cgi"));
106         }
107         
108         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
109                 unless exists $config{wikistatedir};
110         
111         if ($config{rcs}) {
112                 eval qq{require IkiWiki::Rcs::$config{rcs}};
113                 if ($@) {
114                         error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
115                 }
116         }
117         else {
118                 require IkiWiki::Rcs::Stub;
119         }
120
121         run_hooks(checkconfig => sub { shift->() });
122 } #}}}
123
124 sub loadplugins () { #{{{
125         loadplugin($_) foreach @{$config{plugin}};
126         
127         run_hooks(getopt => sub { shift->() });
128         if (grep /^-/, @ARGV) {
129                 print STDERR "Unknown option: $_\n"
130                         foreach grep /^-/, @ARGV;
131                 usage();
132         }
133 } #}}}
134
135 sub loadplugin ($) { #{{{
136         my $plugin=shift;
137
138         return if grep { $_ eq $plugin} @{$config{disable_plugins}};
139
140         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
141         eval qq{use $mod};
142         if ($@) {
143                 error("Failed to load plugin $mod: $@");
144         }
145 } #}}}
146
147 sub error ($;$) { #{{{
148         my $message=shift;
149         my $cleaner=shift;
150         if ($config{cgi}) {
151                 print "Content-type: text/html\n\n";
152                 print misctemplate(gettext("Error"),
153                         "<p>".gettext("Error").": $message</p>");
154         }
155         log_message(debug => $message) if $config{syslog};
156         if (defined $cleaner) {
157                 $cleaner->();
158         }
159         die $message."\n";
160 } #}}}
161
162 sub debug ($) { #{{{
163         return unless $config{verbose};
164         log_message(debug => @_);
165 } #}}}
166
167 my $log_open=0;
168 sub log_message ($$) { #{{{
169         my $type=shift;
170
171         if ($config{syslog}) {
172                 require Sys::Syslog;
173                 unless ($log_open) {
174                         Sys::Syslog::setlogsock('unix');
175                         Sys::Syslog::openlog('ikiwiki', '', 'user');
176                         $log_open=1;
177                 }
178                 eval {
179                         Sys::Syslog::syslog($type, "%s", join(" ", @_));
180                 }
181         }
182         elsif (! $config{cgi}) {
183                 print "@_\n";
184         }
185         else {
186                 print STDERR "@_\n";
187         }
188 } #}}}
189
190 sub possibly_foolish_untaint ($) { #{{{
191         my $tainted=shift;
192         my ($untainted)=$tainted=~/(.*)/;
193         return $untainted;
194 } #}}}
195
196 sub basename ($) { #{{{
197         my $file=shift;
198
199         $file=~s!.*/+!!;
200         return $file;
201 } #}}}
202
203 sub dirname ($) { #{{{
204         my $file=shift;
205
206         $file=~s!/*[^/]+$!!;
207         return $file;
208 } #}}}
209
210 sub pagetype ($) { #{{{
211         my $page=shift;
212         
213         if ($page =~ /\.([^.]+)$/) {
214                 return $1 if exists $hooks{htmlize}{$1};
215         }
216         return undef;
217 } #}}}
218
219 sub pagename ($) { #{{{
220         my $file=shift;
221
222         my $type=pagetype($file);
223         my $page=$file;
224         $page=~s/\Q.$type\E*$// if defined $type;
225         return $page;
226 } #}}}
227
228 sub targetpage ($$) { #{{{
229         my $page=shift;
230         my $ext=shift;
231         
232         if (! $config{usedirs} || $page =~ /^index$/ ) {
233                 return $page.".".$ext;
234         } else {
235                 return $page."/index.".$ext;
236         }
237 } #}}}
238
239 sub htmlpage ($) { #{{{
240         my $page=shift;
241         
242         return targetpage($page, "html");
243 } #}}}
244
245 sub srcfile ($) { #{{{
246         my $file=shift;
247
248         return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
249         return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
250         error("internal error: $file cannot be found");
251 } #}}}
252
253 sub readfile ($;$$) { #{{{
254         my $file=shift;
255         my $binary=shift;
256         my $wantfd=shift;
257
258         if (-l $file) {
259                 error("cannot read a symlink ($file)");
260         }
261         
262         local $/=undef;
263         open (IN, $file) || error("failed to read $file: $!");
264         binmode(IN) if ($binary);
265         return \*IN if $wantfd;
266         my $ret=<IN>;
267         close IN || error("failed to read $file: $!");
268         return $ret;
269 } #}}}
270
271 sub writefile ($$$;$$) { #{{{
272         my $file=shift; # can include subdirs
273         my $destdir=shift; # directory to put file in
274         my $content=shift;
275         my $binary=shift;
276         my $writer=shift;
277         
278         my $test=$file;
279         while (length $test) {
280                 if (-l "$destdir/$test") {
281                         error("cannot write to a symlink ($test)");
282                 }
283                 $test=dirname($test);
284         }
285         my $newfile="$destdir/$file.ikiwiki-new";
286         if (-l $newfile) {
287                 error("cannot write to a symlink ($newfile)");
288         }
289
290         my $dir=dirname($newfile);
291         if (! -d $dir) {
292                 my $d="";
293                 foreach my $s (split(m!/+!, $dir)) {
294                         $d.="$s/";
295                         if (! -d $d) {
296                                 mkdir($d) || error("failed to create directory $d: $!");
297                         }
298                 }
299         }
300
301         my $cleanup = sub { unlink($newfile) };
302         open (OUT, ">$newfile") || error("failed to write $newfile: $!", $cleanup);
303         binmode(OUT) if ($binary);
304         if ($writer) {
305                 $writer->(\*OUT, $cleanup);
306         }
307         else {
308                 print OUT $content or error("failed writing to $newfile: $!", $cleanup);
309         }
310         close OUT || error("failed saving $newfile: $!", $cleanup);
311         rename($newfile, "$destdir/$file") || 
312                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
313 } #}}}
314
315 my %cleared;
316 sub will_render ($$;$) { #{{{
317         my $page=shift;
318         my $dest=shift;
319         my $clear=shift;
320
321         # Important security check.
322         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
323             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
324                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
325         }
326
327         if (! $clear || $cleared{$page}) {
328                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
329         }
330         else {
331                 $renderedfiles{$page}=[$dest];
332                 $cleared{$page}=1;
333         }
334 } #}}}
335
336 sub bestlink ($$) { #{{{
337         my $page=shift;
338         my $link=shift;
339         
340         my $cwd=$page;
341         if ($link=~s/^\/+//) {
342                 # absolute links
343                 $cwd="";
344         }
345
346         do {
347                 my $l=$cwd;
348                 $l.="/" if length $l;
349                 $l.=$link;
350
351                 if (exists $links{$l}) {
352                         return $l;
353                 }
354                 elsif (exists $pagecase{lc $l}) {
355                         return $pagecase{lc $l};
356                 }
357         } while $cwd=~s!/?[^/]+$!!;
358
359         if (length $config{userdir} && exists $links{"$config{userdir}/".lc($link)}) {
360                 return "$config{userdir}/".lc($link);
361         }
362
363         #print STDERR "warning: page $page, broken link: $link\n";
364         return "";
365 } #}}}
366
367 sub isinlinableimage ($) { #{{{
368         my $file=shift;
369         
370         $file=~/\.(png|gif|jpg|jpeg)$/i;
371 } #}}}
372
373 sub pagetitle ($;$) { #{{{
374         my $page=shift;
375         my $unescaped=shift;
376
377         if ($unescaped) {
378                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
379         }
380         else {
381                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
382         }
383
384         return $page;
385 } #}}}
386
387 sub titlepage ($) { #{{{
388         my $title=shift;
389         $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
390         return $title;
391 } #}}}
392
393 sub linkpage ($) { #{{{
394         my $link=shift;
395         $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
396         return $link;
397 } #}}}
398
399 sub cgiurl (@) { #{{{
400         my %params=@_;
401
402         return $config{cgiurl}."?".
403                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
404 } #}}}
405
406 sub baseurl (;$) { #{{{
407         my $page=shift;
408
409         return "$config{url}/" if ! defined $page;
410         
411         $page=htmlpage($page);
412         $page=~s/[^\/]+$//;
413         $page=~s/[^\/]+\//..\//g;
414         return $page;
415 } #}}}
416
417 sub abs2rel ($$) { #{{{
418         # Work around very innefficient behavior in File::Spec if abs2rel
419         # is passed two relative paths. It's much faster if paths are
420         # absolute! (Debian bug #376658; fixed in debian unstable now)
421         my $path="/".shift;
422         my $base="/".shift;
423
424         require File::Spec;
425         my $ret=File::Spec->abs2rel($path, $base);
426         $ret=~s/^// if defined $ret;
427         return $ret;
428 } #}}}
429
430 sub displaytime ($) { #{{{
431         my $time=shift;
432
433         eval q{use POSIX};
434         error($@) if $@;
435         # strftime doesn't know about encodings, so make sure
436         # its output is properly treated as utf8
437         return decode_utf8(POSIX::strftime(
438                         $config{timeformat}, localtime($time)));
439 } #}}}
440
441 sub beautify_url ($) { #{{{
442         my $url=shift;
443
444         $url =~ s!/index.html$!/!;
445         $url =~ s!^$!./!; # Browsers don't like empty links...
446
447         return $url;
448 } #}}}
449
450 sub urlto ($$) { #{{{
451         my $to=shift;
452         my $from=shift;
453
454         if (! length $to) {
455                 return beautify_url(baseurl($from));
456         }
457
458         if (! grep { $_ eq $to } map { @{$_} } values %renderedfiles) {
459                 $to=htmlpage($to);
460         }
461
462         my $link = abs2rel($to, dirname(htmlpage($from)));
463
464         return beautify_url($link);
465 } #}}}
466
467 sub htmllink ($$$;@) { #{{{
468         my $lpage=shift; # the page doing the linking
469         my $page=shift; # the page that will contain the link (different for inline)
470         my $link=shift;
471         my %opts=@_;
472
473         my $bestlink;
474         if (! $opts{forcesubpage}) {
475                 $bestlink=bestlink($lpage, $link);
476         }
477         else {
478                 $bestlink="$lpage/".lc($link);
479         }
480
481         my $linktext;
482         if (defined $opts{linktext}) {
483                 $linktext=$opts{linktext};
484         }
485         else {
486                 $linktext=pagetitle(basename($link));
487         }
488         
489         return "<span class=\"selflink\">$linktext</span>"
490                 if length $bestlink && $page eq $bestlink;
491         
492         if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
493                 $bestlink=htmlpage($bestlink);
494         }
495         if (! grep { $_ eq $bestlink } map { @{$_} } values %renderedfiles) {
496                 return $linktext unless length $config{cgiurl};
497                 return "<span><a href=\"".
498                         cgiurl(
499                                 do => "create",
500                                 page => pagetitle(lc($link), 1),
501                                 from => $lpage
502                         ).
503                         "\">?</a>$linktext</span>"
504         }
505         
506         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
507         $bestlink=beautify_url($bestlink);
508         
509         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
510                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
511         }
512
513         if (defined $opts{anchor}) {
514                 $bestlink.="#".$opts{anchor};
515         }
516
517         return "<a href=\"$bestlink\">$linktext</a>";
518 } #}}}
519
520 sub htmlize ($$$) { #{{{
521         my $page=shift;
522         my $type=shift;
523         my $content=shift;
524
525         if (exists $hooks{htmlize}{$type}) {
526                 $content=$hooks{htmlize}{$type}{call}->(
527                         page => $page,
528                         content => $content,
529                 );
530         }
531         else {
532                 error("htmlization of $type not supported");
533         }
534
535         run_hooks(sanitize => sub {
536                 $content=shift->(
537                         page => $page,
538                         content => $content,
539                 );
540         });
541
542         return $content;
543 } #}}}
544
545 sub linkify ($$$) { #{{{
546         my $lpage=shift; # the page containing the links
547         my $page=shift; # the page the link will end up on (different for inline)
548         my $content=shift;
549
550         $content =~ s{(\\?)$config{wiki_link_regexp}}{
551                 defined $2
552                         ? ( $1 ? "[[$2|$3]]" : htmllink($lpage, $page, linkpage($3), anchor => $4, linktext => pagetitle($2)))
553                         : ( $1 ? "[[$3]]"    : htmllink($lpage, $page, linkpage($3), anchor => $4))
554         }eg;
555         
556         return $content;
557 } #}}}
558
559 my %preprocessing;
560 our $preprocess_preview=0;
561 sub preprocess ($$$;$$) { #{{{
562         my $page=shift; # the page the data comes from
563         my $destpage=shift; # the page the data will appear in (different for inline)
564         my $content=shift;
565         my $scan=shift;
566         my $preview=shift;
567
568         # Using local because it needs to be set within any nested calls
569         # of this function.
570         local $preprocess_preview=$preview if defined $preview;
571
572         my $handle=sub {
573                 my $escape=shift;
574                 my $command=shift;
575                 my $params=shift;
576                 if (length $escape) {
577                         return "[[$command $params]]";
578                 }
579                 elsif (exists $hooks{preprocess}{$command}) {
580                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
581                         # Note: preserve order of params, some plugins may
582                         # consider it significant.
583                         my @params;
584                         while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
585                                 my $key=$1;
586                                 my $val;
587                                 if (defined $2) {
588                                         $val=$2;
589                                         $val=~s/\r\n/\n/mg;
590                                         $val=~s/^\n+//g;
591                                         $val=~s/\n+$//g;
592                                 }
593                                 elsif (defined $3) {
594                                         $val=$3;
595                                 }
596                                 elsif (defined $4) {
597                                         $val=$4;
598                                 }
599
600                                 if (defined $key) {
601                                         push @params, $key, $val;
602                                 }
603                                 else {
604                                         push @params, $val, '';
605                                 }
606                         }
607                         if ($preprocessing{$page}++ > 3) {
608                                 # Avoid loops of preprocessed pages preprocessing
609                                 # other pages that preprocess them, etc.
610                                 #translators: The first parameter is a
611                                 #translators: preprocessor directive name,
612                                 #translators: the second a page name, the
613                                 #translators: third a number.
614                                 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
615                                         $command, $page, $preprocessing{$page}).
616                                 "]]";
617                         }
618                         my $ret=$hooks{preprocess}{$command}{call}->(
619                                 @params,
620                                 page => $page,
621                                 destpage => $destpage,
622                                 preview => $preprocess_preview,
623                         );
624                         $preprocessing{$page}--;
625                         return $ret;
626                 }
627                 else {
628                         return "[[$command $params]]";
629                 }
630         };
631         
632         $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
633         return $content;
634 } #}}}
635
636 sub filter ($$) { #{{{
637         my $page=shift;
638         my $content=shift;
639
640         run_hooks(filter => sub {
641                 $content=shift->(page => $page, content => $content);
642         });
643
644         return $content;
645 } #}}}
646
647 sub indexlink () { #{{{
648         return "<a href=\"$config{url}\">$config{wikiname}</a>";
649 } #}}}
650
651 sub lockwiki () { #{{{
652         # Take an exclusive lock on the wiki to prevent multiple concurrent
653         # run issues. The lock will be dropped on program exit.
654         if (! -d $config{wikistatedir}) {
655                 mkdir($config{wikistatedir});
656         }
657         open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
658                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
659         if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
660                 debug("wiki seems to be locked, waiting for lock");
661                 my $wait=600; # arbitrary, but don't hang forever to 
662                               # prevent process pileup
663                 for (1..$wait) {
664                         return if flock(WIKILOCK, 2 | 4);
665                         sleep 1;
666                 }
667                 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
668         }
669 } #}}}
670
671 sub unlockwiki () { #{{{
672         close WIKILOCK;
673 } #}}}
674
675 sub commit_hook_enabled () { #{{{
676         open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
677                 error ("cannot write to $config{wikistatedir}/commitlock: $!");
678         if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
679                 close COMMITLOCK;
680                 return 0;
681         }
682         close COMMITLOCK;
683         return 1;
684 } #}}}
685
686 sub disable_commit_hook () { #{{{
687         open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
688                 error ("cannot write to $config{wikistatedir}/commitlock: $!");
689         if (! flock(COMMITLOCK, 2)) { # LOCK_EX
690                 error("failed to get commit lock");
691         }
692 } #}}}
693
694 sub enable_commit_hook () { #{{{
695         close COMMITLOCK;
696 } #}}}
697
698 sub loadindex () { #{{{
699         open (IN, "$config{wikistatedir}/index") || return;
700         while (<IN>) {
701                 $_=possibly_foolish_untaint($_);
702                 chomp;
703                 my %items;
704                 $items{link}=[];
705                 $items{dest}=[];
706                 foreach my $i (split(/ /, $_)) {
707                         my ($item, $val)=split(/=/, $i, 2);
708                         push @{$items{$item}}, decode_entities($val);
709                 }
710
711                 next unless exists $items{src}; # skip bad lines for now
712
713                 my $page=pagename($items{src}[0]);
714                 if (! $config{rebuild}) {
715                         $pagesources{$page}=$items{src}[0];
716                         $pagemtime{$page}=$items{mtime}[0];
717                         $oldlinks{$page}=[@{$items{link}}];
718                         $links{$page}=[@{$items{link}}];
719                         $depends{$page}=$items{depends}[0] if exists $items{depends};
720                         $renderedfiles{$page}=[@{$items{dest}}];
721                         $oldrenderedfiles{$page}=[@{$items{dest}}];
722                         $pagecase{lc $page}=$page;
723                 }
724                 $pagectime{$page}=$items{ctime}[0];
725         }
726         close IN;
727 } #}}}
728
729 sub saveindex () { #{{{
730         run_hooks(savestate => sub { shift->() });
731
732         if (! -d $config{wikistatedir}) {
733                 mkdir($config{wikistatedir});
734         }
735         my $newfile="$config{wikistatedir}/index.new";
736         my $cleanup = sub { unlink($newfile) };
737         open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
738         foreach my $page (keys %pagemtime) {
739                 next unless $pagemtime{$page};
740                 my $line="mtime=$pagemtime{$page} ".
741                         "ctime=$pagectime{$page} ".
742                         "src=$pagesources{$page}";
743                 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
744                 my %count;
745                 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
746                 if (exists $depends{$page}) {
747                         $line.=" depends=".encode_entities($depends{$page}, " \t\n");
748                 }
749                 print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
750         }
751         close OUT || error("failed saving to $newfile: $!", $cleanup);
752         rename($newfile, "$config{wikistatedir}/index") ||
753                 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
754 } #}}}
755
756 sub template_file ($) { #{{{
757         my $template=shift;
758
759         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
760                 return "$dir/$template" if -e "$dir/$template";
761         }
762         return undef;
763 } #}}}
764
765 sub template_params (@) { #{{{
766         my $filename=template_file(shift);
767
768         if (! defined $filename) {
769                 return if wantarray;
770                 return "";
771         }
772
773         require HTML::Template;
774         my @ret=(
775                 filter => sub {
776                         my $text_ref = shift;
777                         $$text_ref=&Encode::decode_utf8($$text_ref);
778                 },
779                 filename => $filename,
780                 loop_context_vars => 1,
781                 die_on_bad_params => 0,
782                 @_
783         );
784         return wantarray ? @ret : {@ret};
785 } #}}}
786
787 sub template ($;@) { #{{{
788         HTML::Template->new(template_params(@_));
789 } #}}}
790
791 sub misctemplate ($$;@) { #{{{
792         my $title=shift;
793         my $pagebody=shift;
794         
795         my $template=template("misc.tmpl");
796         $template->param(
797                 title => $title,
798                 indexlink => indexlink(),
799                 wikiname => $config{wikiname},
800                 pagebody => $pagebody,
801                 baseurl => baseurl(),
802                 @_,
803         );
804         run_hooks(pagetemplate => sub {
805                 shift->(page => "", destpage => "", template => $template);
806         });
807         return $template->output;
808 }#}}}
809
810 sub hook (@) { # {{{
811         my %param=@_;
812         
813         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
814                 error "hook requires type, call, and id parameters";
815         }
816
817         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
818         
819         $hooks{$param{type}}{$param{id}}=\%param;
820 } # }}}
821
822 sub run_hooks ($$) { # {{{
823         # Calls the given sub for each hook of the given type,
824         # passing it the hook function to call.
825         my $type=shift;
826         my $sub=shift;
827
828         if (exists $hooks{$type}) {
829                 my @deferred;
830                 foreach my $id (keys %{$hooks{$type}}) {
831                         if ($hooks{$type}{$id}{last}) {
832                                 push @deferred, $id;
833                                 next;
834                         }
835                         $sub->($hooks{$type}{$id}{call});
836                 }
837                 foreach my $id (@deferred) {
838                         $sub->($hooks{$type}{$id}{call});
839                 }
840         }
841 } #}}}
842
843 sub globlist_to_pagespec ($) { #{{{
844         my @globlist=split(' ', shift);
845
846         my (@spec, @skip);
847         foreach my $glob (@globlist) {
848                 if ($glob=~/^!(.*)/) {
849                         push @skip, $glob;
850                 }
851                 else {
852                         push @spec, $glob;
853                 }
854         }
855
856         my $spec=join(" or ", @spec);
857         if (@skip) {
858                 my $skip=join(" and ", @skip);
859                 if (length $spec) {
860                         $spec="$skip and ($spec)";
861                 }
862                 else {
863                         $spec=$skip;
864                 }
865         }
866         return $spec;
867 } #}}}
868
869 sub is_globlist ($) { #{{{
870         my $s=shift;
871         $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
872 } #}}}
873
874 sub safequote ($) { #{{{
875         my $s=shift;
876         $s=~s/[{}]//g;
877         return "q{$s}";
878 } #}}}
879
880 sub add_depends ($$) { #{{{
881         my $page=shift;
882         my $pagespec=shift;
883         
884         if (! exists $depends{$page}) {
885                 $depends{$page}=$pagespec;
886         }
887         else {
888                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
889         }
890 } # }}}
891
892 sub file_pruned ($$) { #{{{
893         require File::Spec;
894         my $file=File::Spec->canonpath(shift);
895         my $base=File::Spec->canonpath(shift);
896         $file=~s#^\Q$base\E/*##;
897
898         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
899         $file =~ m/$regexp/;
900 } #}}}
901
902 sub gettext { #{{{
903         # Only use gettext in the rare cases it's needed.
904         if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
905                 if (! $gettext_obj) {
906                         $gettext_obj=eval q{
907                                 use Locale::gettext q{textdomain};
908                                 Locale::gettext->domain('ikiwiki')
909                         };
910                         if ($@) {
911                                 print STDERR "$@";
912                                 $gettext_obj=undef;
913                                 return shift;
914                         }
915                 }
916                 return $gettext_obj->get(shift);
917         }
918         else {
919                 return shift;
920         }
921 } #}}}
922
923 sub pagespec_merge ($$) { #{{{
924         my $a=shift;
925         my $b=shift;
926
927         return $a if $a eq $b;
928
929         # Support for old-style GlobLists.
930         if (is_globlist($a)) {
931                 $a=globlist_to_pagespec($a);
932         }
933         if (is_globlist($b)) {
934                 $b=globlist_to_pagespec($b);
935         }
936
937         return "($a) or ($b)";
938 } #}}}
939
940 sub pagespec_translate ($) { #{{{
941         # This assumes that $page is in scope in the function
942         # that evalulates the translated pagespec code.
943         my $spec=shift;
944
945         # Support for old-style GlobLists.
946         if (is_globlist($spec)) {
947                 $spec=globlist_to_pagespec($spec);
948         }
949
950         # Convert spec to perl code.
951         my $code="";
952         while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
953                 my $word=$1;
954                 if (lc $word eq "and") {
955                         $code.=" &&";
956                 }
957                 elsif (lc $word eq "or") {
958                         $code.=" ||";
959                 }
960                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
961                         $code.=" ".$word;
962                 }
963                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
964                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
965                                 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \$from)";
966                         }
967                         else {
968                                 $code.=" 0";
969                         }
970                 }
971                 else {
972                         $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
973                 }
974         }
975
976         return $code;
977 } #}}}
978
979 sub pagespec_match ($$;$) { #{{{
980         my $page=shift;
981         my $spec=shift;
982         my $from=shift;
983
984         return eval pagespec_translate($spec);
985 } #}}}
986
987 package IkiWiki::PageSpec;
988
989 sub match_glob ($$$) { #{{{
990         my $page=shift;
991         my $glob=shift;
992         my $from=shift;
993         if (! defined $from){
994                 $from = "";
995         }
996
997         # relative matching
998         if ($glob =~ m!^\./!) {
999                 $from=~s!/?[^/]+$!!;
1000                 $glob=~s!^\./!!;
1001                 $glob="$from/$glob" if length $from;
1002         }
1003
1004         # turn glob into safe regexp
1005         $glob=quotemeta($glob);
1006         $glob=~s/\\\*/.*/g;
1007         $glob=~s/\\\?/./g;
1008
1009         return $page=~/^$glob$/i;
1010 } #}}}
1011
1012 sub match_link ($$$) { #{{{
1013         my $page=shift;
1014         my $link=lc(shift);
1015         my $from=shift;
1016         if (! defined $from){
1017                 $from = "";
1018         }
1019
1020         # relative matching
1021         if ($link =~ m!^\.! && defined $from) {
1022                 $from=~s!/?[^/]+$!!;
1023                 $link=~s!^\./!!;
1024                 $link="$from/$link" if length $from;
1025         }
1026
1027         my $links = $IkiWiki::links{$page} or return undef;
1028         return 0 unless @$links;
1029         my $bestlink = IkiWiki::bestlink($from, $link);
1030         return 0 unless length $bestlink;
1031         foreach my $p (@$links) {
1032                 return 1 if $bestlink eq IkiWiki::bestlink($page, $p);
1033         }
1034         return 0;
1035 } #}}}
1036
1037 sub match_backlink ($$$) { #{{{
1038         match_link($_[1], $_[0], $_[3]);
1039 } #}}}
1040
1041 sub match_created_before ($$$) { #{{{
1042         my $page=shift;
1043         my $testpage=shift;
1044
1045         if (exists $IkiWiki::pagectime{$testpage}) {
1046                 return $IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage};
1047         }
1048         else {
1049                 return 0;
1050         }
1051 } #}}}
1052
1053 sub match_created_after ($$$) { #{{{
1054         my $page=shift;
1055         my $testpage=shift;
1056
1057         if (exists $IkiWiki::pagectime{$testpage}) {
1058                 return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
1059         }
1060         else {
1061                 return 0;
1062         }
1063 } #}}}
1064
1065 sub match_creation_day ($$$) { #{{{
1066         return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
1067 } #}}}
1068
1069 sub match_creation_month ($$$) { #{{{
1070         return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
1071 } #}}}
1072
1073 sub match_creation_year ($$$) { #{{{
1074         return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);
1075 } #}}}
1076
1077 1