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