is this in fact WONTFIX?
[ikiwiki] / IkiWiki.pm
1 #!/usr/bin/perl
2
3 package IkiWiki;
4
5 use warnings;
6 use strict;
7 use Encode;
8 use HTML::Entities;
9 use URI::Escape q{uri_escape_utf8};
10 use POSIX;
11 use Storable;
12 use open qw{:utf8 :std};
13
14 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
15             %pagestate %wikistate %renderedfiles %oldrenderedfiles
16             %pagesources %destsources %depends %hooks %forcerebuild
17             %loaded_plugins};
18
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
21                  pagespec_match_list bestlink htmllink readfile writefile
22                  pagetype srcfile pagename displaytime will_render gettext urlto
23                  targetpage add_underlay pagetitle titlepage linkpage
24                  newpagefile inject add_link
25                  %config %links %pagestate %wikistate %renderedfiles
26                  %pagesources %destsources);
27 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
28 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
29 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
30
31 # Optimisation.
32 use Memoize;
33 memoize("abs2rel");
34 memoize("pagespec_translate");
35 memoize("file_pruned");
36
37 sub getsetup () {
38         wikiname => {
39                 type => "string",
40                 default => "wiki",
41                 description => "name of the wiki",
42                 safe => 1,
43                 rebuild => 1,
44         },
45         adminemail => {
46                 type => "string",
47                 default => undef,
48                 example => 'me@example.com',
49                 description => "contact email for wiki",
50                 safe => 1,
51                 rebuild => 0,
52         },
53         adminuser => {
54                 type => "string",
55                 default => [],
56                 description => "users who are wiki admins",
57                 safe => 1,
58                 rebuild => 0,
59         },
60         banned_users => {
61                 type => "string",
62                 default => [],
63                 description => "users who are banned from the wiki",
64                 safe => 1,
65                 rebuild => 0,
66         },
67         srcdir => {
68                 type => "string",
69                 default => undef,
70                 example => "$ENV{HOME}/wiki",
71                 description => "where the source of the wiki is located",
72                 safe => 0, # path
73                 rebuild => 1,
74         },
75         destdir => {
76                 type => "string",
77                 default => undef,
78                 example => "/var/www/wiki",
79                 description => "where to build the wiki",
80                 safe => 0, # path
81                 rebuild => 1,
82         },
83         url => {
84                 type => "string",
85                 default => '',
86                 example => "http://example.com/wiki",
87                 description => "base url to the wiki",
88                 safe => 1,
89                 rebuild => 1,
90         },
91         cgiurl => {
92                 type => "string",
93                 default => '',
94                 example => "http://example.com/wiki/ikiwiki.cgi",
95                 description => "url to the ikiwiki.cgi",
96                 safe => 1,
97                 rebuild => 1,
98         },
99         cgi_wrapper => {
100                 type => "string",
101                 default => '',
102                 example => "/var/www/wiki/ikiwiki.cgi",
103                 description => "filename of cgi wrapper to generate",
104                 safe => 0, # file
105                 rebuild => 0,
106         },
107         cgi_wrappermode => {
108                 type => "string",
109                 default => '06755',
110                 description => "mode for cgi_wrapper (can safely be made suid)",
111                 safe => 0,
112                 rebuild => 0,
113         },
114         rcs => {
115                 type => "string",
116                 default => '',
117                 description => "rcs backend to use",
118                 safe => 0, # don't allow overriding
119                 rebuild => 0,
120         },
121         default_plugins => {
122                 type => "internal",
123                 default => [qw{mdwn link inline meta htmlscrubber passwordauth
124                                 openid signinedit lockedit conditional
125                                 recentchanges parentlinks editpage}],
126                 description => "plugins to enable by default",
127                 safe => 0,
128                 rebuild => 1,
129         },
130         add_plugins => {
131                 type => "string",
132                 default => [],
133                 description => "plugins to add to the default configuration",
134                 safe => 1,
135                 rebuild => 1,
136         },
137         disable_plugins => {
138                 type => "string",
139                 default => [],
140                 description => "plugins to disable",
141                 safe => 1,
142                 rebuild => 1,
143         },
144         templatedir => {
145                 type => "string",
146                 default => "$installdir/share/ikiwiki/templates",
147                 description => "location of template files",
148                 advanced => 1,
149                 safe => 0, # path
150                 rebuild => 1,
151         },
152         underlaydir => {
153                 type => "string",
154                 default => "$installdir/share/ikiwiki/basewiki",
155                 description => "base wiki source location",
156                 advanced => 1,
157                 safe => 0, # path
158                 rebuild => 0,
159         },
160         underlaydirbase => {
161                 type => "internal",
162                 default => "$installdir/share/ikiwiki",
163                 description => "parent directory containing additional underlays",
164                 safe => 0,
165                 rebuild => 0,
166         },
167         wrappers => {
168                 type => "internal",
169                 default => [],
170                 description => "wrappers to generate",
171                 safe => 0,
172                 rebuild => 0,
173         },
174         underlaydirs => {
175                 type => "internal",
176                 default => [],
177                 description => "additional underlays to use",
178                 safe => 0,
179                 rebuild => 0,
180         },
181         verbose => {
182                 type => "boolean",
183                 example => 1,
184                 description => "display verbose messages?",
185                 safe => 1,
186                 rebuild => 0,
187         },
188         syslog => {
189                 type => "boolean",
190                 example => 1,
191                 description => "log to syslog?",
192                 safe => 1,
193                 rebuild => 0,
194         },
195         usedirs => {
196                 type => "boolean",
197                 default => 1,
198                 description => "create output files named page/index.html?",
199                 safe => 0, # changing requires manual transition
200                 rebuild => 1,
201         },
202         prefix_directives => {
203                 type => "boolean",
204                 default => 1,
205                 description => "use '!'-prefixed preprocessor directives?",
206                 safe => 0, # changing requires manual transition
207                 rebuild => 1,
208         },
209         indexpages => {
210                 type => "boolean",
211                 default => 0,
212                 description => "use page/index.mdwn source files",
213                 safe => 1,
214                 rebuild => 1,
215         },
216         discussion => {
217                 type => "boolean",
218                 default => 1,
219                 description => "enable Discussion pages?",
220                 safe => 1,
221                 rebuild => 1,
222         },
223         sslcookie => {
224                 type => "boolean",
225                 default => 0,
226                 description => "only send cookies over SSL connections?",
227                 advanced => 1,
228                 safe => 1,
229                 rebuild => 0,
230         },
231         default_pageext => {
232                 type => "string",
233                 default => "mdwn",
234                 description => "extension to use for new pages",
235                 safe => 0, # not sanitized
236                 rebuild => 0,
237         },
238         htmlext => {
239                 type => "string",
240                 default => "html",
241                 description => "extension to use for html files",
242                 safe => 0, # not sanitized
243                 rebuild => 1,
244         },
245         timeformat => {
246                 type => "string",
247                 default => '%c',
248                 description => "strftime format string to display date",
249                 advanced => 1,
250                 safe => 1,
251                 rebuild => 1,
252         },
253         locale => {
254                 type => "string",
255                 default => undef,
256                 example => "en_US.UTF-8",
257                 description => "UTF-8 locale to use",
258                 advanced => 1,
259                 safe => 0,
260                 rebuild => 1,
261         },
262         userdir => {
263                 type => "string",
264                 default => "",
265                 example => "users",
266                 description => "put user pages below specified page",
267                 safe => 1,
268                 rebuild => 1,
269         },
270         numbacklinks => {
271                 type => "integer",
272                 default => 10,
273                 description => "how many backlinks to show before hiding excess (0 to show all)",
274                 safe => 1,
275                 rebuild => 1,
276         },
277         hardlink => {
278                 type => "boolean",
279                 default => 0,
280                 description => "attempt to hardlink source files? (optimisation for large files)",
281                 advanced => 1,
282                 safe => 0, # paranoia
283                 rebuild => 0,
284         },
285         umask => {
286                 type => "integer",
287                 example => "022",
288                 description => "force ikiwiki to use a particular umask",
289                 advanced => 1,
290                 safe => 0, # paranoia
291                 rebuild => 0,
292         },
293         wrappergroup => {
294                 type => "string",
295                 example => "ikiwiki",
296                 description => "group for wrappers to run in",
297                 advanced => 1,
298                 safe => 0, # paranoia
299                 rebuild => 0,
300         },
301         libdir => {
302                 type => "string",
303                 default => "",
304                 example => "$ENV{HOME}/.ikiwiki/",
305                 description => "extra library and plugin directory",
306                 advanced => 1,
307                 safe => 0, # directory
308                 rebuild => 0,
309         },
310         ENV => {
311                 type => "string", 
312                 default => {},
313                 description => "environment variables",
314                 safe => 0, # paranoia
315                 rebuild => 0,
316         },
317         exclude => {
318                 type => "string",
319                 default => undef,
320                 example => '\.wav$',
321                 description => "regexp of source files to ignore",
322                 advanced => 1,
323                 safe => 0, # regexp
324                 rebuild => 1,
325         },
326         wiki_file_prune_regexps => {
327                 type => "internal",
328                 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
329                         qr/\.x?html?$/, qr/\.ikiwiki-new$/,
330                         qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
331                         qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
332                         qr/\.dpkg-tmp$/],
333                 description => "regexps of source files to ignore",
334                 safe => 0,
335                 rebuild => 1,
336         },
337         wiki_file_chars => {
338                 type => "string",
339                 description => "specifies the characters that are allowed in source filenames",
340                 default => "-[:alnum:]+/.:_",
341                 safe => 0,
342                 rebuild => 1,
343         },
344         wiki_file_regexp => {
345                 type => "internal",
346                 description => "regexp of legal source files",
347                 safe => 0,
348                 rebuild => 1,
349         },
350         web_commit_regexp => {
351                 type => "internal",
352                 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
353                 description => "regexp to parse web commits from logs",
354                 safe => 0,
355                 rebuild => 0,
356         },
357         cgi => {
358                 type => "internal",
359                 default => 0,
360                 description => "run as a cgi",
361                 safe => 0,
362                 rebuild => 0,
363         },
364         cgi_disable_uploads => {
365                 type => "internal",
366                 default => 1,
367                 description => "whether CGI should accept file uploads",
368                 safe => 0,
369                 rebuild => 0,
370         },
371         post_commit => {
372                 type => "internal",
373                 default => 0,
374                 description => "run as a post-commit hook",
375                 safe => 0,
376                 rebuild => 0,
377         },
378         rebuild => {
379                 type => "internal",
380                 default => 0,
381                 description => "running in rebuild mode",
382                 safe => 0,
383                 rebuild => 0,
384         },
385         setup => {
386                 type => "internal",
387                 default => undef,
388                 description => "running in setup mode",
389                 safe => 0,
390                 rebuild => 0,
391         },
392         refresh => {
393                 type => "internal",
394                 default => 0,
395                 description => "running in refresh mode",
396                 safe => 0,
397                 rebuild => 0,
398         },
399         test_receive => {
400                 type => "internal",
401                 default => 0,
402                 description => "running in receive test mode",
403                 safe => 0,
404                 rebuild => 0,
405         },
406         getctime => {
407                 type => "internal",
408                 default => 0,
409                 description => "running in getctime mode",
410                 safe => 0,
411                 rebuild => 0,
412         },
413         w3mmode => {
414                 type => "internal",
415                 default => 0,
416                 description => "running in w3mmode",
417                 safe => 0,
418                 rebuild => 0,
419         },
420         wikistatedir => {
421                 type => "internal",
422                 default => undef,
423                 description => "path to the .ikiwiki directory holding ikiwiki state",
424                 safe => 0,
425                 rebuild => 0,
426         },
427         setupfile => {
428                 type => "internal",
429                 default => undef,
430                 description => "path to setup file",
431                 safe => 0,
432                 rebuild => 0,
433         },
434         allow_symlinks_before_srcdir => {
435                 type => "boolean",
436                 default => 0,
437                 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
438                 safe => 0,
439                 rebuild => 0,
440         },
441 }
442
443 sub defaultconfig () {
444         my %s=getsetup();
445         my @ret;
446         foreach my $key (keys %s) {
447                 push @ret, $key, $s{$key}->{default};
448         }
449         use Data::Dumper;
450         return @ret;
451 }
452
453 sub checkconfig () {
454         # locale stuff; avoid LC_ALL since it overrides everything
455         if (defined $ENV{LC_ALL}) {
456                 $ENV{LANG} = $ENV{LC_ALL};
457                 delete $ENV{LC_ALL};
458         }
459         if (defined $config{locale}) {
460                 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
461                         $ENV{LANG}=$config{locale};
462                         define_gettext();
463                 }
464         }
465                 
466         if (! defined $config{wiki_file_regexp}) {
467                 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
468         }
469
470         if (ref $config{ENV} eq 'HASH') {
471                 foreach my $val (keys %{$config{ENV}}) {
472                         $ENV{$val}=$config{ENV}{$val};
473                 }
474         }
475
476         if ($config{w3mmode}) {
477                 eval q{use Cwd q{abs_path}};
478                 error($@) if $@;
479                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
480                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
481                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
482                         unless $config{cgiurl} =~ m!file:///!;
483                 $config{url}="file://".$config{destdir};
484         }
485
486         if ($config{cgi} && ! length $config{url}) {
487                 error(gettext("Must specify url to wiki with --url when using --cgi"));
488         }
489         
490         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
491                 unless exists $config{wikistatedir} && defined $config{wikistatedir};
492
493         if (defined $config{umask}) {
494                 umask(possibly_foolish_untaint($config{umask}));
495         }
496
497         run_hooks(checkconfig => sub { shift->() });
498
499         return 1;
500 }
501
502 sub listplugins () {
503         my %ret;
504
505         foreach my $dir (@INC, $config{libdir}) {
506                 next unless defined $dir && length $dir;
507                 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
508                         my ($plugin)=$file=~/.*\/(.*)\.pm$/;
509                         $ret{$plugin}=1;
510                 }
511         }
512         foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
513                 next unless defined $dir && length $dir;
514                 foreach my $file (glob("$dir/plugins/*")) {
515                         $ret{basename($file)}=1 if -x $file;
516                 }
517         }
518
519         return keys %ret;
520 }
521
522 sub loadplugins () {
523         if (defined $config{libdir} && length $config{libdir}) {
524                 unshift @INC, possibly_foolish_untaint($config{libdir});
525         }
526
527         foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
528                 loadplugin($plugin);
529         }
530         
531         if ($config{rcs}) {
532                 if (exists $IkiWiki::hooks{rcs}) {
533                         error(gettext("cannot use multiple rcs plugins"));
534                 }
535                 loadplugin($config{rcs});
536         }
537         if (! exists $IkiWiki::hooks{rcs}) {
538                 loadplugin("norcs");
539         }
540
541         run_hooks(getopt => sub { shift->() });
542         if (grep /^-/, @ARGV) {
543                 print STDERR "Unknown option (or missing parameter): $_\n"
544                         foreach grep /^-/, @ARGV;
545                 usage();
546         }
547
548         return 1;
549 }
550
551 sub loadplugin ($) {
552         my $plugin=shift;
553
554         return if grep { $_ eq $plugin} @{$config{disable_plugins}};
555
556         foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
557                          "$installdir/lib/ikiwiki") {
558                 if (defined $dir && -x "$dir/plugins/$plugin") {
559                         eval { require IkiWiki::Plugin::external };
560                         if ($@) {
561                                 my $reason=$@;
562                                 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
563                         }
564                         import IkiWiki::Plugin::external "$dir/plugins/$plugin";
565                         $loaded_plugins{$plugin}=1;
566                         return 1;
567                 }
568         }
569
570         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
571         eval qq{use $mod};
572         if ($@) {
573                 error("Failed to load plugin $mod: $@");
574         }
575         $loaded_plugins{$plugin}=1;
576         return 1;
577 }
578
579 sub error ($;$) {
580         my $message=shift;
581         my $cleaner=shift;
582         log_message('err' => $message) if $config{syslog};
583         if (defined $cleaner) {
584                 $cleaner->();
585         }
586         die $message."\n";
587 }
588
589 sub debug ($) {
590         return unless $config{verbose};
591         return log_message(debug => @_);
592 }
593
594 my $log_open=0;
595 sub log_message ($$) {
596         my $type=shift;
597
598         if ($config{syslog}) {
599                 require Sys::Syslog;
600                 if (! $log_open) {
601                         Sys::Syslog::setlogsock('unix');
602                         Sys::Syslog::openlog('ikiwiki', '', 'user');
603                         $log_open=1;
604                 }
605                 return eval {
606                         Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
607                 };
608         }
609         elsif (! $config{cgi}) {
610                 return print "@_\n";
611         }
612         else {
613                 return print STDERR "@_\n";
614         }
615 }
616
617 sub possibly_foolish_untaint ($) {
618         my $tainted=shift;
619         my ($untainted)=$tainted=~/(.*)/s;
620         return $untainted;
621 }
622
623 sub basename ($) {
624         my $file=shift;
625
626         $file=~s!.*/+!!;
627         return $file;
628 }
629
630 sub dirname ($) {
631         my $file=shift;
632
633         $file=~s!/*[^/]+$!!;
634         return $file;
635 }
636
637 sub isinternal ($) {
638         my $page=shift;
639         return exists $pagesources{$page} &&
640                 $pagesources{$page} =~ /\._([^.]+)$/;
641 }
642
643 sub pagetype ($) {
644         my $file=shift;
645         
646         if ($file =~ /\.([^.]+)$/) {
647                 return $1 if exists $hooks{htmlize}{$1};
648         }
649         my $base=basename($file);
650         if (exists $hooks{htmlize}{$base} &&
651             $hooks{htmlize}{$base}{noextension}) {
652                 return $base;
653         }
654         return;
655 }
656
657 sub pagename ($) {
658         my $file=shift;
659
660         my $type=pagetype($file);
661         my $page=$file;
662         $page=~s/\Q.$type\E*$//
663                 if defined $type && !$hooks{htmlize}{$type}{keepextension}
664                         && !$hooks{htmlize}{$type}{noextension};
665         if ($config{indexpages} && $page=~/(.*)\/index$/) {
666                 $page=$1;
667         }
668         return $page;
669 }
670
671 sub newpagefile ($$) {
672         my $page=shift;
673         my $type=shift;
674
675         if (! $config{indexpages} || $page eq 'index') {
676                 return $page.".".$type;
677         }
678         else {
679                 return $page."/index.".$type;
680         }
681 }
682
683 sub targetpage ($$;$) {
684         my $page=shift;
685         my $ext=shift;
686         my $filename=shift;
687         
688         if (defined $filename) {
689                 return $page."/".$filename.".".$ext;
690         }
691         elsif (! $config{usedirs} || $page eq 'index') {
692                 return $page.".".$ext;
693         }
694         else {
695                 return $page."/index.".$ext;
696         }
697 }
698
699 sub htmlpage ($) {
700         my $page=shift;
701         
702         return targetpage($page, $config{htmlext});
703 }
704
705 sub srcfile_stat {
706         my $file=shift;
707         my $nothrow=shift;
708
709         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
710         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
711                 return "$dir/$file", stat(_) if -e "$dir/$file";
712         }
713         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
714         return;
715 }
716
717 sub srcfile ($;$) {
718         return (srcfile_stat(@_))[0];
719 }
720
721 sub add_underlay ($) {
722         my $dir=shift;
723
724         if ($dir !~ /^\//) {
725                 $dir="$config{underlaydirbase}/$dir";
726         }
727
728         if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
729                 unshift @{$config{underlaydirs}}, $dir;
730         }
731
732         return 1;
733 }
734
735 sub readfile ($;$$) {
736         my $file=shift;
737         my $binary=shift;
738         my $wantfd=shift;
739
740         if (-l $file) {
741                 error("cannot read a symlink ($file)");
742         }
743         
744         local $/=undef;
745         open (my $in, "<", $file) || error("failed to read $file: $!");
746         binmode($in) if ($binary);
747         return \*$in if $wantfd;
748         my $ret=<$in>;
749         # check for invalid utf-8, and toss it back to avoid crashes
750         if (! utf8::valid($ret)) {
751                 $ret=encode_utf8($ret);
752         }
753         close $in || error("failed to read $file: $!");
754         return $ret;
755 }
756
757 sub prep_writefile ($$) {
758         my $file=shift;
759         my $destdir=shift;
760         
761         my $test=$file;
762         while (length $test) {
763                 if (-l "$destdir/$test") {
764                         error("cannot write to a symlink ($test)");
765                 }
766                 $test=dirname($test);
767         }
768
769         my $dir=dirname("$destdir/$file");
770         if (! -d $dir) {
771                 my $d="";
772                 foreach my $s (split(m!/+!, $dir)) {
773                         $d.="$s/";
774                         if (! -d $d) {
775                                 mkdir($d) || error("failed to create directory $d: $!");
776                         }
777                 }
778         }
779
780         return 1;
781 }
782
783 sub writefile ($$$;$$) {
784         my $file=shift; # can include subdirs
785         my $destdir=shift; # directory to put file in
786         my $content=shift;
787         my $binary=shift;
788         my $writer=shift;
789         
790         prep_writefile($file, $destdir);
791         
792         my $newfile="$destdir/$file.ikiwiki-new";
793         if (-l $newfile) {
794                 error("cannot write to a symlink ($newfile)");
795         }
796         
797         my $cleanup = sub { unlink($newfile) };
798         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
799         binmode($out) if ($binary);
800         if ($writer) {
801                 $writer->(\*$out, $cleanup);
802         }
803         else {
804                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
805         }
806         close $out || error("failed saving $newfile: $!", $cleanup);
807         rename($newfile, "$destdir/$file") || 
808                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
809
810         return 1;
811 }
812
813 my %cleared;
814 sub will_render ($$;$) {
815         my $page=shift;
816         my $dest=shift;
817         my $clear=shift;
818
819         # Important security check.
820         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
821             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
822                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
823         }
824
825         if (! $clear || $cleared{$page}) {
826                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
827         }
828         else {
829                 foreach my $old (@{$renderedfiles{$page}}) {
830                         delete $destsources{$old};
831                 }
832                 $renderedfiles{$page}=[$dest];
833                 $cleared{$page}=1;
834         }
835         $destsources{$dest}=$page;
836
837         return 1;
838 }
839
840 sub bestlink ($$) {
841         my $page=shift;
842         my $link=shift;
843         
844         my $cwd=$page;
845         if ($link=~s/^\/+//) {
846                 # absolute links
847                 $cwd="";
848         }
849         $link=~s/\/$//;
850
851         do {
852                 my $l=$cwd;
853                 $l.="/" if length $l;
854                 $l.=$link;
855
856                 if (exists $links{$l}) {
857                         return $l;
858                 }
859                 elsif (exists $pagecase{lc $l}) {
860                         return $pagecase{lc $l};
861                 }
862         } while $cwd=~s{/?[^/]+$}{};
863
864         if (length $config{userdir}) {
865                 my $l = "$config{userdir}/".lc($link);
866                 if (exists $links{$l}) {
867                         return $l;
868                 }
869                 elsif (exists $pagecase{lc $l}) {
870                         return $pagecase{lc $l};
871                 }
872         }
873
874         #print STDERR "warning: page $page, broken link: $link\n";
875         return "";
876 }
877
878 sub isinlinableimage ($) {
879         my $file=shift;
880         
881         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
882 }
883
884 sub pagetitle ($;$) {
885         my $page=shift;
886         my $unescaped=shift;
887
888         if ($unescaped) {
889                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
890         }
891         else {
892                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
893         }
894
895         return $page;
896 }
897
898 sub titlepage ($) {
899         my $title=shift;
900         # support use w/o %config set
901         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
902         $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
903         return $title;
904 }
905
906 sub linkpage ($) {
907         my $link=shift;
908         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
909         $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
910         return $link;
911 }
912
913 sub cgiurl (@) {
914         my %params=@_;
915
916         return $config{cgiurl}."?".
917                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
918 }
919
920 sub baseurl (;$) {
921         my $page=shift;
922
923         return "$config{url}/" if ! defined $page;
924         
925         $page=htmlpage($page);
926         $page=~s/[^\/]+$//;
927         $page=~s/[^\/]+\//..\//g;
928         return $page;
929 }
930
931 sub abs2rel ($$) {
932         # Work around very innefficient behavior in File::Spec if abs2rel
933         # is passed two relative paths. It's much faster if paths are
934         # absolute! (Debian bug #376658; fixed in debian unstable now)
935         my $path="/".shift;
936         my $base="/".shift;
937
938         require File::Spec;
939         my $ret=File::Spec->abs2rel($path, $base);
940         $ret=~s/^// if defined $ret;
941         return $ret;
942 }
943
944 sub displaytime ($;$) {
945         # Plugins can override this function to mark up the time to
946         # display.
947         return '<span class="date">'.formattime(@_).'</span>';
948 }
949
950 sub formattime ($;$) {
951         # Plugins can override this function to format the time.
952         my $time=shift;
953         my $format=shift;
954         if (! defined $format) {
955                 $format=$config{timeformat};
956         }
957
958         # strftime doesn't know about encodings, so make sure
959         # its output is properly treated as utf8
960         return decode_utf8(POSIX::strftime($format, localtime($time)));
961 }
962
963 sub beautify_urlpath ($) {
964         my $url=shift;
965
966         # Ensure url is not an empty link, and if necessary,
967         # add ./ to avoid colon confusion.
968         if ($url !~ /^\// && $url !~ /^\.\.?\//) {
969                 $url="./$url";
970         }
971
972         if ($config{usedirs}) {
973                 $url =~ s!/index.$config{htmlext}$!/!;
974         }
975
976         return $url;
977 }
978
979 sub urlto ($$;$) {
980         my $to=shift;
981         my $from=shift;
982         my $absolute=shift;
983         
984         if (! length $to) {
985                 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
986         }
987
988         if (! $destsources{$to}) {
989                 $to=htmlpage($to);
990         }
991
992         if ($absolute) {
993                 return $config{url}.beautify_urlpath("/".$to);
994         }
995
996         my $link = abs2rel($to, dirname(htmlpage($from)));
997
998         return beautify_urlpath($link);
999 }
1000
1001 sub htmllink ($$$;@) {
1002         my $lpage=shift; # the page doing the linking
1003         my $page=shift; # the page that will contain the link (different for inline)
1004         my $link=shift;
1005         my %opts=@_;
1006
1007         $link=~s/\/$//;
1008
1009         my $bestlink;
1010         if (! $opts{forcesubpage}) {
1011                 $bestlink=bestlink($lpage, $link);
1012         }
1013         else {
1014                 $bestlink="$lpage/".lc($link);
1015         }
1016
1017         my $linktext;
1018         if (defined $opts{linktext}) {
1019                 $linktext=$opts{linktext};
1020         }
1021         else {
1022                 $linktext=pagetitle(basename($link));
1023         }
1024         
1025         return "<span class=\"selflink\">$linktext</span>"
1026                 if length $bestlink && $page eq $bestlink &&
1027                    ! defined $opts{anchor};
1028         
1029         if (! $destsources{$bestlink}) {
1030                 $bestlink=htmlpage($bestlink);
1031
1032                 if (! $destsources{$bestlink}) {
1033                         return $linktext unless length $config{cgiurl};
1034                         return "<span class=\"createlink\"><a href=\"".
1035                                 cgiurl(
1036                                         do => "create",
1037                                         page => lc($link),
1038                                         from => $lpage
1039                                 ).
1040                                 "\" rel=\"nofollow\">?</a>$linktext</span>"
1041                 }
1042         }
1043         
1044         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1045         $bestlink=beautify_urlpath($bestlink);
1046         
1047         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1048                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1049         }
1050
1051         if (defined $opts{anchor}) {
1052                 $bestlink.="#".$opts{anchor};
1053         }
1054
1055         my @attrs;
1056         if (defined $opts{rel}) {
1057                 push @attrs, ' rel="'.$opts{rel}.'"';
1058         }
1059         if (defined $opts{class}) {
1060                 push @attrs, ' class="'.$opts{class}.'"';
1061         }
1062
1063         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1064 }
1065
1066 sub openiduser ($) {
1067         my $user=shift;
1068
1069         if ($user =~ m!^https?://! &&
1070             eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1071                 my $display;
1072
1073                 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1074                         # this works in at least 2.x
1075                         $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1076                 }
1077                 else {
1078                         # this only works in 1.x
1079                         my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1080                         $display=$oid->display;
1081                 }
1082
1083                 # Convert "user.somehost.com" to "user [somehost.com]"
1084                 # (also "user.somehost.co.uk")
1085                 if ($display !~ /\[/) {
1086                         $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1087                 }
1088                 # Convert "http://somehost.com/user" to "user [somehost.com]".
1089                 # (also "https://somehost.com/user/")
1090                 if ($display !~ /\[/) {
1091                         $display=~s/^https?:\/\/(.+)\/([^\/]+)\/?$/$2 [$1]/;
1092                 }
1093                 $display=~s!^https?://!!; # make sure this is removed
1094                 eval q{use CGI 'escapeHTML'};
1095                 error($@) if $@;
1096                 return escapeHTML($display);
1097         }
1098         return;
1099 }
1100
1101 sub userlink ($) {
1102         my $user=shift;
1103
1104         my $oiduser=eval { openiduser($user) };
1105         if (defined $oiduser) {
1106                 return "<a href=\"$user\">$oiduser</a>";
1107         }
1108         else {
1109                 eval q{use CGI 'escapeHTML'};
1110                 error($@) if $@;
1111
1112                 return htmllink("", "", escapeHTML(
1113                         length $config{userdir} ? $config{userdir}."/".$user : $user
1114                 ), noimageinline => 1);
1115         }
1116 }
1117
1118 sub htmlize ($$$$) {
1119         my $page=shift;
1120         my $destpage=shift;
1121         my $type=shift;
1122         my $content=shift;
1123         
1124         my $oneline = $content !~ /\n/;
1125
1126         if (exists $hooks{htmlize}{$type}) {
1127                 $content=$hooks{htmlize}{$type}{call}->(
1128                         page => $page,
1129                         content => $content,
1130                 );
1131         }
1132         else {
1133                 error("htmlization of $type not supported");
1134         }
1135
1136         run_hooks(sanitize => sub {
1137                 $content=shift->(
1138                         page => $page,
1139                         destpage => $destpage,
1140                         content => $content,
1141                 );
1142         });
1143         
1144         if ($oneline) {
1145                 # hack to get rid of enclosing junk added by markdown
1146                 # and other htmlizers
1147                 $content=~s/^<p>//i;
1148                 $content=~s/<\/p>$//i;
1149                 chomp $content;
1150         }
1151
1152         return $content;
1153 }
1154
1155 sub linkify ($$$) {
1156         my $page=shift;
1157         my $destpage=shift;
1158         my $content=shift;
1159
1160         run_hooks(linkify => sub {
1161                 $content=shift->(
1162                         page => $page,
1163                         destpage => $destpage,
1164                         content => $content,
1165                 );
1166         });
1167         
1168         return $content;
1169 }
1170
1171 our %preprocessing;
1172 our $preprocess_preview=0;
1173 sub preprocess ($$$;$$) {
1174         my $page=shift; # the page the data comes from
1175         my $destpage=shift; # the page the data will appear in (different for inline)
1176         my $content=shift;
1177         my $scan=shift;
1178         my $preview=shift;
1179
1180         # Using local because it needs to be set within any nested calls
1181         # of this function.
1182         local $preprocess_preview=$preview if defined $preview;
1183
1184         my $handle=sub {
1185                 my $escape=shift;
1186                 my $prefix=shift;
1187                 my $command=shift;
1188                 my $params=shift;
1189                 $params="" if ! defined $params;
1190
1191                 if (length $escape) {
1192                         return "[[$prefix$command $params]]";
1193                 }
1194                 elsif (exists $hooks{preprocess}{$command}) {
1195                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1196                         # Note: preserve order of params, some plugins may
1197                         # consider it significant.
1198                         my @params;
1199                         while ($params =~ m{
1200                                 (?:([-\w]+)=)?          # 1: named parameter key?
1201                                 (?:
1202                                         """(.*?)"""     # 2: triple-quoted value
1203                                 |
1204                                         "([^"]+)"       # 3: single-quoted value
1205                                 |
1206                                         (\S+)           # 4: unquoted value
1207                                 )
1208                                 (?:\s+|$)               # delimiter to next param
1209                         }sgx) {
1210                                 my $key=$1;
1211                                 my $val;
1212                                 if (defined $2) {
1213                                         $val=$2;
1214                                         $val=~s/\r\n/\n/mg;
1215                                         $val=~s/^\n+//g;
1216                                         $val=~s/\n+$//g;
1217                                 }
1218                                 elsif (defined $3) {
1219                                         $val=$3;
1220                                 }
1221                                 elsif (defined $4) {
1222                                         $val=$4;
1223                                 }
1224
1225                                 if (defined $key) {
1226                                         push @params, $key, $val;
1227                                 }
1228                                 else {
1229                                         push @params, $val, '';
1230                                 }
1231                         }
1232                         if ($preprocessing{$page}++ > 3) {
1233                                 # Avoid loops of preprocessed pages preprocessing
1234                                 # other pages that preprocess them, etc.
1235                                 return "[[!$command <span class=\"error\">".
1236                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1237                                                 $page, $preprocessing{$page}).
1238                                         "</span>]]";
1239                         }
1240                         my $ret;
1241                         if (! $scan) {
1242                                 $ret=eval {
1243                                         $hooks{preprocess}{$command}{call}->(
1244                                                 @params,
1245                                                 page => $page,
1246                                                 destpage => $destpage,
1247                                                 preview => $preprocess_preview,
1248                                         );
1249                                 };
1250                                 if ($@) {
1251                                         chomp $@;
1252                                         $ret="[[!$command <span class=\"error\">".
1253                                                 gettext("Error").": $@"."</span>]]";
1254                                 }
1255                         }
1256                         else {
1257                                 # use void context during scan pass
1258                                 eval {
1259                                         $hooks{preprocess}{$command}{call}->(
1260                                                 @params,
1261                                                 page => $page,
1262                                                 destpage => $destpage,
1263                                                 preview => $preprocess_preview,
1264                                         );
1265                                 };
1266                                 $ret="";
1267                         }
1268                         $preprocessing{$page}--;
1269                         return $ret;
1270                 }
1271                 else {
1272                         return "[[$prefix$command $params]]";
1273                 }
1274         };
1275         
1276         my $regex;
1277         if ($config{prefix_directives}) {
1278                 $regex = qr{
1279                         (\\?)           # 1: escape?
1280                         \[\[(!)         # directive open; 2: prefix
1281                         ([-\w]+)        # 3: command
1282                         (               # 4: the parameters..
1283                                 \s+     # Must have space if parameters present
1284                                 (?:
1285                                         (?:[-\w]+=)?            # named parameter key?
1286                                         (?:
1287                                                 """.*?"""       # triple-quoted value
1288                                                 |
1289                                                 "[^"]+"         # single-quoted value
1290                                                 |
1291                                                 [^"\s\]]+       # unquoted value
1292                                         )
1293                                         \s*                     # whitespace or end
1294                                                                 # of directive
1295                                 )
1296                         *)?             # 0 or more parameters
1297                         \]\]            # directive closed
1298                 }sx;
1299         }
1300         else {
1301                 $regex = qr{
1302                         (\\?)           # 1: escape?
1303                         \[\[(!?)        # directive open; 2: optional prefix
1304                         ([-\w]+)        # 3: command
1305                         \s+
1306                         (               # 4: the parameters..
1307                                 (?:
1308                                         (?:[-\w]+=)?            # named parameter key?
1309                                         (?:
1310                                                 """.*?"""       # triple-quoted value
1311                                                 |
1312                                                 "[^"]+"         # single-quoted value
1313                                                 |
1314                                                 [^"\s\]]+       # unquoted value
1315                                         )
1316                                         \s*                     # whitespace or end
1317                                                                 # of directive
1318                                 )
1319                         *)              # 0 or more parameters
1320                         \]\]            # directive closed
1321                 }sx;
1322         }
1323
1324         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1325         return $content;
1326 }
1327
1328 sub filter ($$$) {
1329         my $page=shift;
1330         my $destpage=shift;
1331         my $content=shift;
1332
1333         run_hooks(filter => sub {
1334                 $content=shift->(page => $page, destpage => $destpage, 
1335                         content => $content);
1336         });
1337
1338         return $content;
1339 }
1340
1341 sub indexlink () {
1342         return "<a href=\"$config{url}\">$config{wikiname}</a>";
1343 }
1344
1345 sub check_canedit ($$$;$) {
1346         my $page=shift;
1347         my $q=shift;
1348         my $session=shift;
1349         my $nonfatal=shift;
1350         
1351         my $canedit;
1352         run_hooks(canedit => sub {
1353                 return if defined $canedit;
1354                 my $ret=shift->($page, $q, $session);
1355                 if (defined $ret) {
1356                         if ($ret eq "") {
1357                                 $canedit=1;
1358                         }
1359                         elsif (ref $ret eq 'CODE') {
1360                                 $ret->() unless $nonfatal;
1361                                 $canedit=0;
1362                         }
1363                         elsif (defined $ret) {
1364                                 error($ret) unless $nonfatal;
1365                                 $canedit=0;
1366                         }
1367                 }
1368         });
1369         return defined $canedit ? $canedit : 1;
1370 }
1371
1372 sub check_content (@) {
1373         my %params=@_;
1374         
1375         return 1 if ! exists $hooks{checkcontent}; # optimisation
1376
1377         if (exists $pagesources{$params{page}}) {
1378                 my @diff;
1379                 my %old=map { $_ => 1 }
1380                         split("\n", readfile(srcfile($pagesources{$params{page}})));
1381                 foreach my $line (split("\n", $params{content})) {
1382                         push @diff, $line if ! exists $old{$_};
1383                 }
1384                 $params{diff}=join("\n", @diff);
1385         }
1386
1387         my $ok;
1388         run_hooks(checkcontent => sub {
1389                 return if defined $ok;
1390                 my $ret=shift->(%params);
1391                 if (defined $ret) {
1392                         if ($ret eq "") {
1393                                 $ok=1;
1394                         }
1395                         elsif (ref $ret eq 'CODE') {
1396                                 $ret->() unless $params{nonfatal};
1397                                 $ok=0;
1398                         }
1399                         elsif (defined $ret) {
1400                                 error($ret) unless $params{nonfatal};
1401                                 $ok=0;
1402                         }
1403                 }
1404
1405         });
1406         return defined $ok ? $ok : 1;
1407 }
1408
1409 my $wikilock;
1410
1411 sub lockwiki () {
1412         # Take an exclusive lock on the wiki to prevent multiple concurrent
1413         # run issues. The lock will be dropped on program exit.
1414         if (! -d $config{wikistatedir}) {
1415                 mkdir($config{wikistatedir});
1416         }
1417         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1418                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1419         if (! flock($wikilock, 2)) { # LOCK_EX
1420                 error("failed to get lock");
1421         }
1422         return 1;
1423 }
1424
1425 sub unlockwiki () {
1426         POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1427         return close($wikilock) if $wikilock;
1428         return;
1429 }
1430
1431 my $commitlock;
1432
1433 sub commit_hook_enabled () {
1434         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1435                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1436         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1437                 close($commitlock) || error("failed closing commitlock: $!");
1438                 return 0;
1439         }
1440         close($commitlock) || error("failed closing commitlock: $!");
1441         return 1;
1442 }
1443
1444 sub disable_commit_hook () {
1445         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1446                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1447         if (! flock($commitlock, 2)) { # LOCK_EX
1448                 error("failed to get commit lock");
1449         }
1450         return 1;
1451 }
1452
1453 sub enable_commit_hook () {
1454         return close($commitlock) if $commitlock;
1455         return;
1456 }
1457
1458 sub loadindex () {
1459         %oldrenderedfiles=%pagectime=();
1460         if (! $config{rebuild}) {
1461                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1462                 %destsources=%renderedfiles=%pagecase=%pagestate=();
1463         }
1464         my $in;
1465         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1466                 if (-e "$config{wikistatedir}/index") {
1467                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1468                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1469                 }
1470                 else {
1471                         return;
1472                 }
1473         }
1474
1475         my $index=Storable::fd_retrieve($in);
1476         if (! defined $index) {
1477                 return 0;
1478         }
1479
1480         my $pages;
1481         if (exists $index->{version} && ! ref $index->{version}) {
1482                 $pages=$index->{page};
1483                 %wikistate=%{$index->{state}};
1484         }
1485         else {
1486                 $pages=$index;
1487                 %wikistate=();
1488         }
1489
1490         foreach my $src (keys %$pages) {
1491                 my $d=$pages->{$src};
1492                 my $page=pagename($src);
1493                 $pagectime{$page}=$d->{ctime};
1494                 if (! $config{rebuild}) {
1495                         $pagesources{$page}=$src;
1496                         $pagemtime{$page}=$d->{mtime};
1497                         $renderedfiles{$page}=$d->{dest};
1498                         if (exists $d->{links} && ref $d->{links}) {
1499                                 $links{$page}=$d->{links};
1500                                 $oldlinks{$page}=[@{$d->{links}}];
1501                         }
1502                         if (exists $d->{depends}) {
1503                                 $depends{$page}=$d->{depends};
1504                         }
1505                         if (exists $d->{state}) {
1506                                 $pagestate{$page}=$d->{state};
1507                         }
1508                 }
1509                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1510         }
1511         foreach my $page (keys %pagesources) {
1512                 $pagecase{lc $page}=$page;
1513         }
1514         foreach my $page (keys %renderedfiles) {
1515                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1516         }
1517         return close($in);
1518 }
1519
1520 sub saveindex () {
1521         run_hooks(savestate => sub { shift->() });
1522
1523         my %hookids;
1524         foreach my $type (keys %hooks) {
1525                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1526         }
1527         my @hookids=keys %hookids;
1528
1529         if (! -d $config{wikistatedir}) {
1530                 mkdir($config{wikistatedir});
1531         }
1532         my $newfile="$config{wikistatedir}/indexdb.new";
1533         my $cleanup = sub { unlink($newfile) };
1534         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1535
1536         my %index;
1537         foreach my $page (keys %pagemtime) {
1538                 next unless $pagemtime{$page};
1539                 my $src=$pagesources{$page};
1540
1541                 $index{page}{$src}={
1542                         ctime => $pagectime{$page},
1543                         mtime => $pagemtime{$page},
1544                         dest => $renderedfiles{$page},
1545                         links => $links{$page},
1546                 };
1547
1548                 if (exists $depends{$page}) {
1549                         $index{page}{$src}{depends} = $depends{$page};
1550                 }
1551
1552                 if (exists $pagestate{$page}) {
1553                         foreach my $id (@hookids) {
1554                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1555                                         $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1556                                 }
1557                         }
1558                 }
1559         }
1560
1561         $index{state}={};
1562         foreach my $id (@hookids) {
1563                 foreach my $key (keys %{$wikistate{$id}}) {
1564                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
1565                 }
1566         }
1567         
1568         $index{version}="3";
1569         my $ret=Storable::nstore_fd(\%index, $out);
1570         return if ! defined $ret || ! $ret;
1571         close $out || error("failed saving to $newfile: $!", $cleanup);
1572         rename($newfile, "$config{wikistatedir}/indexdb") ||
1573                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1574         
1575         return 1;
1576 }
1577
1578 sub template_file ($) {
1579         my $template=shift;
1580
1581         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1582                 return "$dir/$template" if -e "$dir/$template";
1583         }
1584         return;
1585 }
1586
1587 sub template_params (@) {
1588         my $filename=template_file(shift);
1589
1590         if (! defined $filename) {
1591                 return if wantarray;
1592                 return "";
1593         }
1594
1595         my @ret=(
1596                 filter => sub {
1597                         my $text_ref = shift;
1598                         ${$text_ref} = decode_utf8(${$text_ref});
1599                 },
1600                 filename => $filename,
1601                 loop_context_vars => 1,
1602                 die_on_bad_params => 0,
1603                 @_
1604         );
1605         return wantarray ? @ret : {@ret};
1606 }
1607
1608 sub template ($;@) {
1609         require HTML::Template;
1610         return HTML::Template->new(template_params(@_));
1611 }
1612
1613 sub misctemplate ($$;@) {
1614         my $title=shift;
1615         my $pagebody=shift;
1616         
1617         my $template=template("misc.tmpl");
1618         $template->param(
1619                 title => $title,
1620                 indexlink => indexlink(),
1621                 wikiname => $config{wikiname},
1622                 pagebody => $pagebody,
1623                 baseurl => baseurl(),
1624                 @_,
1625         );
1626         run_hooks(pagetemplate => sub {
1627                 shift->(page => "", destpage => "", template => $template);
1628         });
1629         return $template->output;
1630 }
1631
1632 sub hook (@) {
1633         my %param=@_;
1634         
1635         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1636                 error 'hook requires type, call, and id parameters';
1637         }
1638
1639         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1640         
1641         $hooks{$param{type}}{$param{id}}=\%param;
1642         return 1;
1643 }
1644
1645 sub run_hooks ($$) {
1646         # Calls the given sub for each hook of the given type,
1647         # passing it the hook function to call.
1648         my $type=shift;
1649         my $sub=shift;
1650
1651         if (exists $hooks{$type}) {
1652                 my (@first, @middle, @last);
1653                 foreach my $id (keys %{$hooks{$type}}) {
1654                         if ($hooks{$type}{$id}{first}) {
1655                                 push @first, $id;
1656                         }
1657                         elsif ($hooks{$type}{$id}{last}) {
1658                                 push @last, $id;
1659                         }
1660                         else {
1661                                 push @middle, $id;
1662                         }
1663                 }
1664                 foreach my $id (@first, @middle, @last) {
1665                         $sub->($hooks{$type}{$id}{call});
1666                 }
1667         }
1668
1669         return 1;
1670 }
1671
1672 sub rcs_update () {
1673         $hooks{rcs}{rcs_update}{call}->(@_);
1674 }
1675
1676 sub rcs_prepedit ($) {
1677         $hooks{rcs}{rcs_prepedit}{call}->(@_);
1678 }
1679
1680 sub rcs_commit ($$$;$$) {
1681         $hooks{rcs}{rcs_commit}{call}->(@_);
1682 }
1683
1684 sub rcs_commit_staged ($$$) {
1685         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1686 }
1687
1688 sub rcs_add ($) {
1689         $hooks{rcs}{rcs_add}{call}->(@_);
1690 }
1691
1692 sub rcs_remove ($) {
1693         $hooks{rcs}{rcs_remove}{call}->(@_);
1694 }
1695
1696 sub rcs_rename ($$) {
1697         $hooks{rcs}{rcs_rename}{call}->(@_);
1698 }
1699
1700 sub rcs_recentchanges ($) {
1701         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1702 }
1703
1704 sub rcs_diff ($) {
1705         $hooks{rcs}{rcs_diff}{call}->(@_);
1706 }
1707
1708 sub rcs_getctime ($) {
1709         $hooks{rcs}{rcs_getctime}{call}->(@_);
1710 }
1711
1712 sub rcs_receive () {
1713         $hooks{rcs}{rcs_receive}{call}->();
1714 }
1715
1716 sub add_depends ($$) {
1717         my $page=shift;
1718         my $pagespec=shift;
1719         
1720         return unless pagespec_valid($pagespec);
1721
1722         if (! exists $depends{$page}) {
1723                 $depends{$page}=$pagespec;
1724         }
1725         else {
1726                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1727         }
1728
1729         return 1;
1730 }
1731
1732 sub file_pruned ($$) {
1733         require File::Spec;
1734         my $file=File::Spec->canonpath(shift);
1735         my $base=File::Spec->canonpath(shift);
1736         $file =~ s#^\Q$base\E/+##;
1737
1738         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1739         return $file =~ m/$regexp/ && $file ne $base;
1740 }
1741
1742 sub define_gettext () {
1743         # If translation is needed, redefine the gettext function to do it.
1744         # Otherwise, it becomes a quick no-op.
1745         no warnings 'redefine';
1746         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1747             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1748             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1749                 *gettext=sub {
1750                         my $gettext_obj=eval q{
1751                                 use Locale::gettext q{textdomain};
1752                                 Locale::gettext->domain('ikiwiki')
1753                         };
1754
1755                         if ($gettext_obj) {
1756                                 $gettext_obj->get(shift);
1757                         }
1758                         else {
1759                                 return shift;
1760                         }
1761                 };
1762         }
1763         else {
1764                 *gettext=sub { return shift };
1765         }
1766 }
1767
1768 sub gettext {
1769         define_gettext();
1770         gettext(@_);
1771 }
1772
1773 sub yesno ($) {
1774         my $val=shift;
1775
1776         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1777 }
1778
1779 sub inject {
1780         # Injects a new function into the symbol table to replace an
1781         # exported function.
1782         my %params=@_;
1783
1784         # This is deep ugly perl foo, beware.
1785         no strict;
1786         no warnings;
1787         if (! defined $params{parent}) {
1788                 $params{parent}='::';
1789                 $params{old}=\&{$params{name}};
1790                 $params{name}=~s/.*:://;
1791         }
1792         my $parent=$params{parent};
1793         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1794                 $ns = $params{parent} . $ns;
1795                 inject(%params, parent => $ns) unless $ns eq '::main::';
1796                 *{$ns . $params{name}} = $params{call}
1797                         if exists ${$ns}{$params{name}} &&
1798                            \&{${$ns}{$params{name}}} == $params{old};
1799         }
1800         use strict;
1801         use warnings;
1802 }
1803
1804 sub add_link ($$) {
1805         my $page=shift;
1806         my $link=shift;
1807
1808         push @{$links{$page}}, $link
1809                 unless grep { $_ eq $link } @{$links{$page}};
1810 }
1811
1812 sub pagespec_merge ($$) {
1813         my $a=shift;
1814         my $b=shift;
1815
1816         return $a if $a eq $b;
1817         return "($a) or ($b)";
1818 }
1819
1820 sub pagespec_translate ($) {
1821         my $spec=shift;
1822
1823         # Convert spec to perl code.
1824         my $code="";
1825         my @data;
1826         while ($spec=~m{
1827                 \s*             # ignore whitespace
1828                 (               # 1: match a single word
1829                         \!              # !
1830                 |
1831                         \(              # (
1832                 |
1833                         \)              # )
1834                 |
1835                         \w+\([^\)]*\)   # command(params)
1836                 |
1837                         [^\s()]+        # any other text
1838                 )
1839                 \s*             # ignore whitespace
1840         }igx) {
1841                 my $word=$1;
1842                 if (lc $word eq 'and') {
1843                         $code.=' &&';
1844                 }
1845                 elsif (lc $word eq 'or') {
1846                         $code.=' ||';
1847                 }
1848                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1849                         $code.=' '.$word;
1850                 }
1851                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1852                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1853                                 push @data, $2;
1854                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
1855                         }
1856                         else {
1857                                 push @data, qq{unknown function in pagespec "$word"};
1858                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
1859                         }
1860                 }
1861                 else {
1862                         push @data, $word;
1863                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
1864                 }
1865         }
1866
1867         if (! length $code) {
1868                 $code="IkiWiki::FailReason->new('empty pagespec')";
1869         }
1870
1871         no warnings;
1872         return eval 'sub { my $page=shift; '.$code.' }';
1873 }
1874
1875 sub pagespec_match ($$;@) {
1876         my $page=shift;
1877         my $spec=shift;
1878         my @params=@_;
1879
1880         # Backwards compatability with old calling convention.
1881         if (@params == 1) {
1882                 unshift @params, 'location';
1883         }
1884
1885         my $sub=pagespec_translate($spec);
1886         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
1887                 if $@ || ! defined $sub;
1888         return $sub->($page, @params);
1889 }
1890
1891 sub pagespec_match_list ($$;@) {
1892         my $pages=shift;
1893         my $spec=shift;
1894         my @params=@_;
1895
1896         my $sub=pagespec_translate($spec);
1897         error "syntax error in pagespec \"$spec\""
1898                 if $@ || ! defined $sub;
1899         
1900         my @ret;
1901         my $r;
1902         foreach my $page (@$pages) {
1903                 $r=$sub->($page, @params);
1904                 push @ret, $page if $r;
1905         }
1906
1907         if (! @ret && defined $r && $r->isa("IkiWiki::ErrorReason")) {
1908                 error(sprintf(gettext("cannot match pages: %s"), $r));
1909         }
1910         else {
1911                 return @ret;
1912         }
1913 }
1914
1915 sub pagespec_valid ($) {
1916         my $spec=shift;
1917
1918         my $sub=pagespec_translate($spec);
1919         return ! $@;
1920 }
1921
1922 sub glob2re ($) {
1923         my $re=quotemeta(shift);
1924         $re=~s/\\\*/.*/g;
1925         $re=~s/\\\?/./g;
1926         return $re;
1927 }
1928
1929 package IkiWiki::FailReason;
1930
1931 use overload (
1932         '""'    => sub { ${$_[0]} },
1933         '0+'    => sub { 0 },
1934         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1935         fallback => 1,
1936 );
1937
1938 sub new {
1939         my $class = shift;
1940         my $value = shift;
1941         return bless \$value, $class;
1942 }
1943
1944 package IkiWiki::ErrorReason;
1945
1946 our @ISA = 'IkiWiki::FailReason';
1947
1948 package IkiWiki::SuccessReason;
1949
1950 use overload (
1951         '""'    => sub { ${$_[0]} },
1952         '0+'    => sub { 1 },
1953         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
1954         fallback => 1,
1955 );
1956
1957 sub new {
1958         my $class = shift;
1959         my $value = shift;
1960         return bless \$value, $class;
1961 };
1962
1963 package IkiWiki::PageSpec;
1964
1965 sub derel ($$) {
1966         my $path=shift;
1967         my $from=shift;
1968
1969         if ($path =~ m!^\./!) {
1970                 $from=~s#/?[^/]+$## if defined $from;
1971                 $path=~s#^\./##;
1972                 $path="$from/$path" if length $from;
1973         }
1974
1975         return $path;
1976 }
1977
1978 sub match_glob ($$;@) {
1979         my $page=shift;
1980         my $glob=shift;
1981         my %params=@_;
1982         
1983         $glob=derel($glob, $params{location});
1984
1985         my $regexp=IkiWiki::glob2re($glob);
1986         if ($page=~/^$regexp$/i) {
1987                 if (! IkiWiki::isinternal($page) || $params{internal}) {
1988                         return IkiWiki::SuccessReason->new("$glob matches $page");
1989                 }
1990                 else {
1991                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1992                 }
1993         }
1994         else {
1995                 return IkiWiki::FailReason->new("$glob does not match $page");
1996         }
1997 }
1998
1999 sub match_internal ($$;@) {
2000         return match_glob($_[0], $_[1], @_, internal => 1)
2001 }
2002
2003 sub match_link ($$;@) {
2004         my $page=shift;
2005         my $link=lc(shift);
2006         my %params=@_;
2007
2008         $link=derel($link, $params{location});
2009         my $from=exists $params{location} ? $params{location} : '';
2010
2011         my $links = $IkiWiki::links{$page};
2012         return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
2013         my $bestlink = IkiWiki::bestlink($from, $link);
2014         foreach my $p (@{$links}) {
2015                 if (length $bestlink) {
2016                         return IkiWiki::SuccessReason->new("$page links to $link")
2017                                 if $bestlink eq IkiWiki::bestlink($page, $p);
2018                 }
2019                 else {
2020                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
2021                                 if match_glob($p, $link, %params);
2022                         $p=~s/^\///;
2023                         $link=~s/^\///;
2024                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
2025                                 if match_glob($p, $link, %params);
2026                 }
2027         }
2028         return IkiWiki::FailReason->new("$page does not link to $link");
2029 }
2030
2031 sub match_backlink ($$;@) {
2032         return match_link($_[1], $_[0], @_);
2033 }
2034
2035 sub match_created_before ($$;@) {
2036         my $page=shift;
2037         my $testpage=shift;
2038         my %params=@_;
2039         
2040         $testpage=derel($testpage, $params{location});
2041
2042         if (exists $IkiWiki::pagectime{$testpage}) {
2043                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2044                         return IkiWiki::SuccessReason->new("$page created before $testpage");
2045                 }
2046                 else {
2047                         return IkiWiki::FailReason->new("$page not created before $testpage");
2048                 }
2049         }
2050         else {
2051                 return IkiWiki::FailReason->new("$testpage has no ctime");
2052         }
2053 }
2054
2055 sub match_created_after ($$;@) {
2056         my $page=shift;
2057         my $testpage=shift;
2058         my %params=@_;
2059         
2060         $testpage=derel($testpage, $params{location});
2061
2062         if (exists $IkiWiki::pagectime{$testpage}) {
2063                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2064                         return IkiWiki::SuccessReason->new("$page created after $testpage");
2065                 }
2066                 else {
2067                         return IkiWiki::FailReason->new("$page not created after $testpage");
2068                 }
2069         }
2070         else {
2071                 return IkiWiki::FailReason->new("$testpage has no ctime");
2072         }
2073 }
2074
2075 sub match_creation_day ($$;@) {
2076         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2077                 return IkiWiki::SuccessReason->new('creation_day matched');
2078         }
2079         else {
2080                 return IkiWiki::FailReason->new('creation_day did not match');
2081         }
2082 }
2083
2084 sub match_creation_month ($$;@) {
2085         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2086                 return IkiWiki::SuccessReason->new('creation_month matched');
2087         }
2088         else {
2089                 return IkiWiki::FailReason->new('creation_month did not match');
2090         }
2091 }
2092
2093 sub match_creation_year ($$;@) {
2094         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2095                 return IkiWiki::SuccessReason->new('creation_year matched');
2096         }
2097         else {
2098                 return IkiWiki::FailReason->new('creation_year did not match');
2099         }
2100 }
2101
2102 sub match_user ($$;@) {
2103         shift;
2104         my $user=shift;
2105         my %params=@_;
2106         
2107         if (! exists $params{user}) {
2108                 return IkiWiki::ErrorReason->new("no user specified");
2109         }
2110
2111         if (defined $params{user} && lc $params{user} eq lc $user) {
2112                 return IkiWiki::SuccessReason->new("user is $user");
2113         }
2114         elsif (! defined $params{user}) {
2115                 return IkiWiki::FailReason->new("not logged in");
2116         }
2117         else {
2118                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2119         }
2120 }
2121
2122 sub match_admin ($$;@) {
2123         shift;
2124         shift;
2125         my %params=@_;
2126         
2127         if (! exists $params{user}) {
2128                 return IkiWiki::ErrorReason->new("no user specified");
2129         }
2130
2131         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2132                 return IkiWiki::SuccessReason->new("user is an admin");
2133         }
2134         elsif (! defined $params{user}) {
2135                 return IkiWiki::FailReason->new("not logged in");
2136         }
2137         else {
2138                 return IkiWiki::FailReason->new("user is not an admin");
2139         }
2140 }
2141
2142 sub match_ip ($$;@) {
2143         shift;
2144         my $ip=shift;
2145         my %params=@_;
2146         
2147         if (! exists $params{ip}) {
2148                 return IkiWiki::ErrorReason->new("no IP specified");
2149         }
2150
2151         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2152                 return IkiWiki::SuccessReason->new("IP is $ip");
2153         }
2154         else {
2155                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2156         }
2157 }
2158
2159 1