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