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