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