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