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