]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki.pm
update news item, note this is a security fix release
[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         if ($config{usedirs}) {
518                 $url =~ s!/index.$config{htmlext}$!/!;
519         }
520         $url =~ s!^$!./!; # Browsers don't like empty links...
521
522         return $url;
523 } #}}}
524
525 sub urlto ($$) { #{{{
526         my $to=shift;
527         my $from=shift;
528
529         if (! length $to) {
530                 return beautify_url(baseurl($from));
531         }
532
533         if (! $destsources{$to}) {
534                 $to=htmlpage($to);
535         }
536
537         my $link = abs2rel($to, dirname(htmlpage($from)));
538
539         return beautify_url($link);
540 } #}}}
541
542 sub htmllink ($$$;@) { #{{{
543         my $lpage=shift; # the page doing the linking
544         my $page=shift; # the page that will contain the link (different for inline)
545         my $link=shift;
546         my %opts=@_;
547
548         $link=~s/\/$//;
549
550         my $bestlink;
551         if (! $opts{forcesubpage}) {
552                 $bestlink=bestlink($lpage, $link);
553         }
554         else {
555                 $bestlink="$lpage/".lc($link);
556         }
557
558         my $linktext;
559         if (defined $opts{linktext}) {
560                 $linktext=$opts{linktext};
561         }
562         else {
563                 $linktext=pagetitle(basename($link));
564         }
565         
566         return "<span class=\"selflink\">$linktext</span>"
567                 if length $bestlink && $page eq $bestlink &&
568                    ! defined $opts{anchor};
569         
570         if (! $destsources{$bestlink}) {
571                 $bestlink=htmlpage($bestlink);
572
573                 if (! $destsources{$bestlink}) {
574                         return $linktext unless length $config{cgiurl};
575                         return "<span class=\"createlink\"><a href=\"".
576                                 cgiurl(
577                                         do => "create",
578                                         page => pagetitle(lc($link), 1),
579                                         from => $lpage
580                                 ).
581                                 "\">?</a>$linktext</span>"
582                 }
583         }
584         
585         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
586         $bestlink=beautify_url($bestlink);
587         
588         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
589                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
590         }
591
592         if (defined $opts{anchor}) {
593                 $bestlink.="#".$opts{anchor};
594         }
595
596         my @attrs;
597         if (defined $opts{rel}) {
598                 push @attrs, ' rel="'.$opts{rel}.'"';
599         }
600         if (defined $opts{class}) {
601                 push @attrs, ' class="'.$opts{class}.'"';
602         }
603
604         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
605 } #}}}
606
607 sub htmlize ($$$) { #{{{
608         my $page=shift;
609         my $type=shift;
610         my $content=shift;
611
612         if (exists $hooks{htmlize}{$type}) {
613                 $content=$hooks{htmlize}{$type}{call}->(
614                         page => $page,
615                         content => $content,
616                 );
617         }
618         else {
619                 error("htmlization of $type not supported");
620         }
621
622         run_hooks(sanitize => sub {
623                 $content=shift->(
624                         page => $page,
625                         content => $content,
626                 );
627         });
628
629         return $content;
630 } #}}}
631
632 sub linkify ($$$) { #{{{
633         my $lpage=shift; # the page containing the links
634         my $page=shift; # the page the link will end up on (different for inline)
635         my $content=shift;
636
637         $content =~ s{(\\?)$config{wiki_link_regexp}}{
638                 defined $2
639                         ? ( $1 
640                                 ? "[[$2|$3".($4 ? "#$4" : "")."]]" 
641                                 : htmllink($lpage, $page, linkpage($3),
642                                         anchor => $4, linktext => pagetitle($2)))
643                         : ( $1 
644                                 ? "[[$3".($4 ? "#$4" : "")."]]"
645                                 : htmllink($lpage, $page, linkpage($3),
646                                         anchor => $4))
647         }eg;
648         
649         return $content;
650 } #}}}
651
652 my %preprocessing;
653 our $preprocess_preview=0;
654 sub preprocess ($$$;$$) { #{{{
655         my $page=shift; # the page the data comes from
656         my $destpage=shift; # the page the data will appear in (different for inline)
657         my $content=shift;
658         my $scan=shift;
659         my $preview=shift;
660
661         # Using local because it needs to be set within any nested calls
662         # of this function.
663         local $preprocess_preview=$preview if defined $preview;
664
665         my $handle=sub {
666                 my $escape=shift;
667                 my $command=shift;
668                 my $params=shift;
669                 if (length $escape) {
670                         return "[[$command $params]]";
671                 }
672                 elsif (exists $hooks{preprocess}{$command}) {
673                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
674                         # Note: preserve order of params, some plugins may
675                         # consider it significant.
676                         my @params;
677                         while ($params =~ m{
678                                 (?:(\w+)=)?             # 1: named parameter key?
679                                 (?:
680                                         """(.*?)"""     # 2: triple-quoted value
681                                 |
682                                         "([^"]+)"       # 3: single-quoted value
683                                 |
684                                         (\S+)           # 4: unquoted value
685                                 )
686                                 (?:\s+|$)               # delimiter to next param
687                         }sgx) {
688                                 my $key=$1;
689                                 my $val;
690                                 if (defined $2) {
691                                         $val=$2;
692                                         $val=~s/\r\n/\n/mg;
693                                         $val=~s/^\n+//g;
694                                         $val=~s/\n+$//g;
695                                 }
696                                 elsif (defined $3) {
697                                         $val=$3;
698                                 }
699                                 elsif (defined $4) {
700                                         $val=$4;
701                                 }
702
703                                 if (defined $key) {
704                                         push @params, $key, $val;
705                                 }
706                                 else {
707                                         push @params, $val, '';
708                                 }
709                         }
710                         if ($preprocessing{$page}++ > 3) {
711                                 # Avoid loops of preprocessed pages preprocessing
712                                 # other pages that preprocess them, etc.
713                                 #translators: The first parameter is a
714                                 #translators: preprocessor directive name,
715                                 #translators: the second a page name, the
716                                 #translators: third a number.
717                                 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
718                                         $command, $page, $preprocessing{$page}).
719                                 "]]";
720                         }
721                         my $ret=$hooks{preprocess}{$command}{call}->(
722                                 @params,
723                                 page => $page,
724                                 destpage => $destpage,
725                                 preview => $preprocess_preview,
726                         );
727                         $preprocessing{$page}--;
728                         return $ret;
729                 }
730                 else {
731                         return "[[$command $params]]";
732                 }
733         };
734         
735         $content =~ s{
736                 (\\?)           # 1: escape?
737                 \[\[            # directive open
738                 (\w+)           # 2: command
739                 \s+
740                 (               # 3: the parameters..
741                         (?:
742                                 (?:\w+=)?               # named parameter key?
743                                 (?:
744                                         """.*?"""       # triple-quoted value
745                                         |
746                                         "[^"]+"         # single-quoted value
747                                         |
748                                         [^\s\]]+        # unquoted value
749                                 )
750                                 \s*                     # whitespace or end
751                                                         # of directive
752                         )
753                 *)              # 0 or more parameters
754                 \]\]            # directive closed
755         }{$handle->($1, $2, $3)}sexg;
756         return $content;
757 } #}}}
758
759 sub filter ($$$) { #{{{
760         my $page=shift;
761         my $destpage=shift;
762         my $content=shift;
763
764         run_hooks(filter => sub {
765                 $content=shift->(page => $page, destpage => $destpage, 
766                         content => $content);
767         });
768
769         return $content;
770 } #}}}
771
772 sub indexlink () { #{{{
773         return "<a href=\"$config{url}\">$config{wikiname}</a>";
774 } #}}}
775
776 my $wikilock;
777
778 sub lockwiki (;$) { #{{{
779         my $wait=@_ ? shift : 1;
780         # Take an exclusive lock on the wiki to prevent multiple concurrent
781         # run issues. The lock will be dropped on program exit.
782         if (! -d $config{wikistatedir}) {
783                 mkdir($config{wikistatedir});
784         }
785         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
786                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
787         if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
788                 if ($wait) {
789                         debug("wiki seems to be locked, waiting for lock");
790                         my $wait=600; # arbitrary, but don't hang forever to 
791                                       # prevent process pileup
792                         for (1..$wait) {
793                                 return if flock($wikilock, 2 | 4);
794                                 sleep 1;
795                         }
796                         error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
797                 }
798                 else {
799                         return 0;
800                 }
801         }
802         return 1;
803 } #}}}
804
805 sub unlockwiki () { #{{{
806         return close($wikilock) if $wikilock;
807         return;
808 } #}}}
809
810 my $commitlock;
811
812 sub commit_hook_enabled () { #{{{
813         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
814                 error("cannot write to $config{wikistatedir}/commitlock: $!");
815         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
816                 close($commitlock) || error("failed closing commitlock: $!");
817                 return 0;
818         }
819         close($commitlock) || error("failed closing commitlock: $!");
820         return 1;
821 } #}}}
822
823 sub disable_commit_hook () { #{{{
824         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
825                 error("cannot write to $config{wikistatedir}/commitlock: $!");
826         if (! flock($commitlock, 2)) { # LOCK_EX
827                 error("failed to get commit lock");
828         }
829         return 1;
830 } #}}}
831
832 sub enable_commit_hook () { #{{{
833         return close($commitlock) if $commitlock;
834         return;
835 } #}}}
836
837 sub loadindex () { #{{{
838         %oldrenderedfiles=%pagectime=();
839         if (! $config{rebuild}) {
840                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
841                         %destsources=%renderedfiles=%pagecase=();
842         }
843         open (my $in, "<", "$config{wikistatedir}/index") || return;
844         while (<$in>) {
845                 $_=possibly_foolish_untaint($_);
846                 chomp;
847                 my %items;
848                 $items{link}=[];
849                 $items{dest}=[];
850                 foreach my $i (split(/ /, $_)) {
851                         my ($item, $val)=split(/=/, $i, 2);
852                         push @{$items{$item}}, decode_entities($val);
853                 }
854
855                 next unless exists $items{src}; # skip bad lines for now
856
857                 my $page=pagename($items{src}[0]);
858                 if (! $config{rebuild}) {
859                         $pagesources{$page}=$items{src}[0];
860                         $pagemtime{$page}=$items{mtime}[0];
861                         $oldlinks{$page}=[@{$items{link}}];
862                         $links{$page}=[@{$items{link}}];
863                         $depends{$page}=$items{depends}[0] if exists $items{depends};
864                         $destsources{$_}=$page foreach @{$items{dest}};
865                         $renderedfiles{$page}=[@{$items{dest}}];
866                         $pagecase{lc $page}=$page;
867                 }
868                 $oldrenderedfiles{$page}=[@{$items{dest}}];
869                 $pagectime{$page}=$items{ctime}[0];
870         }
871         return close($in);
872 } #}}}
873
874 sub saveindex () { #{{{
875         run_hooks(savestate => sub { shift->() });
876
877         if (! -d $config{wikistatedir}) {
878                 mkdir($config{wikistatedir});
879         }
880         my $newfile="$config{wikistatedir}/index.new";
881         my $cleanup = sub { unlink($newfile) };
882         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
883         foreach my $page (keys %pagemtime) {
884                 next unless $pagemtime{$page};
885                 my $line="mtime=$pagemtime{$page} ".
886                         "ctime=$pagectime{$page} ".
887                         "src=$pagesources{$page}";
888                 $line.=" dest=$_" foreach @{$renderedfiles{$page}};
889                 my %count;
890                 $line.=" link=$_" foreach grep { ++$count{$_} == 1 } @{$links{$page}};
891                 if (exists $depends{$page}) {
892                         $line.=" depends=".encode_entities($depends{$page}, " \t\n");
893                 }
894                 print $out $line."\n" || error("failed writing to $newfile: $!", $cleanup);
895         }
896         close $out || error("failed saving to $newfile: $!", $cleanup);
897         rename($newfile, "$config{wikistatedir}/index") ||
898                 error("failed renaming $newfile to $config{wikistatedir}/index", $cleanup);
899         
900         return 1;
901 } #}}}
902
903 sub template_file ($) { #{{{
904         my $template=shift;
905
906         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
907                 return "$dir/$template" if -e "$dir/$template";
908         }
909         return;
910 } #}}}
911
912 sub template_params (@) { #{{{
913         my $filename=template_file(shift);
914
915         if (! defined $filename) {
916                 return if wantarray;
917                 return "";
918         }
919
920         my @ret=(
921                 filter => sub {
922                         my $text_ref = shift;
923                         ${$text_ref} = decode_utf8(${$text_ref});
924                 },
925                 filename => $filename,
926                 loop_context_vars => 1,
927                 die_on_bad_params => 0,
928                 @_
929         );
930         return wantarray ? @ret : {@ret};
931 } #}}}
932
933 sub template ($;@) { #{{{
934         require HTML::Template;
935         return HTML::Template->new(template_params(@_));
936 } #}}}
937
938 sub misctemplate ($$;@) { #{{{
939         my $title=shift;
940         my $pagebody=shift;
941         
942         my $template=template("misc.tmpl");
943         $template->param(
944                 title => $title,
945                 indexlink => indexlink(),
946                 wikiname => $config{wikiname},
947                 pagebody => $pagebody,
948                 baseurl => baseurl(),
949                 @_,
950         );
951         run_hooks(pagetemplate => sub {
952                 shift->(page => "", destpage => "", template => $template);
953         });
954         return $template->output;
955 }#}}}
956
957 sub hook (@) { # {{{
958         my %param=@_;
959         
960         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
961                 error 'hook requires type, call, and id parameters';
962         }
963
964         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
965         
966         $hooks{$param{type}}{$param{id}}=\%param;
967         return 1;
968 } # }}}
969
970 sub run_hooks ($$) { # {{{
971         # Calls the given sub for each hook of the given type,
972         # passing it the hook function to call.
973         my $type=shift;
974         my $sub=shift;
975
976         if (exists $hooks{$type}) {
977                 my @deferred;
978                 foreach my $id (keys %{$hooks{$type}}) {
979                         if ($hooks{$type}{$id}{last}) {
980                                 push @deferred, $id;
981                                 next;
982                         }
983                         $sub->($hooks{$type}{$id}{call});
984                 }
985                 foreach my $id (@deferred) {
986                         $sub->($hooks{$type}{$id}{call});
987                 }
988         }
989
990         return 1;
991 } #}}}
992
993 sub globlist_to_pagespec ($) { #{{{
994         my @globlist=split(' ', shift);
995
996         my (@spec, @skip);
997         foreach my $glob (@globlist) {
998                 if ($glob=~/^!(.*)/) {
999                         push @skip, $glob;
1000                 }
1001                 else {
1002                         push @spec, $glob;
1003                 }
1004         }
1005
1006         my $spec=join(' or ', @spec);
1007         if (@skip) {
1008                 my $skip=join(' and ', @skip);
1009                 if (length $spec) {
1010                         $spec="$skip and ($spec)";
1011                 }
1012                 else {
1013                         $spec=$skip;
1014                 }
1015         }
1016         return $spec;
1017 } #}}}
1018
1019 sub is_globlist ($) { #{{{
1020         my $s=shift;
1021         return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1022 } #}}}
1023
1024 sub safequote ($) { #{{{
1025         my $s=shift;
1026         $s=~s/[{}]//g;
1027         return "q{$s}";
1028 } #}}}
1029
1030 sub add_depends ($$) { #{{{
1031         my $page=shift;
1032         my $pagespec=shift;
1033         
1034         if (! exists $depends{$page}) {
1035                 $depends{$page}=$pagespec;
1036         }
1037         else {
1038                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1039         }
1040
1041         return 1;
1042 } # }}}
1043
1044 sub file_pruned ($$) { #{{{
1045         require File::Spec;
1046         my $file=File::Spec->canonpath(shift);
1047         my $base=File::Spec->canonpath(shift);
1048         $file =~ s#^\Q$base\E/*##;
1049
1050         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1051         return $file =~ m/$regexp/;
1052 } #}}}
1053
1054 sub gettext { #{{{
1055         # Only use gettext in the rare cases it's needed.
1056         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1057             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1058             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1059                 if (! $gettext_obj) {
1060                         $gettext_obj=eval q{
1061                                 use Locale::gettext q{textdomain};
1062                                 Locale::gettext->domain('ikiwiki')
1063                         };
1064                         if ($@) {
1065                                 print STDERR "$@";
1066                                 $gettext_obj=undef;
1067                                 return shift;
1068                         }
1069                 }
1070                 return $gettext_obj->get(shift);
1071         }
1072         else {
1073                 return shift;
1074         }
1075 } #}}}
1076
1077 sub pagespec_merge ($$) { #{{{
1078         my $a=shift;
1079         my $b=shift;
1080
1081         return $a if $a eq $b;
1082
1083         # Support for old-style GlobLists.
1084         if (is_globlist($a)) {
1085                 $a=globlist_to_pagespec($a);
1086         }
1087         if (is_globlist($b)) {
1088                 $b=globlist_to_pagespec($b);
1089         }
1090
1091         return "($a) or ($b)";
1092 } #}}}
1093
1094 sub pagespec_translate ($) { #{{{
1095         # This assumes that $page is in scope in the function
1096         # that evalulates the translated pagespec code.
1097         my $spec=shift;
1098
1099         # Support for old-style GlobLists.
1100         if (is_globlist($spec)) {
1101                 $spec=globlist_to_pagespec($spec);
1102         }
1103
1104         # Convert spec to perl code.
1105         my $code="";
1106         while ($spec=~m{
1107                 \s*             # ignore whitespace
1108                 (               # 1: match a single word
1109                         \!              # !
1110                 |
1111                         \(              # (
1112                 |
1113                         \)              # )
1114                 |
1115                         \w+\([^\)]*\)   # command(params)
1116                 |
1117                         [^\s()]+        # any other text
1118                 )
1119                 \s*             # ignore whitespace
1120         }igx) {
1121                 my $word=$1;
1122                 if (lc $word eq 'and') {
1123                         $code.=' &&';
1124                 }
1125                 elsif (lc $word eq 'or') {
1126                         $code.=' ||';
1127                 }
1128                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1129                         $code.=' '.$word;
1130                 }
1131                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1132                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1133                                 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@params)";
1134                         }
1135                         else {
1136                                 $code.=' 0';
1137                         }
1138                 }
1139                 else {
1140                         $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@params)";
1141                 }
1142         }
1143
1144         return $code;
1145 } #}}}
1146
1147 sub pagespec_match ($$;@) { #{{{
1148         my $page=shift;
1149         my $spec=shift;
1150         my @params=@_;
1151
1152         # Backwards compatability with old calling convention.
1153         if (@params == 1) {
1154                 unshift @params, 'location';
1155         }
1156
1157         my $ret=eval pagespec_translate($spec);
1158         return IkiWiki::FailReason->new('syntax error') if $@;
1159         return $ret;
1160 } #}}}
1161
1162 package IkiWiki::FailReason;
1163
1164 use overload ( #{{{
1165         '""'    => sub { ${$_[0]} },
1166         '0+'    => sub { 0 },
1167         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1168         fallback => 1,
1169 ); #}}}
1170
1171 sub new { #{{{
1172         return bless \$_[1], $_[0];
1173 } #}}}
1174
1175 package IkiWiki::SuccessReason;
1176
1177 use overload ( #{{{
1178         '""'    => sub { ${$_[0]} },
1179         '0+'    => sub { 1 },
1180         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
1181         fallback => 1,
1182 ); #}}}
1183
1184 sub new { #{{{
1185         return bless \$_[1], $_[0];
1186 }; #}}}
1187
1188 package IkiWiki::PageSpec;
1189
1190 sub match_glob ($$;@) { #{{{
1191         my $page=shift;
1192         my $glob=shift;
1193         my %params=@_;
1194         
1195         my $from=exists $params{location} ? $params{location} : '';
1196         
1197         # relative matching
1198         if ($glob =~ m!^\./!) {
1199                 $from=~s#/?[^/]+$##;
1200                 $glob=~s#^\./##;
1201                 $glob="$from/$glob" if length $from;
1202         }
1203
1204         # turn glob into safe regexp
1205         $glob=quotemeta($glob);
1206         $glob=~s/\\\*/.*/g;
1207         $glob=~s/\\\?/./g;
1208
1209         if ($page=~/^$glob$/i) {
1210                 return IkiWiki::SuccessReason->new("$glob matches $page");
1211         }
1212         else {
1213                 return IkiWiki::FailReason->new("$glob does not match $page");
1214         }
1215 } #}}}
1216
1217 sub match_link ($$;@) { #{{{
1218         my $page=shift;
1219         my $link=lc(shift);
1220         my %params=@_;
1221
1222         my $from=exists $params{location} ? $params{location} : '';
1223
1224         # relative matching
1225         if ($link =~ m!^\.! && defined $from) {
1226                 $from=~s#/?[^/]+$##;
1227                 $link=~s#^\./##;
1228                 $link="$from/$link" if length $from;
1229         }
1230
1231         my $links = $IkiWiki::links{$page};
1232         return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1233         my $bestlink = IkiWiki::bestlink($from, $link);
1234         foreach my $p (@{$links}) {
1235                 if (length $bestlink) {
1236                         return IkiWiki::SuccessReason->new("$page links to $link")
1237                                 if $bestlink eq IkiWiki::bestlink($page, $p);
1238                 }
1239                 else {
1240                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1241                                 if match_glob($p, $link, %params);
1242                 }
1243         }
1244         return IkiWiki::FailReason->new("$page does not link to $link");
1245 } #}}}
1246
1247 sub match_backlink ($$;@) { #{{{
1248         return match_link($_[1], $_[0], @_);
1249 } #}}}
1250
1251 sub match_created_before ($$;@) { #{{{
1252         my $page=shift;
1253         my $testpage=shift;
1254
1255         if (exists $IkiWiki::pagectime{$testpage}) {
1256                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1257                         return IkiWiki::SuccessReason->new("$page created before $testpage");
1258                 }
1259                 else {
1260                         return IkiWiki::FailReason->new("$page not created before $testpage");
1261                 }
1262         }
1263         else {
1264                 return IkiWiki::FailReason->new("$testpage has no ctime");
1265         }
1266 } #}}}
1267
1268 sub match_created_after ($$;@) { #{{{
1269         my $page=shift;
1270         my $testpage=shift;
1271
1272         if (exists $IkiWiki::pagectime{$testpage}) {
1273                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1274                         return IkiWiki::SuccessReason->new("$page created after $testpage");
1275                 }
1276                 else {
1277                         return IkiWiki::FailReason->new("$page not created after $testpage");
1278                 }
1279         }
1280         else {
1281                 return IkiWiki::FailReason->new("$testpage has no ctime");
1282         }
1283 } #}}}
1284
1285 sub match_creation_day ($$;@) { #{{{
1286         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1287                 return IkiWiki::SuccessReason->new('creation_day matched');
1288         }
1289         else {
1290                 return IkiWiki::FailReason->new('creation_day did not match');
1291         }
1292 } #}}}
1293
1294 sub match_creation_month ($$;@) { #{{{
1295         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1296                 return IkiWiki::SuccessReason->new('creation_month matched');
1297         }
1298         else {
1299                 return IkiWiki::FailReason->new('creation_month did not match');
1300         }
1301 } #}}}
1302
1303 sub match_creation_year ($$;@) { #{{{
1304         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1305                 return IkiWiki::SuccessReason->new('creation_year matched');
1306         }
1307         else {
1308                 return IkiWiki::FailReason->new('creation_year did not match');
1309         }
1310 } #}}}
1311
1312 sub match_user ($$;@) { #{{{
1313         shift;
1314         my $user=shift;
1315         my %params=@_;
1316
1317         return IkiWiki::FailReason->new('cannot match user')
1318                 unless exists $params{user};
1319         if ($user eq $params{user}) {
1320                 return IkiWiki::SuccessReason->new("user is $user")
1321         }
1322         else {
1323                 return IkiWiki::FailReason->new("user is not $user");
1324         }
1325 } #}}}
1326
1327 1