use err facility when logging errors to syslog
[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('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                 $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 
553                                 ? "[[$2|$3".($4 ? "#$4" : "")."]]" 
554                                 : htmllink($lpage, $page, linkpage($3),
555                                         anchor => $4, linktext => pagetitle($2)))
556                         : ( $1 
557                                 ? "[[$3".($4 ? "#$4" : "")."]]"
558                                 : htmllink($lpage, $page, linkpage($3),
559                                         anchor => $4))
560         }eg;
561         
562         return $content;
563 } #}}}
564
565 my %preprocessing;
566 our $preprocess_preview=0;
567 sub preprocess ($$$;$$) { #{{{
568         my $page=shift; # the page the data comes from
569         my $destpage=shift; # the page the data will appear in (different for inline)
570         my $content=shift;
571         my $scan=shift;
572         my $preview=shift;
573
574         # Using local because it needs to be set within any nested calls
575         # of this function.
576         local $preprocess_preview=$preview if defined $preview;
577
578         my $handle=sub {
579                 my $escape=shift;
580                 my $command=shift;
581                 my $params=shift;
582                 if (length $escape) {
583                         return "[[$command $params]]";
584                 }
585                 elsif (exists $hooks{preprocess}{$command}) {
586                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
587                         # Note: preserve order of params, some plugins may
588                         # consider it significant.
589                         my @params;
590                         while ($params =~ /(?:(\w+)=)?(?:"""(.*?)"""|"([^"]+)"|(\S+))(?:\s+|$)/sg) {
591                                 my $key=$1;
592                                 my $val;
593                                 if (defined $2) {
594                                         $val=$2;
595                                         $val=~s/\r\n/\n/mg;
596                                         $val=~s/^\n+//g;
597                                         $val=~s/\n+$//g;
598                                 }
599                                 elsif (defined $3) {
600                                         $val=$3;
601                                 }
602                                 elsif (defined $4) {
603                                         $val=$4;
604                                 }
605
606                                 if (defined $key) {
607                                         push @params, $key, $val;
608                                 }
609                                 else {
610                                         push @params, $val, '';
611                                 }
612                         }
613                         if ($preprocessing{$page}++ > 3) {
614                                 # Avoid loops of preprocessed pages preprocessing
615                                 # other pages that preprocess them, etc.
616                                 #translators: The first parameter is a
617                                 #translators: preprocessor directive name,
618                                 #translators: the second a page name, the
619                                 #translators: third a number.
620                                 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
621                                         $command, $page, $preprocessing{$page}).
622                                 "]]";
623                         }
624                         my $ret=$hooks{preprocess}{$command}{call}->(
625                                 @params,
626                                 page => $page,
627                                 destpage => $destpage,
628                                 preview => $preprocess_preview,
629                         );
630                         $preprocessing{$page}--;
631                         return $ret;
632                 }
633                 else {
634                         return "[[$command $params]]";
635                 }
636         };
637         
638         $content =~ s{(\\?)\[\[(\w+)\s+((?:(?:\w+=)?(?:""".*?"""|"[^"]+"|[^\s\]]+)\s*)*)\]\]}{$handle->($1, $2, $3)}seg;
639         return $content;
640 } #}}}
641
642 sub filter ($$) { #{{{
643         my $page=shift;
644         my $content=shift;
645
646         run_hooks(filter => sub {
647                 $content=shift->(page => $page, content => $content);
648         });
649
650         return $content;
651 } #}}}
652
653 sub indexlink () { #{{{
654         return "<a href=\"$config{url}\">$config{wikiname}</a>";
655 } #}}}
656
657 sub lockwiki () { #{{{
658         # Take an exclusive lock on the wiki to prevent multiple concurrent
659         # run issues. The lock will be dropped on program exit.
660         if (! -d $config{wikistatedir}) {
661                 mkdir($config{wikistatedir});
662         }
663         open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
664                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
665         if (! flock(WIKILOCK, 2 | 4)) { # LOCK_EX | LOCK_NB
666                 debug("wiki seems to be locked, waiting for lock");
667                 my $wait=600; # arbitrary, but don't hang forever to 
668                               # prevent process pileup
669                 for (1..$wait) {
670                         return if flock(WIKILOCK, 2 | 4);
671                         sleep 1;
672                 }
673                 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
674         }
675 } #}}}
676
677 sub unlockwiki () { #{{{
678         close WIKILOCK;
679 } #}}}
680
681 sub commit_hook_enabled () { #{{{
682         open(COMMITLOCK, "+>$config{wikistatedir}/commitlock") ||
683                 error ("cannot write to $config{wikistatedir}/commitlock: $!");
684         if (! flock(COMMITLOCK, 1 | 4)) { # LOCK_SH | LOCK_NB to test
685                 close COMMITLOCK;
686                 return 0;
687         }
688         close COMMITLOCK;
689         return 1;
690 } #}}}
691
692 sub disable_commit_hook () { #{{{
693         open(COMMITLOCK, ">$config{wikistatedir}/commitlock") ||
694                 error ("cannot write to $config{wikistatedir}/commitlock: $!");
695         if (! flock(COMMITLOCK, 2)) { # LOCK_EX
696                 error("failed to get commit lock");
697         }
698 } #}}}
699
700 sub enable_commit_hook () { #{{{
701         close COMMITLOCK;
702 } #}}}
703
704 sub loadindex () { #{{{
705         open (IN, "$config{wikistatedir}/index") || return;
706         while (<IN>) {
707                 $_=possibly_foolish_untaint($_);
708                 chomp;
709                 my %items;
710                 $items{link}=[];
711                 $items{dest}=[];
712                 foreach my $i (split(/ /, $_)) {
713                         my ($item, $val)=split(/=/, $i, 2);
714                         push @{$items{$item}}, decode_entities($val);
715                 }
716
717                 next unless exists $items{src}; # skip bad lines for now
718
719                 my $page=pagename($items{src}[0]);
720                 if (! $config{rebuild}) {
721                         $pagesources{$page}=$items{src}[0];
722                         $pagemtime{$page}=$items{mtime}[0];
723                         $oldlinks{$page}=[@{$items{link}}];
724                         $links{$page}=[@{$items{link}}];
725                         $depends{$page}=$items{depends}[0] if exists $items{depends};
726                         $renderedfiles{$page}=[@{$items{dest}}];
727                         $oldrenderedfiles{$page}=[@{$items{dest}}];
728                         $pagecase{lc $page}=$page;
729                 }
730                 $pagectime{$page}=$items{ctime}[0];
731         }
732         close IN;
733 } #}}}
734
735 sub saveindex () { #{{{
736         run_hooks(savestate => sub { shift->() });
737
738         if (! -d $config{wikistatedir}) {
739                 mkdir($config{wikistatedir});
740         }
741         my $newfile="$config{wikistatedir}/index.new";
742         my $cleanup = sub { unlink($newfile) };
743         open (OUT, ">$newfile") || error("cannot write to $newfile: $!", $cleanup);
744         foreach my $page (keys %pagemtime) {
745                 next unless $pagemtime{$page};
746                 my $line="mtime=$pagemtime{$page} ".
747                         "ctime=$pagectime{$page} ".
748                         "src=$pagesources{$page}";
749                 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
750                 my %count;
751                 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
752                 if (exists $depends{$page}) {
753                         $line.=" depends=".encode_entities($depends{$page}, " \t\n");
754                 }
755                 print OUT $line."\n" || error("failed writing to $newfile: $!", $cleanup);
756         }
757         close OUT || error("failed saving to $newfile: $!", $cleanup);
758         rename($newfile, "$config{wikistatedir}/index") ||
759                 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
760 } #}}}
761
762 sub template_file ($) { #{{{
763         my $template=shift;
764
765         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
766                 return "$dir/$template" if -e "$dir/$template";
767         }
768         return undef;
769 } #}}}
770
771 sub template_params (@) { #{{{
772         my $filename=template_file(shift);
773
774         if (! defined $filename) {
775                 return if wantarray;
776                 return "";
777         }
778
779         require HTML::Template;
780         my @ret=(
781                 filter => sub {
782                         my $text_ref = shift;
783                         $$text_ref=&Encode::decode_utf8($$text_ref);
784                 },
785                 filename => $filename,
786                 loop_context_vars => 1,
787                 die_on_bad_params => 0,
788                 @_
789         );
790         return wantarray ? @ret : {@ret};
791 } #}}}
792
793 sub template ($;@) { #{{{
794         HTML::Template->new(template_params(@_));
795 } #}}}
796
797 sub misctemplate ($$;@) { #{{{
798         my $title=shift;
799         my $pagebody=shift;
800         
801         my $template=template("misc.tmpl");
802         $template->param(
803                 title => $title,
804                 indexlink => indexlink(),
805                 wikiname => $config{wikiname},
806                 pagebody => $pagebody,
807                 baseurl => baseurl(),
808                 @_,
809         );
810         run_hooks(pagetemplate => sub {
811                 shift->(page => "", destpage => "", template => $template);
812         });
813         return $template->output;
814 }#}}}
815
816 sub hook (@) { # {{{
817         my %param=@_;
818         
819         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
820                 error "hook requires type, call, and id parameters";
821         }
822
823         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
824         
825         $hooks{$param{type}}{$param{id}}=\%param;
826 } # }}}
827
828 sub run_hooks ($$) { # {{{
829         # Calls the given sub for each hook of the given type,
830         # passing it the hook function to call.
831         my $type=shift;
832         my $sub=shift;
833
834         if (exists $hooks{$type}) {
835                 my @deferred;
836                 foreach my $id (keys %{$hooks{$type}}) {
837                         if ($hooks{$type}{$id}{last}) {
838                                 push @deferred, $id;
839                                 next;
840                         }
841                         $sub->($hooks{$type}{$id}{call});
842                 }
843                 foreach my $id (@deferred) {
844                         $sub->($hooks{$type}{$id}{call});
845                 }
846         }
847 } #}}}
848
849 sub globlist_to_pagespec ($) { #{{{
850         my @globlist=split(' ', shift);
851
852         my (@spec, @skip);
853         foreach my $glob (@globlist) {
854                 if ($glob=~/^!(.*)/) {
855                         push @skip, $glob;
856                 }
857                 else {
858                         push @spec, $glob;
859                 }
860         }
861
862         my $spec=join(" or ", @spec);
863         if (@skip) {
864                 my $skip=join(" and ", @skip);
865                 if (length $spec) {
866                         $spec="$skip and ($spec)";
867                 }
868                 else {
869                         $spec=$skip;
870                 }
871         }
872         return $spec;
873 } #}}}
874
875 sub is_globlist ($) { #{{{
876         my $s=shift;
877         $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
878 } #}}}
879
880 sub safequote ($) { #{{{
881         my $s=shift;
882         $s=~s/[{}]//g;
883         return "q{$s}";
884 } #}}}
885
886 sub add_depends ($$) { #{{{
887         my $page=shift;
888         my $pagespec=shift;
889         
890         if (! exists $depends{$page}) {
891                 $depends{$page}=$pagespec;
892         }
893         else {
894                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
895         }
896 } # }}}
897
898 sub file_pruned ($$) { #{{{
899         require File::Spec;
900         my $file=File::Spec->canonpath(shift);
901         my $base=File::Spec->canonpath(shift);
902         $file=~s#^\Q$base\E/*##;
903
904         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
905         $file =~ m/$regexp/;
906 } #}}}
907
908 sub gettext { #{{{
909         # Only use gettext in the rare cases it's needed.
910         if (exists $ENV{LANG} || exists $ENV{LC_ALL} || exists $ENV{LC_MESSAGES}) {
911                 if (! $gettext_obj) {
912                         $gettext_obj=eval q{
913                                 use Locale::gettext q{textdomain};
914                                 Locale::gettext->domain('ikiwiki')
915                         };
916                         if ($@) {
917                                 print STDERR "$@";
918                                 $gettext_obj=undef;
919                                 return shift;
920                         }
921                 }
922                 return $gettext_obj->get(shift);
923         }
924         else {
925                 return shift;
926         }
927 } #}}}
928
929 sub pagespec_merge ($$) { #{{{
930         my $a=shift;
931         my $b=shift;
932
933         return $a if $a eq $b;
934
935         # Support for old-style GlobLists.
936         if (is_globlist($a)) {
937                 $a=globlist_to_pagespec($a);
938         }
939         if (is_globlist($b)) {
940                 $b=globlist_to_pagespec($b);
941         }
942
943         return "($a) or ($b)";
944 } #}}}
945
946 sub pagespec_translate ($) { #{{{
947         # This assumes that $page is in scope in the function
948         # that evalulates the translated pagespec code.
949         my $spec=shift;
950
951         # Support for old-style GlobLists.
952         if (is_globlist($spec)) {
953                 $spec=globlist_to_pagespec($spec);
954         }
955
956         # Convert spec to perl code.
957         my $code="";
958         while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
959                 my $word=$1;
960                 if (lc $word eq "and") {
961                         $code.=" &&";
962                 }
963                 elsif (lc $word eq "or") {
964                         $code.=" ||";
965                 }
966                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
967                         $code.=" ".$word;
968                 }
969                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
970                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
971                                 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \$from)";
972                         }
973                         else {
974                                 $code.=" 0";
975                         }
976                 }
977                 else {
978                         $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \$from)";
979                 }
980         }
981
982         return $code;
983 } #}}}
984
985 sub pagespec_match ($$;$) { #{{{
986         my $page=shift;
987         my $spec=shift;
988         my $from=shift;
989
990         return eval pagespec_translate($spec);
991 } #}}}
992
993 package IkiWiki::PageSpec;
994
995 sub match_glob ($$$) { #{{{
996         my $page=shift;
997         my $glob=shift;
998         my $from=shift;
999         if (! defined $from){
1000                 $from = "";
1001         }
1002
1003         # relative matching
1004         if ($glob =~ m!^\./!) {
1005                 $from=~s!/?[^/]+$!!;
1006                 $glob=~s!^\./!!;
1007                 $glob="$from/$glob" if length $from;
1008         }
1009
1010         # turn glob into safe regexp
1011         $glob=quotemeta($glob);
1012         $glob=~s/\\\*/.*/g;
1013         $glob=~s/\\\?/./g;
1014
1015         return $page=~/^$glob$/i;
1016 } #}}}
1017
1018 sub match_link ($$$) { #{{{
1019         my $page=shift;
1020         my $link=lc(shift);
1021         my $from=shift;
1022         if (! defined $from){
1023                 $from = "";
1024         }
1025
1026         # relative matching
1027         if ($link =~ m!^\.! && defined $from) {
1028                 $from=~s!/?[^/]+$!!;
1029                 $link=~s!^\./!!;
1030                 $link="$from/$link" if length $from;
1031         }
1032
1033         my $links = $IkiWiki::links{$page} or return undef;
1034         return 0 unless @$links;
1035         my $bestlink = IkiWiki::bestlink($from, $link);
1036         return 0 unless length $bestlink;
1037         foreach my $p (@$links) {
1038                 return 1 if $bestlink eq IkiWiki::bestlink($page, $p);
1039         }
1040         return 0;
1041 } #}}}
1042
1043 sub match_backlink ($$$) { #{{{
1044         match_link($_[1], $_[0], $_[3]);
1045 } #}}}
1046
1047 sub match_created_before ($$$) { #{{{
1048         my $page=shift;
1049         my $testpage=shift;
1050
1051         if (exists $IkiWiki::pagectime{$testpage}) {
1052                 return $IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage};
1053         }
1054         else {
1055                 return 0;
1056         }
1057 } #}}}
1058
1059 sub match_created_after ($$$) { #{{{
1060         my $page=shift;
1061         my $testpage=shift;
1062
1063         if (exists $IkiWiki::pagectime{$testpage}) {
1064                 return $IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage};
1065         }
1066         else {
1067                 return 0;
1068         }
1069 } #}}}
1070
1071 sub match_creation_day ($$$) { #{{{
1072         return ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift);
1073 } #}}}
1074
1075 sub match_creation_month ($$$) { #{{{
1076         return ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift);
1077 } #}}}
1078
1079 sub match_creation_year ($$$) { #{{{
1080         return ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift);
1081 } #}}}
1082
1083 1