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