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