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