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