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