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