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