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