]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki.pm
need to handle urls to images the same
[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 ($) { #{{{
286         my $file=shift;
287
288         return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
289         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
290                 return "$dir/$file" if -e "$dir/$file";
291         }
292         error("internal error: $file cannot be found in $config{srcdir} or underlay");
293         return;
294 } #}}}
295
296 sub add_underlay ($) { #{{{
297         my $dir=shift;
298
299         if ($dir=~/^\//) {
300                 unshift @{$config{underlaydirs}}, $dir;
301         }
302         else {
303                 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
304         }
305
306         return 1;
307 } #}}}
308
309 sub readfile ($;$$) { #{{{
310         my $file=shift;
311         my $binary=shift;
312         my $wantfd=shift;
313
314         if (-l $file) {
315                 error("cannot read a symlink ($file)");
316         }
317         
318         local $/=undef;
319         open (my $in, "<", $file) || error("failed to read $file: $!");
320         binmode($in) if ($binary);
321         return \*$in if $wantfd;
322         my $ret=<$in>;
323         close $in || error("failed to read $file: $!");
324         return $ret;
325 } #}}}
326
327 sub prep_writefile ($$) {
328         my $file=shift;
329         my $destdir=shift;
330         
331         my $test=$file;
332         while (length $test) {
333                 if (-l "$destdir/$test") {
334                         error("cannot write to a symlink ($test)");
335                 }
336                 $test=dirname($test);
337         }
338
339         my $dir=dirname("$destdir/$file");
340         if (! -d $dir) {
341                 my $d="";
342                 foreach my $s (split(m!/+!, $dir)) {
343                         $d.="$s/";
344                         if (! -d $d) {
345                                 mkdir($d) || error("failed to create directory $d: $!");
346                         }
347                 }
348         }
349
350         return 1;
351 }
352
353 sub writefile ($$$;$$) { #{{{
354         my $file=shift; # can include subdirs
355         my $destdir=shift; # directory to put file in
356         my $content=shift;
357         my $binary=shift;
358         my $writer=shift;
359         
360         prep_writefile($file, $destdir);
361         
362         my $newfile="$destdir/$file.ikiwiki-new";
363         if (-l $newfile) {
364                 error("cannot write to a symlink ($newfile)");
365         }
366         
367         my $cleanup = sub { unlink($newfile) };
368         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
369         binmode($out) if ($binary);
370         if ($writer) {
371                 $writer->(\*$out, $cleanup);
372         }
373         else {
374                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
375         }
376         close $out || error("failed saving $newfile: $!", $cleanup);
377         rename($newfile, "$destdir/$file") || 
378                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
379
380         return 1;
381 } #}}}
382
383 my %cleared;
384 sub will_render ($$;$) { #{{{
385         my $page=shift;
386         my $dest=shift;
387         my $clear=shift;
388
389         # Important security check.
390         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
391             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
392                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
393         }
394
395         if (! $clear || $cleared{$page}) {
396                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
397         }
398         else {
399                 foreach my $old (@{$renderedfiles{$page}}) {
400                         delete $destsources{$old};
401                 }
402                 $renderedfiles{$page}=[$dest];
403                 $cleared{$page}=1;
404         }
405         $destsources{$dest}=$page;
406
407         return 1;
408 } #}}}
409
410 sub bestlink ($$) { #{{{
411         my $page=shift;
412         my $link=shift;
413         
414         my $cwd=$page;
415         if ($link=~s/^\/+//) {
416                 # absolute links
417                 $cwd="";
418         }
419         $link=~s/\/$//;
420
421         do {
422                 my $l=$cwd;
423                 $l.="/" if length $l;
424                 $l.=$link;
425
426                 if (exists $links{$l}) {
427                         return $l;
428                 }
429                 elsif (exists $pagecase{lc $l}) {
430                         return $pagecase{lc $l};
431                 }
432         } while $cwd=~s!/?[^/]+$!!;
433
434         if (length $config{userdir}) {
435                 my $l = "$config{userdir}/".lc($link);
436                 if (exists $links{$l}) {
437                         return $l;
438                 }
439                 elsif (exists $pagecase{lc $l}) {
440                         return $pagecase{lc $l};
441                 }
442         }
443
444         #print STDERR "warning: page $page, broken link: $link\n";
445         return "";
446 } #}}}
447
448 sub isinlinableimage ($) { #{{{
449         my $file=shift;
450         
451         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
452 } #}}}
453
454 sub pagetitle ($;$) { #{{{
455         my $page=shift;
456         my $unescaped=shift;
457
458         if ($unescaped) {
459                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
460         }
461         else {
462                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
463         }
464
465         return $page;
466 } #}}}
467
468 sub titlepage ($) { #{{{
469         my $title=shift;
470         $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
471         return $title;
472 } #}}}
473
474 sub linkpage ($) { #{{{
475         my $link=shift;
476         $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
477         return $link;
478 } #}}}
479
480 sub cgiurl (@) { #{{{
481         my %params=@_;
482
483         return $config{cgiurl}."?".
484                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
485 } #}}}
486
487 sub baseurl (;$) { #{{{
488         my $page=shift;
489
490         return "$config{url}/" if ! defined $page;
491         
492         $page=htmlpage($page);
493         $page=~s/[^\/]+$//;
494         $page=~s/[^\/]+\//..\//g;
495         return $page;
496 } #}}}
497
498 sub abs2rel ($$) { #{{{
499         # Work around very innefficient behavior in File::Spec if abs2rel
500         # is passed two relative paths. It's much faster if paths are
501         # absolute! (Debian bug #376658; fixed in debian unstable now)
502         my $path="/".shift;
503         my $base="/".shift;
504
505         require File::Spec;
506         my $ret=File::Spec->abs2rel($path, $base);
507         $ret=~s/^// if defined $ret;
508         return $ret;
509 } #}}}
510
511 sub displaytime ($;$) { #{{{
512         my $time=shift;
513         my $format=shift;
514         if (! defined $format) {
515                 $format=$config{timeformat};
516         }
517
518         # strftime doesn't know about encodings, so make sure
519         # its output is properly treated as utf8
520         return decode_utf8(POSIX::strftime($format, localtime($time)));
521 } #}}}
522
523 sub beautify_url ($) { #{{{
524         my $url=shift;
525
526         if ($config{usedirs}) {
527                 $url =~ s!/index.$config{htmlext}$!/!;
528         }
529         $url =~ s!^$!./!; # Browsers don't like empty links...
530
531         return $url;
532 } #}}}
533
534 sub urlto ($$) { #{{{
535         my $to=shift;
536         my $from=shift;
537
538         if (! length $to) {
539                 return beautify_url(baseurl($from));
540         }
541
542         if (! $destsources{$to}) {
543                 $to=htmlpage($to);
544         }
545
546         my $link = abs2rel($to, dirname(htmlpage($from)));
547
548         return beautify_url($link);
549 } #}}}
550
551 sub htmllink ($$$;@) { #{{{
552         my $lpage=shift; # the page doing the linking
553         my $page=shift; # the page that will contain the link (different for inline)
554         my $link=shift;
555         my %opts=@_;
556
557         $link=~s/\/$//;
558
559         my $bestlink;
560         if (! $opts{forcesubpage}) {
561                 $bestlink=bestlink($lpage, $link);
562         }
563         else {
564                 $bestlink="$lpage/".lc($link);
565         }
566
567         my $linktext;
568         if (defined $opts{linktext}) {
569                 $linktext=$opts{linktext};
570         }
571         else {
572                 $linktext=pagetitle(basename($link));
573         }
574         
575         return "<span class=\"selflink\">$linktext</span>"
576                 if length $bestlink && $page eq $bestlink &&
577                    ! defined $opts{anchor};
578         
579         if (! $destsources{$bestlink}) {
580                 $bestlink=htmlpage($bestlink);
581
582                 if (! $destsources{$bestlink}) {
583                         return $linktext unless length $config{cgiurl};
584                         return "<span class=\"createlink\"><a href=\"".
585                                 cgiurl(
586                                         do => "create",
587                                         page => pagetitle(lc($link), 1),
588                                         from => $lpage
589                                 ).
590                                 "\">?</a>$linktext</span>"
591                 }
592         }
593         
594         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
595         $bestlink=beautify_url($bestlink);
596         
597         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
598                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
599         }
600
601         if (defined $opts{anchor}) {
602                 $bestlink.="#".$opts{anchor};
603         }
604
605         my @attrs;
606         if (defined $opts{rel}) {
607                 push @attrs, ' rel="'.$opts{rel}.'"';
608         }
609         if (defined $opts{class}) {
610                 push @attrs, ' class="'.$opts{class}.'"';
611         }
612
613         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
614 } #}}}
615
616 sub userlink ($) { #{{{
617         my $user=shift;
618
619         my $oiduser=eval { openiduser($user) };
620         if (defined $oiduser) {
621                 return "<a href=\"$user\">$oiduser</a>";
622         }
623         else {
624                 return htmllink("", "", escapeHTML(
625                         length $config{userdir} ? $config{userdir}."/".$user : $user
626                 ), noimageinline => 1);
627         }
628 } #}}}
629
630 sub htmlize ($$$) { #{{{
631         my $page=shift;
632         my $type=shift;
633         my $content=shift;
634         
635         my $oneline = $content !~ /\n/;
636
637         if (exists $hooks{htmlize}{$type}) {
638                 $content=$hooks{htmlize}{$type}{call}->(
639                         page => $page,
640                         content => $content,
641                 );
642         }
643         else {
644                 error("htmlization of $type not supported");
645         }
646
647         run_hooks(sanitize => sub {
648                 $content=shift->(
649                         page => $page,
650                         content => $content,
651                 );
652         });
653         
654         if ($oneline) {
655                 # hack to get rid of enclosing junk added by markdown
656                 # and other htmlizers
657                 $content=~s/^<p>//i;
658                 $content=~s/<\/p>$//i;
659                 chomp $content;
660         }
661
662         return $content;
663 } #}}}
664
665 sub linkify ($$$) { #{{{
666         my $page=shift;
667         my $destpage=shift;
668         my $content=shift;
669
670         run_hooks(linkify => sub {
671                 $content=shift->(
672                         page => $page,
673                         destpage => $destpage,
674                         content => $content,
675                 );
676         });
677         
678         return $content;
679 } #}}}
680
681 my %preprocessing;
682 our $preprocess_preview=0;
683 sub preprocess ($$$;$$) { #{{{
684         my $page=shift; # the page the data comes from
685         my $destpage=shift; # the page the data will appear in (different for inline)
686         my $content=shift;
687         my $scan=shift;
688         my $preview=shift;
689
690         # Using local because it needs to be set within any nested calls
691         # of this function.
692         local $preprocess_preview=$preview if defined $preview;
693
694         my $handle=sub {
695                 my $escape=shift;
696                 my $prefix=shift;
697                 my $command=shift;
698                 my $params=shift;
699                 if (length $escape) {
700                         return "[[$prefix$command $params]]";
701                 }
702                 elsif (exists $hooks{preprocess}{$command}) {
703                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
704                         # Note: preserve order of params, some plugins may
705                         # consider it significant.
706                         my @params;
707                         while ($params =~ m{
708                                 (?:([-\w]+)=)?          # 1: named parameter key?
709                                 (?:
710                                         """(.*?)"""     # 2: triple-quoted value
711                                 |
712                                         "([^"]+)"       # 3: single-quoted value
713                                 |
714                                         (\S+)           # 4: unquoted value
715                                 )
716                                 (?:\s+|$)               # delimiter to next param
717                         }sgx) {
718                                 my $key=$1;
719                                 my $val;
720                                 if (defined $2) {
721                                         $val=$2;
722                                         $val=~s/\r\n/\n/mg;
723                                         $val=~s/^\n+//g;
724                                         $val=~s/\n+$//g;
725                                 }
726                                 elsif (defined $3) {
727                                         $val=$3;
728                                 }
729                                 elsif (defined $4) {
730                                         $val=$4;
731                                 }
732
733                                 if (defined $key) {
734                                         push @params, $key, $val;
735                                 }
736                                 else {
737                                         push @params, $val, '';
738                                 }
739                         }
740                         if ($preprocessing{$page}++ > 3) {
741                                 # Avoid loops of preprocessed pages preprocessing
742                                 # other pages that preprocess them, etc.
743                                 #translators: The first parameter is a
744                                 #translators: preprocessor directive name,
745                                 #translators: the second a page name, the
746                                 #translators: third a number.
747                                 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
748                                         $command, $page, $preprocessing{$page}).
749                                 "]]";
750                         }
751                         my $ret;
752                         if (! $scan) {
753                                 $ret=$hooks{preprocess}{$command}{call}->(
754                                         @params,
755                                         page => $page,
756                                         destpage => $destpage,
757                                         preview => $preprocess_preview,
758                                 );
759                         }
760                         else {
761                                 # use void context during scan pass
762                                 $hooks{preprocess}{$command}{call}->(
763                                         @params,
764                                         page => $page,
765                                         destpage => $destpage,
766                                         preview => $preprocess_preview,
767                                 );
768                                 $ret="";
769                         }
770                         $preprocessing{$page}--;
771                         return $ret;
772                 }
773                 else {
774                         return "[[$prefix$command $params]]";
775                 }
776         };
777         
778         my $regex;
779         if ($config{prefix_directives}) {
780                 $regex = qr{
781                         (\\?)           # 1: escape?
782                         \[\[(!)         # directive open; 2: prefix
783                         ([-\w]+)        # 3: command
784                         (               # 4: the parameters..
785                                 \s+     # Must have space if parameters present
786                                 (?:
787                                         (?:[-\w]+=)?            # named parameter key?
788                                         (?:
789                                                 """.*?"""       # triple-quoted value
790                                                 |
791                                                 "[^"]+"         # single-quoted value
792                                                 |
793                                                 [^\s\]]+        # unquoted value
794                                         )
795                                         \s*                     # whitespace or end
796                                                                 # of directive
797                                 )
798                         *)?             # 0 or more parameters
799                         \]\]            # directive closed
800                 }sx;
801         } else {
802                 $regex = qr{
803                         (\\?)           # 1: escape?
804                         \[\[(!?)        # directive open; 2: optional prefix
805                         ([-\w]+)        # 3: command
806                         \s+
807                         (               # 4: the parameters..
808                                 (?:
809                                         (?:[-\w]+=)?            # named parameter key?
810                                         (?:
811                                                 """.*?"""       # triple-quoted value
812                                                 |
813                                                 "[^"]+"         # single-quoted value
814                                                 |
815                                                 [^\s\]]+        # unquoted value
816                                         )
817                                         \s*                     # whitespace or end
818                                                                 # of directive
819                                 )
820                         *)              # 0 or more parameters
821                         \]\]            # directive closed
822                 }sx;
823         }
824
825         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
826         return $content;
827 } #}}}
828
829 sub filter ($$$) { #{{{
830         my $page=shift;
831         my $destpage=shift;
832         my $content=shift;
833
834         run_hooks(filter => sub {
835                 $content=shift->(page => $page, destpage => $destpage, 
836                         content => $content);
837         });
838
839         return $content;
840 } #}}}
841
842 sub indexlink () { #{{{
843         return "<a href=\"$config{url}\">$config{wikiname}</a>";
844 } #}}}
845
846 my $wikilock;
847
848 sub lockwiki (;$) { #{{{
849         my $wait=@_ ? shift : 1;
850         # Take an exclusive lock on the wiki to prevent multiple concurrent
851         # run issues. The lock will be dropped on program exit.
852         if (! -d $config{wikistatedir}) {
853                 mkdir($config{wikistatedir});
854         }
855         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
856                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
857         if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
858                 if ($wait) {
859                         debug("wiki seems to be locked, waiting for lock");
860                         my $wait=600; # arbitrary, but don't hang forever to 
861                                       # prevent process pileup
862                         for (1..$wait) {
863                                 return if flock($wikilock, 2 | 4);
864                                 sleep 1;
865                         }
866                         error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
867                 }
868                 else {
869                         return 0;
870                 }
871         }
872         return 1;
873 } #}}}
874
875 sub unlockwiki () { #{{{
876         return close($wikilock) if $wikilock;
877         return;
878 } #}}}
879
880 my $commitlock;
881
882 sub commit_hook_enabled () { #{{{
883         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
884                 error("cannot write to $config{wikistatedir}/commitlock: $!");
885         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
886                 close($commitlock) || error("failed closing commitlock: $!");
887                 return 0;
888         }
889         close($commitlock) || error("failed closing commitlock: $!");
890         return 1;
891 } #}}}
892
893 sub disable_commit_hook () { #{{{
894         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
895                 error("cannot write to $config{wikistatedir}/commitlock: $!");
896         if (! flock($commitlock, 2)) { # LOCK_EX
897                 error("failed to get commit lock");
898         }
899         return 1;
900 } #}}}
901
902 sub enable_commit_hook () { #{{{
903         return close($commitlock) if $commitlock;
904         return;
905 } #}}}
906
907 sub loadindex () { #{{{
908         %oldrenderedfiles=%pagectime=();
909         if (! $config{rebuild}) {
910                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
911                 %destsources=%renderedfiles=%pagecase=%pagestate=();
912         }
913         my $in;
914         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
915                 if (-e "$config{wikistatedir}/index") {
916                         system("ikiwiki-transition", "indexdb", $config{srcdir});
917                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
918                 }
919                 else {
920                         return;
921                 }
922         }
923         my $ret=Storable::fd_retrieve($in);
924         if (! defined $ret) {
925                 return 0;
926         }
927         my %index=%$ret;
928         foreach my $src (keys %index) {
929                 my %d=%{$index{$src}};
930                 my $page=pagename($src);
931                 $pagectime{$page}=$d{ctime};
932                 if (! $config{rebuild}) {
933                         $pagesources{$page}=$src;
934                         $pagemtime{$page}=$d{mtime};
935                         $renderedfiles{$page}=$d{dest};
936                         if (exists $d{links} && ref $d{links}) {
937                                 $links{$page}=$d{links};
938                                 $oldlinks{$page}=[@{$d{links}}];
939                         }
940                         if (exists $d{depends}) {
941                                 $depends{$page}=$d{depends};
942                         }
943                         if (exists $d{state}) {
944                                 $pagestate{$page}=$d{state};
945                         }
946                 }
947                 $oldrenderedfiles{$page}=[@{$d{dest}}];
948         }
949         foreach my $page (keys %pagesources) {
950                 $pagecase{lc $page}=$page;
951         }
952         foreach my $page (keys %renderedfiles) {
953                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
954         }
955         return close($in);
956 } #}}}
957
958 sub saveindex () { #{{{
959         run_hooks(savestate => sub { shift->() });
960
961         my %hookids;
962         foreach my $type (keys %hooks) {
963                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
964         }
965         my @hookids=keys %hookids;
966
967         if (! -d $config{wikistatedir}) {
968                 mkdir($config{wikistatedir});
969         }
970         my $newfile="$config{wikistatedir}/indexdb.new";
971         my $cleanup = sub { unlink($newfile) };
972         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
973         my %index;
974         foreach my $page (keys %pagemtime) {
975                 next unless $pagemtime{$page};
976                 my $src=$pagesources{$page};
977
978                 $index{$src}={
979                         ctime => $pagectime{$page},
980                         mtime => $pagemtime{$page},
981                         dest => $renderedfiles{$page},
982                         links => $links{$page},
983                 };
984
985                 if (exists $depends{$page}) {
986                         $index{$src}{depends} = $depends{$page};
987                 }
988
989                 if (exists $pagestate{$page}) {
990                         foreach my $id (@hookids) {
991                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
992                                         $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
993                                 }
994                         }
995                 }
996         }
997         my $ret=Storable::nstore_fd(\%index, $out);
998         return if ! defined $ret || ! $ret;
999         close $out || error("failed saving to $newfile: $!", $cleanup);
1000         rename($newfile, "$config{wikistatedir}/indexdb") ||
1001                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1002         
1003         return 1;
1004 } #}}}
1005
1006 sub template_file ($) { #{{{
1007         my $template=shift;
1008
1009         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1010                 return "$dir/$template" if -e "$dir/$template";
1011         }
1012         return;
1013 } #}}}
1014
1015 sub template_params (@) { #{{{
1016         my $filename=template_file(shift);
1017
1018         if (! defined $filename) {
1019                 return if wantarray;
1020                 return "";
1021         }
1022
1023         my @ret=(
1024                 filter => sub {
1025                         my $text_ref = shift;
1026                         ${$text_ref} = decode_utf8(${$text_ref});
1027                 },
1028                 filename => $filename,
1029                 loop_context_vars => 1,
1030                 die_on_bad_params => 0,
1031                 @_
1032         );
1033         return wantarray ? @ret : {@ret};
1034 } #}}}
1035
1036 sub template ($;@) { #{{{
1037         require HTML::Template;
1038         return HTML::Template->new(template_params(@_));
1039 } #}}}
1040
1041 sub misctemplate ($$;@) { #{{{
1042         my $title=shift;
1043         my $pagebody=shift;
1044         
1045         my $template=template("misc.tmpl");
1046         $template->param(
1047                 title => $title,
1048                 indexlink => indexlink(),
1049                 wikiname => $config{wikiname},
1050                 pagebody => $pagebody,
1051                 baseurl => baseurl(),
1052                 @_,
1053         );
1054         run_hooks(pagetemplate => sub {
1055                 shift->(page => "", destpage => "", template => $template);
1056         });
1057         return $template->output;
1058 }#}}}
1059
1060 sub hook (@) { # {{{
1061         my %param=@_;
1062         
1063         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1064                 error 'hook requires type, call, and id parameters';
1065         }
1066
1067         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1068         
1069         $hooks{$param{type}}{$param{id}}=\%param;
1070         return 1;
1071 } # }}}
1072
1073 sub run_hooks ($$) { # {{{
1074         # Calls the given sub for each hook of the given type,
1075         # passing it the hook function to call.
1076         my $type=shift;
1077         my $sub=shift;
1078
1079         if (exists $hooks{$type}) {
1080                 my @deferred;
1081                 foreach my $id (keys %{$hooks{$type}}) {
1082                         if ($hooks{$type}{$id}{last}) {
1083                                 push @deferred, $id;
1084                                 next;
1085                         }
1086                         $sub->($hooks{$type}{$id}{call});
1087                 }
1088                 foreach my $id (@deferred) {
1089                         $sub->($hooks{$type}{$id}{call});
1090                 }
1091         }
1092
1093         return 1;
1094 } #}}}
1095
1096 sub globlist_to_pagespec ($) { #{{{
1097         my @globlist=split(' ', shift);
1098
1099         my (@spec, @skip);
1100         foreach my $glob (@globlist) {
1101                 if ($glob=~/^!(.*)/) {
1102                         push @skip, $glob;
1103                 }
1104                 else {
1105                         push @spec, $glob;
1106                 }
1107         }
1108
1109         my $spec=join(' or ', @spec);
1110         if (@skip) {
1111                 my $skip=join(' and ', @skip);
1112                 if (length $spec) {
1113                         $spec="$skip and ($spec)";
1114                 }
1115                 else {
1116                         $spec=$skip;
1117                 }
1118         }
1119         return $spec;
1120 } #}}}
1121
1122 sub is_globlist ($) { #{{{
1123         my $s=shift;
1124         return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1125 } #}}}
1126
1127 sub safequote ($) { #{{{
1128         my $s=shift;
1129         $s=~s/[{}]//g;
1130         return "q{$s}";
1131 } #}}}
1132
1133 sub add_depends ($$) { #{{{
1134         my $page=shift;
1135         my $pagespec=shift;
1136         
1137         return unless pagespec_valid($pagespec);
1138
1139         if (! exists $depends{$page}) {
1140                 $depends{$page}=$pagespec;
1141         }
1142         else {
1143                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1144         }
1145
1146         return 1;
1147 } # }}}
1148
1149 sub file_pruned ($$) { #{{{
1150         require File::Spec;
1151         my $file=File::Spec->canonpath(shift);
1152         my $base=File::Spec->canonpath(shift);
1153         $file =~ s#^\Q$base\E/+##;
1154
1155         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1156         return $file =~ m/$regexp/ && $file ne $base;
1157 } #}}}
1158
1159 sub gettext { #{{{
1160         # Only use gettext in the rare cases it's needed.
1161         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1162             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1163             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1164                 if (! $gettext_obj) {
1165                         $gettext_obj=eval q{
1166                                 use Locale::gettext q{textdomain};
1167                                 Locale::gettext->domain('ikiwiki')
1168                         };
1169                         if ($@) {
1170                                 print STDERR "$@";
1171                                 $gettext_obj=undef;
1172                                 return shift;
1173                         }
1174                 }
1175                 return $gettext_obj->get(shift);
1176         }
1177         else {
1178                 return shift;
1179         }
1180 } #}}}
1181
1182 sub pagespec_merge ($$) { #{{{
1183         my $a=shift;
1184         my $b=shift;
1185
1186         return $a if $a eq $b;
1187
1188         # Support for old-style GlobLists.
1189         if (is_globlist($a)) {
1190                 $a=globlist_to_pagespec($a);
1191         }
1192         if (is_globlist($b)) {
1193                 $b=globlist_to_pagespec($b);
1194         }
1195
1196         return "($a) or ($b)";
1197 } #}}}
1198
1199 sub pagespec_translate ($) { #{{{
1200         my $spec=shift;
1201
1202         # Support for old-style GlobLists.
1203         if (is_globlist($spec)) {
1204                 $spec=globlist_to_pagespec($spec);
1205         }
1206
1207         # Convert spec to perl code.
1208         my $code="";
1209         while ($spec=~m{
1210                 \s*             # ignore whitespace
1211                 (               # 1: match a single word
1212                         \!              # !
1213                 |
1214                         \(              # (
1215                 |
1216                         \)              # )
1217                 |
1218                         \w+\([^\)]*\)   # command(params)
1219                 |
1220                         [^\s()]+        # any other text
1221                 )
1222                 \s*             # ignore whitespace
1223         }igx) {
1224                 my $word=$1;
1225                 if (lc $word eq 'and') {
1226                         $code.=' &&';
1227                 }
1228                 elsif (lc $word eq 'or') {
1229                         $code.=' ||';
1230                 }
1231                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1232                         $code.=' '.$word;
1233                 }
1234                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1235                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1236                                 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1237                         }
1238                         else {
1239                                 $code.=' 0';
1240                         }
1241                 }
1242                 else {
1243                         $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1244                 }
1245         }
1246
1247         return eval 'sub { my $page=shift; '.$code.' }';
1248 } #}}}
1249
1250 sub pagespec_match ($$;@) { #{{{
1251         my $page=shift;
1252         my $spec=shift;
1253         my @params=@_;
1254
1255         # Backwards compatability with old calling convention.
1256         if (@params == 1) {
1257                 unshift @params, 'location';
1258         }
1259
1260         my $sub=pagespec_translate($spec);
1261         return IkiWiki::FailReason->new('syntax error') if $@;
1262         return $sub->($page, @params);
1263 } #}}}
1264
1265 sub pagespec_valid ($) { #{{{
1266         my $spec=shift;
1267
1268         my $sub=pagespec_translate($spec);
1269         return ! $@;
1270 } #}}}
1271
1272 package IkiWiki::FailReason;
1273
1274 use overload ( #{{{
1275         '""'    => sub { ${$_[0]} },
1276         '0+'    => sub { 0 },
1277         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1278         fallback => 1,
1279 ); #}}}
1280
1281 sub new { #{{{
1282         return bless \$_[1], $_[0];
1283 } #}}}
1284
1285 package IkiWiki::SuccessReason;
1286
1287 use overload ( #{{{
1288         '""'    => sub { ${$_[0]} },
1289         '0+'    => sub { 1 },
1290         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
1291         fallback => 1,
1292 ); #}}}
1293
1294 sub new { #{{{
1295         return bless \$_[1], $_[0];
1296 }; #}}}
1297
1298 package IkiWiki::PageSpec;
1299
1300 sub match_glob ($$;@) { #{{{
1301         my $page=shift;
1302         my $glob=shift;
1303         my %params=@_;
1304         
1305         my $from=exists $params{location} ? $params{location} : '';
1306         
1307         # relative matching
1308         if ($glob =~ m!^\./!) {
1309                 $from=~s#/?[^/]+$##;
1310                 $glob=~s#^\./##;
1311                 $glob="$from/$glob" if length $from;
1312         }
1313
1314         # turn glob into safe regexp
1315         $glob=quotemeta($glob);
1316         $glob=~s/\\\*/.*/g;
1317         $glob=~s/\\\?/./g;
1318
1319         if ($page=~/^$glob$/i) {
1320                 if (! IkiWiki::isinternal($page) || $params{internal}) {
1321                         return IkiWiki::SuccessReason->new("$glob matches $page");
1322                 }
1323                 else {
1324                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1325                 }
1326         }
1327         else {
1328                 return IkiWiki::FailReason->new("$glob does not match $page");
1329         }
1330 } #}}}
1331
1332 sub match_internal ($$;@) { #{{{
1333         return match_glob($_[0], $_[1], @_, internal => 1)
1334 } #}}}
1335
1336 sub match_link ($$;@) { #{{{
1337         my $page=shift;
1338         my $link=lc(shift);
1339         my %params=@_;
1340
1341         my $from=exists $params{location} ? $params{location} : '';
1342
1343         # relative matching
1344         if ($link =~ m!^\.! && defined $from) {
1345                 $from=~s#/?[^/]+$##;
1346                 $link=~s#^\./##;
1347                 $link="$from/$link" if length $from;
1348         }
1349
1350         my $links = $IkiWiki::links{$page};
1351         return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1352         my $bestlink = IkiWiki::bestlink($from, $link);
1353         foreach my $p (@{$links}) {
1354                 if (length $bestlink) {
1355                         return IkiWiki::SuccessReason->new("$page links to $link")
1356                                 if $bestlink eq IkiWiki::bestlink($page, $p);
1357                 }
1358                 else {
1359                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1360                                 if match_glob($p, $link, %params);
1361                 }
1362         }
1363         return IkiWiki::FailReason->new("$page does not link to $link");
1364 } #}}}
1365
1366 sub match_backlink ($$;@) { #{{{
1367         return match_link($_[1], $_[0], @_);
1368 } #}}}
1369
1370 sub match_created_before ($$;@) { #{{{
1371         my $page=shift;
1372         my $testpage=shift;
1373
1374         if (exists $IkiWiki::pagectime{$testpage}) {
1375                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1376                         return IkiWiki::SuccessReason->new("$page created before $testpage");
1377                 }
1378                 else {
1379                         return IkiWiki::FailReason->new("$page not created before $testpage");
1380                 }
1381         }
1382         else {
1383                 return IkiWiki::FailReason->new("$testpage has no ctime");
1384         }
1385 } #}}}
1386
1387 sub match_created_after ($$;@) { #{{{
1388         my $page=shift;
1389         my $testpage=shift;
1390
1391         if (exists $IkiWiki::pagectime{$testpage}) {
1392                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1393                         return IkiWiki::SuccessReason->new("$page created after $testpage");
1394                 }
1395                 else {
1396                         return IkiWiki::FailReason->new("$page not created after $testpage");
1397                 }
1398         }
1399         else {
1400                 return IkiWiki::FailReason->new("$testpage has no ctime");
1401         }
1402 } #}}}
1403
1404 sub match_creation_day ($$;@) { #{{{
1405         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1406                 return IkiWiki::SuccessReason->new('creation_day matched');
1407         }
1408         else {
1409                 return IkiWiki::FailReason->new('creation_day did not match');
1410         }
1411 } #}}}
1412
1413 sub match_creation_month ($$;@) { #{{{
1414         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1415                 return IkiWiki::SuccessReason->new('creation_month matched');
1416         }
1417         else {
1418                 return IkiWiki::FailReason->new('creation_month did not match');
1419         }
1420 } #}}}
1421
1422 sub match_creation_year ($$;@) { #{{{
1423         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1424                 return IkiWiki::SuccessReason->new('creation_year matched');
1425         }
1426         else {
1427                 return IkiWiki::FailReason->new('creation_year did not match');
1428         }
1429 } #}}}
1430
1431 1