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