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