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