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