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