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