* Add a new %destsources hash, which maps between a destination file and
[ikiwiki.git] / 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 %destsources
13             %depends %hooks %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('err' => $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                 foreach my $old (@{$renderedfiles{$page}}) {
332                         delete $destsources{$old};
333                 }
334                 $renderedfiles{$page}=[$dest];
335                 $cleared{$page}=1;
336         }
337         $destsources{$dest}=$page;
338 } #}}}
339
340 sub bestlink ($$) { #{{{
341         my $page=shift;
342         my $link=shift;
343         
344         my $cwd=$page;
345         if ($link=~s/^\/+//) {
346                 # absolute links
347                 $cwd="";
348         }
349
350         do {
351                 my $l=$cwd;
352                 $l.="/" if length $l;
353                 $l.=$link;
354
355                 if (exists $links{$l}) {
356                         return $l;
357                 }
358                 elsif (exists $pagecase{lc $l}) {
359                         return $pagecase{lc $l};
360                 }
361         } while $cwd=~s!/?[^/]+$!!;
362
363         if (length $config{userdir} && exists $links{"$config{userdir}/".lc($link)}) {
364                 return "$config{userdir}/".lc($link);
365         }
366
367         #print STDERR "warning: page $page, broken link: $link\n";
368         return "";
369 } #}}}
370
371 sub isinlinableimage ($) { #{{{
372         my $file=shift;
373         
374         $file=~/\.(png|gif|jpg|jpeg)$/i;
375 } #}}}
376
377 sub pagetitle ($;$) { #{{{
378         my $page=shift;
379         my $unescaped=shift;
380
381         if ($unescaped) {
382                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
383         }
384         else {
385                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
386         }
387
388         return $page;
389 } #}}}
390
391 sub titlepage ($) { #{{{
392         my $title=shift;
393         $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
394         return $title;
395 } #}}}
396
397 sub linkpage ($) { #{{{
398         my $link=shift;
399         $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
400         return $link;
401 } #}}}
402
403 sub cgiurl (@) { #{{{
404         my %params=@_;
405
406         return $config{cgiurl}."?".
407                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
408 } #}}}
409
410 sub baseurl (;$) { #{{{
411         my $page=shift;
412
413         return "$config{url}/" if ! defined $page;
414         
415         $page=htmlpage($page);
416         $page=~s/[^\/]+$//;
417         $page=~s/[^\/]+\//..\//g;
418         return $page;
419 } #}}}
420
421 sub abs2rel ($$) { #{{{
422         # Work around very innefficient behavior in File::Spec if abs2rel
423         # is passed two relative paths. It's much faster if paths are
424         # absolute! (Debian bug #376658; fixed in debian unstable now)
425         my $path="/".shift;
426         my $base="/".shift;
427
428         require File::Spec;
429         my $ret=File::Spec->abs2rel($path, $base);
430         $ret=~s/^// if defined $ret;
431         return $ret;
432 } #}}}
433
434 sub displaytime ($) { #{{{
435         my $time=shift;
436
437         eval q{use POSIX};
438         error($@) if $@;
439         # strftime doesn't know about encodings, so make sure
440         # its output is properly treated as utf8
441         return decode_utf8(POSIX::strftime(
442                         $config{timeformat}, localtime($time)));
443 } #}}}
444
445 sub beautify_url ($) { #{{{
446         my $url=shift;
447
448         $url =~ s!/index.html$!/!;
449         $url =~ s!^$!./!; # Browsers don't like empty links...
450
451         return $url;
452 } #}}}
453
454 sub urlto ($$) { #{{{
455         my $to=shift;
456         my $from=shift;
457
458         if (! length $to) {
459                 return beautify_url(baseurl($from));
460         }
461
462         if (! $destsources{$to}) {
463                 $to=htmlpage($to);
464         }
465
466         my $link = abs2rel($to, dirname(htmlpage($from)));
467
468         return beautify_url($link);
469 } #}}}
470
471 sub htmllink ($$$;@) { #{{{
472         my $lpage=shift; # the page doing the linking
473         my $page=shift; # the page that will contain the link (different for inline)
474         my $link=shift;
475         my %opts=@_;
476
477         my $bestlink;
478         if (! $opts{forcesubpage}) {
479                 $bestlink=bestlink($lpage, $link);
480         }
481         else {
482                 $bestlink="$lpage/".lc($link);
483         }
484
485         my $linktext;
486         if (defined $opts{linktext}) {
487                 $linktext=$opts{linktext};
488         }
489         else {
490                 $linktext=pagetitle(basename($link));
491         }
492         
493         return "<span class=\"selflink\">$linktext</span>"
494                 if length $bestlink && $page eq $bestlink;
495         
496         if (! $destsources{$bestlink}) {
497                 $bestlink=htmlpage($bestlink);
498
499                 if (! $destsources{$bestlink}) {
500                         return $linktext unless length $config{cgiurl};
501                         return "<span><a href=\"".
502                                 cgiurl(
503                                         do => "create",
504                                         page => pagetitle(lc($link), 1),
505                                         from => $lpage
506                                 ).
507                                 "\">?</a>$linktext</span>"
508                 }
509         }
510         
511         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
512         $bestlink=beautify_url($bestlink);
513         
514         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
515                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
516         }
517
518         if (defined $opts{anchor}) {
519                 $bestlink.="#".$opts{anchor};
520         }
521
522         return "<a href=\"$bestlink\">$linktext</a>";
523 } #}}}
524
525 sub htmlize ($$$) { #{{{
526         my $page=shift;
527         my $type=shift;
528         my $content=shift;
529
530         if (exists $hooks{htmlize}{$type}) {
531                 $content=$hooks{htmlize}{$type}{call}->(
532                         page => $page,
533                         content => $content,
534                 );
535         }
536         else {
537                 error("htmlization of $type not supported");
538         }
539
540         run_hooks(sanitize => sub {
541                 $content=shift->(
542                         page => $page,
543                         content => $content,
544                 );
545         });
546
547         return $content;
548 } #}}}
549
550 sub linkify ($$$) { #{{{
551         my $lpage=shift; # the page containing the links
552         my $page=shift; # the page the link will end up on (different for inline)
553         my $content=shift;
554
555         $content =~ s{(\\?)$config{wiki_link_regexp}}{
556                 defined $2
557                         ? ( $1 
558                                 ? "[[$2|$3".($4 ? "#$4" : "")."]]" 
559                                 : htmllink($lpage, $page, linkpage($3),
560                                         anchor => $4, linktext => pagetitle($2)))
561                         : ( $1 
562                                 ? "[[$3".($4 ? "#$4" : "")."]]"
563                                 : htmllink($lpage, $page, linkpage($3),
564                                         anchor => $4))
565         }eg;
566         
567         return $content;
568 } #}}}
569
570 my %preprocessing;
571 our $preprocess_preview=0;
572 sub preprocess ($$$;$$) { #{{{
573         my $page=shift; # the page the data comes from
574         my $destpage=shift; # the page the data will appear in (different for inline)
575         my $content=shift;
576         my $scan=shift;
577         my $preview=shift;
578
579         # Using local because it needs to be set within any nested calls
580         # of this function.
581         local $preprocess_preview=$preview if defined $preview;
582
583         my $handle=sub {
584                 my $escape=shift;
585                 my $command=shift;
586                 my $params=shift;
587                 if (length $escape) {
588                         return "[[$command $params]]";
589                 }
590                 elsif (exists $hooks{preprocess}{$command}) {
591                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
592                         # Note: preserve order of params, some plugins may
593                         # consider it significant.
594                         my @params;
595                         while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
596                                 my $key=$1;
597                                 my $val;
598                                 if (defined $2) {
599                                         $val=$2;
600                                         $val=~s/\r\n/\n/mg;
601                                         $val=~s/^\n+//g;
602                                         $val=~s/\n+$//g;
603                                 }
604                                 elsif (defined $3) {
605                                         $val=$3;
606                                 }
607                                 elsif (defined $4) {
608                                         $val=$4;
609                                 }
610
611                                 if (defined $key) {
612                                         push @params, $key, $val;
613                                 }
614                                 else {
615                                         push @params, $val, '';
616                                 }
617                         }
618                         if ($preprocessing{$page}++ > 3) {
619                                 # Avoid loops of preprocessed pages preprocessing
620                                 # other pages that preprocess them, etc.
621                                 #translators: The first parameter is a
622                                 #translators: preprocessor directive name,
623                                 #translators: the second a page name, the
624                                 #translators: third a number.
625                                 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
626                                         $command, $page, $preprocessing{$page}).
627                                 "]]";
628                         }
629                         my $ret=$hooks{preprocess}{$command}{call}->(
630                                 @params,
631                                 page => $page,
632                                 destpage => $destpage,
633                                 preview => $preprocess_preview,
634                         );
635                         $preprocessing{$page}--;
636                         return $ret;
637                 }
638                 else {
639                         return "[[$command $params]]";
640                 }
641         };
642         
643         $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
644         return $content;
645 } #}}}
646
647 sub filter ($$) { #{{{
648         my $page=shift;
649         my $content=shift;
650
651         run_hooks(filter => sub {
652                 $content=shift->(page => $page, content => $content);
653         });
654
655         return $content;
656 } #}}}
657
658 sub indexlink () { #{{{
659         return "<a href=\"$config{url}\">$config{wikiname}</a>";
660 } #}}}
661
662 sub lockwiki () { #{{{
663         # Take an exclusive lock on the wiki to prevent multiple concurrent
664         # run issues. The lock will be dropped on program exit.
665         if (! -d $config{wikistatedir}) {
666                 mkdir($config{wikistatedir});
667         }
668         open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
669                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
670         if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
671                 debug("wiki seems to be locked, waiting for lock");
672                 my $wait=600; # arbitrary, but don't hang forever to 
673                               # prevent process pileup
674                 for (1..$wait) {
675                         return if flock(WIKILOCK, 2 | 4);
676                         sleep 1;
677                 }
678                 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
679         }
680 } #}}}
681
682 sub unlockwiki () { #{{{
683         close WIKILOCK;
684 } #}}}
685
686 sub commit_hook_enabled () { #{{{
687         open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
688                 error ("cannot write to $config{wikistatedir}/commitlock: $!");
689         if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
690                 close COMMITLOCK;
691                 return 0;
692         }
693         close COMMITLOCK;
694         return 1;
695 } #}}}
696
697 sub disable_commit_hook () { #{{{
698         open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
699                 error ("cannot write to $config{wikistatedir}/commitlock: $!");
700         if (! flock(COMMITLOCK, 2)) { # LOCK_EX
701                 error("failed to get commit lock");
702         }
703 } #}}}
704
705 sub enable_commit_hook () { #{{{
706         close COMMITLOCK;
707 } #}}}
708
709 sub loadindex () { #{{{
710         open (IN, "$config{wikistatedir}/index") || return;
711         while (<IN>) {
712                 $_=possibly_foolish_untaint($_);
713                 chomp;
714                 my %items;
715                 $items{link}=[];
716                 $items{dest}=[];
717                 foreach my $i (split(/ /, $_)) {
718                         my ($item, $val)=split(/=/, $i, 2);
719                         push @{$items{$item}}, decode_entities($val);
720                 }
721
722                 next unless exists $items{src}; # skip bad lines for now
723
724                 my $page=pagename($items{src}[0]);
725                 if (! $config{rebuild}) {
726                         $pagesources{$page}=$items{src}[0];
727                         $pagemtime{$page}=$items{mtime}[0];
728                         $oldlinks{$page}=[@{$items{link}}];
729                         $links{$page}=[@{$items{link}}];
730                         $depends{$page}=$items{depends}[0] if exists $items{depends};
731                         $destsources{$_}=$page foreach @{$items{dest}};
732                         $renderedfiles{$page}=[@{$items{dest}}];
733                         $oldrenderedfiles{$page}=[@{$items{dest}}];
734                         $pagecase{lc $page}=$page;
735                 }
736                 $pagectime{$page}=$items{ctime}[0];
737         }
738         close IN;
739 } #}}}
740
741 sub saveindex () { #{{{
742         run_hooks(savestate => sub { shift->() });
743
744         if (! -d $config{wikistatedir}) {
745                 mkdir($config{wikistatedir});
746         }
747         my $newfile="$config{wikistatedir}/index.new";
748         my $cleanup = sub { unlink($newfile) };
749         open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
750         foreach my $page (keys %pagemtime) {
751                 next unless $pagemtime{$page};
752                 my $line="mtime=$pagemtime{$page} ".
753                         "ctime=$pagectime{$page} ".
754                         "src=$pagesources{$page}";
755                 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
756                 my %count;
757                 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
758                 if (exists $depends{$page}) {
759                         $line.=" depends=".encode_entities($depends{$page}, " \t\n");
760                 }
761                 print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
762         }
763         close OUT || error("failed saving to $newfile: $!", $cleanup);
764         rename($newfile, "$config{wikistatedir}/index") ||
765                 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
766 } #}}}
767
768 sub template_file ($) { #{{{
769         my $template=shift;
770
771         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
772                 return "$dir/$template" if -e "$dir/$template";
773         }
774         return undef;
775 } #}}}
776
777 sub template_params (@) { #{{{
778         my $filename=template_file(shift);
779
780         if (! defined $filename) {
781                 return if wantarray;
782                 return "";
783         }
784
785         require HTML::Template;
786         my @ret=(
787                 filter => sub {
788                         my $text_ref = shift;
789                         $$text_ref=&Encode::decode_utf8($$text_ref);
790                 },
791                 filename => $filename,
792                 loop_context_vars => 1,
793                 die_on_bad_params => 0,
794                 @_
795         );
796         return wantarray ? @ret : {@ret};
797 } #}}}
798
799 sub template ($;@) { #{{{
800         HTML::Template->new(template_params(@_));
801 } #}}}
802
803 sub misctemplate ($$;@) { #{{{
804         my $title=shift;
805         my $pagebody=shift;
806         
807         my $template=template("misc.tmpl");
808         $template->param(
809                 title => $title,
810                 indexlink => indexlink(),
811                 wikiname => $config{wikiname},
812                 pagebody => $pagebody,
813                 baseurl => baseurl(),
814                 @_,
815         );
816         run_hooks(pagetemplate => sub {
817                 shift->(page => "", destpage => "", template => $template);
818         });
819         return $template->output;
820 }#}}}
821
822 sub hook (@) { # {{{
823         my %param=@_;
824         
825         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
826                 error "hook requires type, call, and id parameters";
827         }
828
829         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
830         
831         $hooks{$param{type}}{$param{id}}=\%param;
832 } # }}}
833
834 sub run_hooks ($$) { # {{{
835         # Calls the given sub for each hook of the given type,
836         # passing it the hook function to call.
837         my $type=shift;
838         my $sub=shift;
839
840         if (exists $hooks{$type}) {
841                 my @deferred;
842                 foreach my $id (keys %{$hooks{$type}}) {
843                         if ($hooks{$type}{$id}{last}) {
844                                 push @deferred, $id;
845                                 next;
846                         }
847                         $sub->($hooks{$type}{$id}{call});
848                 }
849                 foreach my $id (@deferred) {
850                         $sub->($hooks{$type}{$id}{call});
851                 }
852         }
853 } #}}}
854
855 sub globlist_to_pagespec ($) { #{{{
856         my @globlist=split(' ', shift);
857
858         my (@spec, @skip);
859         foreach my $glob (@globlist) {
860                 if ($glob=~/^!(.*)/) {
861                         push @skip, $glob;
862                 }
863                 else {
864                         push @spec, $glob;
865                 }
866         }
867
868         my $spec=join(" or ", @spec);
869         if (@skip) {
870                 my $skip=join(" and ", @skip);
871                 if (length $spec) {
872                         $spec="$skip and ($spec)";
873                 }
874                 else {
875                         $spec=$skip;
876                 }
877         }
878         return $spec;
879 } #}}}
880
881 sub is_globlist ($) { #{{{
882         my $s=shift;
883         $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
884 } #}}}
885
886 sub safequote ($) { #{{{
887         my $s=shift;
888         $s=~s/[{}]//g;
889         return "q{$s}";
890 } #}}}
891
892 sub add_depends ($$) { #{{{
893         my $page=shift;
894         my $pagespec=shift;
895         
896         if (! exists $depends{$page}) {
897                 $depends{$page}=$pagespec;
898         }
899         else {
900                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
901         }
902 } # }}}
903
904 sub file_pruned ($$) { #{{{
905         require File::Spec;
906         my $file=File::Spec->canonpath(shift);
907         my $base=File::Spec->canonpath(shift);
908         $file=~s#^\Q$base\E/*##;
909
910         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
911         $file =~ m/$regexp/;
912 } #}}}
913
914 sub gettext { #{{{
915         # Only use gettext in the rare cases it's needed.
916         if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
917                 if (! $gettext_obj) {
918                         $gettext_obj=eval q{
919                                 use Locale::gettext q{textdomain};
920                                 Locale::gettext->domain('ikiwiki')
921                         };
922                         if ($@) {
923                                 print STDERR "$@";
924                                 $gettext_obj=undef;
925                                 return shift;
926                         }
927                 }
928                 return $gettext_obj->get(shift);
929         }
930         else {
931                 return shift;
932         }
933 } #}}}
934
935 sub pagespec_merge ($$) { #{{{
936         my $a=shift;
937         my $b=shift;
938
939         return $a if $a eq $b;
940
941         # Support for old-style GlobLists.
942         if (is_globlist($a)) {
943                 $a=globlist_to_pagespec($a);
944         }
945         if (is_globlist($b)) {
946                 $b=globlist_to_pagespec($b);
947         }
948
949         return "($a) or ($b)";
950 } #}}}
951
952 sub pagespec_translate ($) { #{{{
953         # This assumes that $page is in scope in the function
954         # that evalulates the translated pagespec code.
955         my $spec=shift;
956
957         # Support for old-style GlobLists.
958         if (is_globlist($spec)) {
959                 $spec=globlist_to_pagespec($spec);
960         }
961
962         # Convert spec to perl code.
963         my $code="";
964         while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
965                 my $word=$1;
966                 if (lc $word eq "and") {
967                         $code.=" &&";
968                 }
969                 elsif (lc $word eq "or") {
970                         $code.=" ||";
971                 }
972                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
973                         $code.=" ".$word;
974                 }
975                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
976                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
977                                 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \$from)";
978                         }
979                         else {
980                                 $code.=" 0";
981                         }
982                 }
983                 else {
984                         $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
985                 }
986         }
987
988         return $code;
989 } #}}}
990
991 sub pagespec_match ($$;$) { #{{{
992         my $page=shift;
993         my $spec=shift;
994         my $from=shift;
995
996         return eval pagespec_translate($spec);
997 } #}}}
998
999 package IkiWiki::PageSpec;
1000
1001 sub match_glob ($$$) { #{{{
1002         my $page=shift;
1003         my $glob=shift;
1004         my $from=shift;
1005         if (! defined $from){
1006                 $from = "";
1007         }
1008
1009         # relative matching
1010         if ($glob =~ m!^\./!) {
1011                 $from=~s!/?[^/]+$!!;
1012                 $glob=~s!^\./!!;
1013                 $glob="$from/$glob" if length $from;
1014         }
1015
1016         # turn glob into safe regexp
1017         $glob=quotemeta($glob);
1018         $glob=~s/\\\*/.*/g;
1019         $glob=~s/\\\?/./g;
1020
1021         return $page=~/^$glob$/i;
1022 } #}}}
1023
1024 sub match_link ($$$) { #{{{
1025         my $page=shift;
1026         my $link=lc(shift);
1027         my $from=shift;
1028         if (! defined $from){
1029                 $from = "";
1030         }
1031
1032         # relative matching
1033         if ($link =~ m!^\.! && defined $from) {
1034                 $from=~s!/?[^/]+$!!;
1035                 $link=~s!^\./!!;
1036                 $link="$from/$link" if length $from;
1037         }
1038
1039         my $links = $IkiWiki::links{$page} or return undef;
1040         return 0 unless @$links;
1041         my $bestlink = IkiWiki::bestlink($from, $link);
1042         return 0 unless length $bestlink;
1043         foreach my $p (@$links) {
1044                 return 1 if $bestlink eq IkiWiki::bestlink($page, $p);
1045         }
1046         return 0;
1047 } #}}}
1048
1049 sub match_backlink ($$$) { #{{{
1050         match_link($_[1], $_[0], $_[3]);
1051 } #}}}
1052
1053 sub match_created_before ($$$) { #{{{
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_created_after ($$$) { #{{{
1066         my $page=shift;
1067         my $testpage=shift;
1068
1069         if (exists $IkiWiki::pagectime{$testpage}) {
1070                 return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
1071         }
1072         else {
1073                 return 0;
1074         }
1075 } #}}}
1076
1077 sub match_creation_day ($$$) { #{{{
1078         return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
1079 } #}}}
1080
1081 sub match_creation_month ($$$) { #{{{
1082         return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
1083 } #}}}
1084
1085 sub match_creation_year ($$$) { #{{{
1086         return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);
1087 } #}}}
1088
1089 1