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