Merge branch 'master' of git://github.com/joeyh/ikiwiki
[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
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/(^|\/)CVS\//, 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 my %pagename_cache;
665
666 sub pagename ($) {
667         my $file=shift;
668
669         if (exists $pagename_cache{$file}) {
670                 return $pagename_cache{$file};
671         }
672
673         my $type=pagetype($file);
674         my $page=$file;
675         $page=~s/\Q.$type\E*$//
676                 if defined $type && !$hooks{htmlize}{$type}{keepextension}
677                         && !$hooks{htmlize}{$type}{noextension};
678         if ($config{indexpages} && $page=~/(.*)\/index$/) {
679                 $page=$1;
680         }
681
682         $pagename_cache{$file} = $page;
683         return $page;
684 }
685
686 sub newpagefile ($$) {
687         my $page=shift;
688         my $type=shift;
689
690         if (! $config{indexpages} || $page eq 'index') {
691                 return $page.".".$type;
692         }
693         else {
694                 return $page."/index.".$type;
695         }
696 }
697
698 sub targetpage ($$;$) {
699         my $page=shift;
700         my $ext=shift;
701         my $filename=shift;
702         
703         if (defined $filename) {
704                 return $page."/".$filename.".".$ext;
705         }
706         elsif (! $config{usedirs} || $page eq 'index') {
707                 return $page.".".$ext;
708         }
709         else {
710                 return $page."/index.".$ext;
711         }
712 }
713
714 sub htmlpage ($) {
715         my $page=shift;
716         
717         return targetpage($page, $config{htmlext});
718 }
719
720 sub srcfile_stat {
721         my $file=shift;
722         my $nothrow=shift;
723
724         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
725         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
726                 return "$dir/$file", stat(_) if -e "$dir/$file";
727         }
728         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
729         return;
730 }
731
732 sub srcfile ($;$) {
733         return (srcfile_stat(@_))[0];
734 }
735
736 sub add_underlay ($) {
737         my $dir=shift;
738
739         if ($dir !~ /^\//) {
740                 $dir="$config{underlaydirbase}/$dir";
741         }
742
743         if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
744                 unshift @{$config{underlaydirs}}, $dir;
745         }
746
747         return 1;
748 }
749
750 sub readfile ($;$$) {
751         my $file=shift;
752         my $binary=shift;
753         my $wantfd=shift;
754
755         if (-l $file) {
756                 error("cannot read a symlink ($file)");
757         }
758         
759         local $/=undef;
760         open (my $in, "<", $file) || error("failed to read $file: $!");
761         binmode($in) if ($binary);
762         return \*$in if $wantfd;
763         my $ret=<$in>;
764         # check for invalid utf-8, and toss it back to avoid crashes
765         if (! utf8::valid($ret)) {
766                 $ret=encode_utf8($ret);
767         }
768         close $in || error("failed to read $file: $!");
769         return $ret;
770 }
771
772 sub prep_writefile ($$) {
773         my $file=shift;
774         my $destdir=shift;
775         
776         my $test=$file;
777         while (length $test) {
778                 if (-l "$destdir/$test") {
779                         error("cannot write to a symlink ($test)");
780                 }
781                 $test=dirname($test);
782         }
783
784         my $dir=dirname("$destdir/$file");
785         if (! -d $dir) {
786                 my $d="";
787                 foreach my $s (split(m!/+!, $dir)) {
788                         $d.="$s/";
789                         if (! -d $d) {
790                                 mkdir($d) || error("failed to create directory $d: $!");
791                         }
792                 }
793         }
794
795         return 1;
796 }
797
798 sub writefile ($$$;$$) {
799         my $file=shift; # can include subdirs
800         my $destdir=shift; # directory to put file in
801         my $content=shift;
802         my $binary=shift;
803         my $writer=shift;
804         
805         prep_writefile($file, $destdir);
806         
807         my $newfile="$destdir/$file.ikiwiki-new";
808         if (-l $newfile) {
809                 error("cannot write to a symlink ($newfile)");
810         }
811         
812         my $cleanup = sub { unlink($newfile) };
813         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
814         binmode($out) if ($binary);
815         if ($writer) {
816                 $writer->(\*$out, $cleanup);
817         }
818         else {
819                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
820         }
821         close $out || error("failed saving $newfile: $!", $cleanup);
822         rename($newfile, "$destdir/$file") || 
823                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
824
825         return 1;
826 }
827
828 my %cleared;
829 sub will_render ($$;$) {
830         my $page=shift;
831         my $dest=shift;
832         my $clear=shift;
833
834         # Important security check.
835         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
836             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
837                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
838         }
839
840         if (! $clear || $cleared{$page}) {
841                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
842         }
843         else {
844                 foreach my $old (@{$renderedfiles{$page}}) {
845                         delete $destsources{$old};
846                 }
847                 $renderedfiles{$page}=[$dest];
848                 $cleared{$page}=1;
849         }
850         $destsources{$dest}=$page;
851
852         return 1;
853 }
854
855 sub bestlink ($$) {
856         my $page=shift;
857         my $link=shift;
858         
859         my $cwd=$page;
860         if ($link=~s/^\/+//) {
861                 # absolute links
862                 $cwd="";
863         }
864         $link=~s/\/$//;
865
866         do {
867                 my $l=$cwd;
868                 $l.="/" if length $l;
869                 $l.=$link;
870
871                 if (exists $links{$l}) {
872                         return $l;
873                 }
874                 elsif (exists $pagecase{lc $l}) {
875                         return $pagecase{lc $l};
876                 }
877         } while $cwd=~s{/?[^/]+$}{};
878
879         if (length $config{userdir}) {
880                 my $l = "$config{userdir}/".lc($link);
881                 if (exists $links{$l}) {
882                         return $l;
883                 }
884                 elsif (exists $pagecase{lc $l}) {
885                         return $pagecase{lc $l};
886                 }
887         }
888
889         #print STDERR "warning: page $page, broken link: $link\n";
890         return "";
891 }
892
893 sub isinlinableimage ($) {
894         my $file=shift;
895         
896         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
897 }
898
899 sub pagetitle ($;$) {
900         my $page=shift;
901         my $unescaped=shift;
902
903         if ($unescaped) {
904                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
905         }
906         else {
907                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
908         }
909
910         return $page;
911 }
912
913 sub titlepage ($) {
914         my $title=shift;
915         # support use w/o %config set
916         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
917         $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
918         return $title;
919 }
920
921 sub linkpage ($) {
922         my $link=shift;
923         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
924         $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
925         return $link;
926 }
927
928 sub cgiurl (@) {
929         my %params=@_;
930
931         return $config{cgiurl}."?".
932                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
933 }
934
935 sub baseurl (;$) {
936         my $page=shift;
937
938         return "$config{url}/" if ! defined $page;
939         
940         $page=htmlpage($page);
941         $page=~s/[^\/]+$//;
942         $page=~s/[^\/]+\//..\//g;
943         return $page;
944 }
945
946 sub abs2rel ($$) {
947         # Work around very innefficient behavior in File::Spec if abs2rel
948         # is passed two relative paths. It's much faster if paths are
949         # absolute! (Debian bug #376658; fixed in debian unstable now)
950         my $path="/".shift;
951         my $base="/".shift;
952
953         require File::Spec;
954         my $ret=File::Spec->abs2rel($path, $base);
955         $ret=~s/^// if defined $ret;
956         return $ret;
957 }
958
959 sub displaytime ($;$) {
960         # Plugins can override this function to mark up the time to
961         # display.
962         return '<span class="date">'.formattime(@_).'</span>';
963 }
964
965 sub formattime ($;$) {
966         # Plugins can override this function to format the time.
967         my $time=shift;
968         my $format=shift;
969         if (! defined $format) {
970                 $format=$config{timeformat};
971         }
972
973         # strftime doesn't know about encodings, so make sure
974         # its output is properly treated as utf8
975         return decode_utf8(POSIX::strftime($format, localtime($time)));
976 }
977
978 sub beautify_urlpath ($) {
979         my $url=shift;
980
981         # Ensure url is not an empty link, and if necessary,
982         # add ./ to avoid colon confusion.
983         if ($url !~ /^\// && $url !~ /^\.\.?\//) {
984                 $url="./$url";
985         }
986
987         if ($config{usedirs}) {
988                 $url =~ s!/index.$config{htmlext}$!/!;
989         }
990
991         return $url;
992 }
993
994 sub urlto ($$;$) {
995         my $to=shift;
996         my $from=shift;
997         my $absolute=shift;
998         
999         if (! length $to) {
1000                 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1001         }
1002
1003         if (! $destsources{$to}) {
1004                 $to=htmlpage($to);
1005         }
1006
1007         if ($absolute) {
1008                 return $config{url}.beautify_urlpath("/".$to);
1009         }
1010
1011         my $link = abs2rel($to, dirname(htmlpage($from)));
1012
1013         return beautify_urlpath($link);
1014 }
1015
1016 sub htmllink ($$$;@) {
1017         my $lpage=shift; # the page doing the linking
1018         my $page=shift; # the page that will contain the link (different for inline)
1019         my $link=shift;
1020         my %opts=@_;
1021
1022         $link=~s/\/$//;
1023
1024         my $bestlink;
1025         if (! $opts{forcesubpage}) {
1026                 $bestlink=bestlink($lpage, $link);
1027         }
1028         else {
1029                 $bestlink="$lpage/".lc($link);
1030         }
1031
1032         my $linktext;
1033         if (defined $opts{linktext}) {
1034                 $linktext=$opts{linktext};
1035         }
1036         else {
1037                 $linktext=pagetitle(basename($link));
1038         }
1039         
1040         return "<span class=\"selflink\">$linktext</span>"
1041                 if length $bestlink && $page eq $bestlink &&
1042                    ! defined $opts{anchor};
1043         
1044         if (! $destsources{$bestlink}) {
1045                 $bestlink=htmlpage($bestlink);
1046
1047                 if (! $destsources{$bestlink}) {
1048                         return $linktext unless length $config{cgiurl};
1049                         return "<span class=\"createlink\"><a href=\"".
1050                                 cgiurl(
1051                                         do => "create",
1052                                         page => lc($link),
1053                                         from => $lpage
1054                                 ).
1055                                 "\" rel=\"nofollow\">?</a>$linktext</span>"
1056                 }
1057         }
1058         
1059         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1060         $bestlink=beautify_urlpath($bestlink);
1061         
1062         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1063                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1064         }
1065
1066         if (defined $opts{anchor}) {
1067                 $bestlink.="#".$opts{anchor};
1068         }
1069
1070         my @attrs;
1071         if (defined $opts{rel}) {
1072                 push @attrs, ' rel="'.$opts{rel}.'"';
1073         }
1074         if (defined $opts{class}) {
1075                 push @attrs, ' class="'.$opts{class}.'"';
1076         }
1077
1078         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1079 }
1080
1081 sub openiduser ($) {
1082         my $user=shift;
1083
1084         if ($user =~ m!^https?://! &&
1085             eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1086                 my $display;
1087
1088                 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1089                         # this works in at least 2.x
1090                         $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1091                 }
1092                 else {
1093                         # this only works in 1.x
1094                         my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1095                         $display=$oid->display;
1096                 }
1097
1098                 # Convert "user.somehost.com" to "user [somehost.com]"
1099                 # (also "user.somehost.co.uk")
1100                 if ($display !~ /\[/) {
1101                         $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1102                 }
1103                 # Convert "http://somehost.com/user" to "user [somehost.com]".
1104                 # (also "https://somehost.com/user/")
1105                 if ($display !~ /\[/) {
1106                         $display=~s/^https?:\/\/(.+)\/([^\/]+)\/?$/$2 [$1]/;
1107                 }
1108                 $display=~s!^https?://!!; # make sure this is removed
1109                 eval q{use CGI 'escapeHTML'};
1110                 error($@) if $@;
1111                 return escapeHTML($display);
1112         }
1113         return;
1114 }
1115
1116 sub userlink ($) {
1117         my $user=shift;
1118
1119         my $oiduser=eval { openiduser($user) };
1120         if (defined $oiduser) {
1121                 return "<a href=\"$user\">$oiduser</a>";
1122         }
1123         else {
1124                 eval q{use CGI 'escapeHTML'};
1125                 error($@) if $@;
1126
1127                 return htmllink("", "", escapeHTML(
1128                         length $config{userdir} ? $config{userdir}."/".$user : $user
1129                 ), noimageinline => 1);
1130         }
1131 }
1132
1133 sub htmlize ($$$$) {
1134         my $page=shift;
1135         my $destpage=shift;
1136         my $type=shift;
1137         my $content=shift;
1138         
1139         my $oneline = $content !~ /\n/;
1140
1141         if (exists $hooks{htmlize}{$type}) {
1142                 $content=$hooks{htmlize}{$type}{call}->(
1143                         page => $page,
1144                         content => $content,
1145                 );
1146         }
1147         else {
1148                 error("htmlization of $type not supported");
1149         }
1150
1151         run_hooks(sanitize => sub {
1152                 $content=shift->(
1153                         page => $page,
1154                         destpage => $destpage,
1155                         content => $content,
1156                 );
1157         });
1158         
1159         if ($oneline) {
1160                 # hack to get rid of enclosing junk added by markdown
1161                 # and other htmlizers
1162                 $content=~s/^<p>//i;
1163                 $content=~s/<\/p>$//i;
1164                 chomp $content;
1165         }
1166
1167         return $content;
1168 }
1169
1170 sub linkify ($$$) {
1171         my $page=shift;
1172         my $destpage=shift;
1173         my $content=shift;
1174
1175         run_hooks(linkify => sub {
1176                 $content=shift->(
1177                         page => $page,
1178                         destpage => $destpage,
1179                         content => $content,
1180                 );
1181         });
1182         
1183         return $content;
1184 }
1185
1186 our %preprocessing;
1187 our $preprocess_preview=0;
1188 sub preprocess ($$$;$$) {
1189         my $page=shift; # the page the data comes from
1190         my $destpage=shift; # the page the data will appear in (different for inline)
1191         my $content=shift;
1192         my $scan=shift;
1193         my $preview=shift;
1194
1195         # Using local because it needs to be set within any nested calls
1196         # of this function.
1197         local $preprocess_preview=$preview if defined $preview;
1198
1199         my $handle=sub {
1200                 my $escape=shift;
1201                 my $prefix=shift;
1202                 my $command=shift;
1203                 my $params=shift;
1204                 $params="" if ! defined $params;
1205
1206                 if (length $escape) {
1207                         return "[[$prefix$command $params]]";
1208                 }
1209                 elsif (exists $hooks{preprocess}{$command}) {
1210                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1211                         # Note: preserve order of params, some plugins may
1212                         # consider it significant.
1213                         my @params;
1214                         while ($params =~ m{
1215                                 (?:([-\w]+)=)?          # 1: named parameter key?
1216                                 (?:
1217                                         """(.*?)"""     # 2: triple-quoted value
1218                                 |
1219                                         "([^"]+)"       # 3: single-quoted value
1220                                 |
1221                                         (\S+)           # 4: unquoted value
1222                                 )
1223                                 (?:\s+|$)               # delimiter to next param
1224                         }sgx) {
1225                                 my $key=$1;
1226                                 my $val;
1227                                 if (defined $2) {
1228                                         $val=$2;
1229                                         $val=~s/\r\n/\n/mg;
1230                                         $val=~s/^\n+//g;
1231                                         $val=~s/\n+$//g;
1232                                 }
1233                                 elsif (defined $3) {
1234                                         $val=$3;
1235                                 }
1236                                 elsif (defined $4) {
1237                                         $val=$4;
1238                                 }
1239
1240                                 if (defined $key) {
1241                                         push @params, $key, $val;
1242                                 }
1243                                 else {
1244                                         push @params, $val, '';
1245                                 }
1246                         }
1247                         if ($preprocessing{$page}++ > 3) {
1248                                 # Avoid loops of preprocessed pages preprocessing
1249                                 # other pages that preprocess them, etc.
1250                                 return "[[!$command <span class=\"error\">".
1251                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1252                                                 $page, $preprocessing{$page}).
1253                                         "</span>]]";
1254                         }
1255                         my $ret;
1256                         if (! $scan) {
1257                                 $ret=eval {
1258                                         $hooks{preprocess}{$command}{call}->(
1259                                                 @params,
1260                                                 page => $page,
1261                                                 destpage => $destpage,
1262                                                 preview => $preprocess_preview,
1263                                         );
1264                                 };
1265                                 if ($@) {
1266                                         my $error=$@;
1267                                         chomp $error;
1268                                         $ret="[[!$command <span class=\"error\">".
1269                                                 gettext("Error").": $error"."</span>]]";
1270                                 }
1271                         }
1272                         else {
1273                                 # use void context during scan pass
1274                                 eval {
1275                                         $hooks{preprocess}{$command}{call}->(
1276                                                 @params,
1277                                                 page => $page,
1278                                                 destpage => $destpage,
1279                                                 preview => $preprocess_preview,
1280                                         );
1281                                 };
1282                                 $ret="";
1283                         }
1284                         $preprocessing{$page}--;
1285                         return $ret;
1286                 }
1287                 else {
1288                         return "[[$prefix$command $params]]";
1289                 }
1290         };
1291         
1292         my $regex;
1293         if ($config{prefix_directives}) {
1294                 $regex = qr{
1295                         (\\?)           # 1: escape?
1296                         \[\[(!)         # directive open; 2: prefix
1297                         ([-\w]+)        # 3: command
1298                         (               # 4: the parameters..
1299                                 \s+     # Must have space if parameters present
1300                                 (?:
1301                                         (?:[-\w]+=)?            # named parameter key?
1302                                         (?:
1303                                                 """.*?"""       # triple-quoted value
1304                                                 |
1305                                                 "[^"]+"         # single-quoted value
1306                                                 |
1307                                                 [^"\s\]]+       # unquoted value
1308                                         )
1309                                         \s*                     # whitespace or end
1310                                                                 # of directive
1311                                 )
1312                         *)?             # 0 or more parameters
1313                         \]\]            # directive closed
1314                 }sx;
1315         }
1316         else {
1317                 $regex = qr{
1318                         (\\?)           # 1: escape?
1319                         \[\[(!?)        # directive open; 2: optional prefix
1320                         ([-\w]+)        # 3: command
1321                         \s+
1322                         (               # 4: the parameters..
1323                                 (?:
1324                                         (?:[-\w]+=)?            # named parameter key?
1325                                         (?:
1326                                                 """.*?"""       # triple-quoted value
1327                                                 |
1328                                                 "[^"]+"         # single-quoted value
1329                                                 |
1330                                                 [^"\s\]]+       # unquoted value
1331                                         )
1332                                         \s*                     # whitespace or end
1333                                                                 # of directive
1334                                 )
1335                         *)              # 0 or more parameters
1336                         \]\]            # directive closed
1337                 }sx;
1338         }
1339
1340         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1341         return $content;
1342 }
1343
1344 sub filter ($$$) {
1345         my $page=shift;
1346         my $destpage=shift;
1347         my $content=shift;
1348
1349         run_hooks(filter => sub {
1350                 $content=shift->(page => $page, destpage => $destpage, 
1351                         content => $content);
1352         });
1353
1354         return $content;
1355 }
1356
1357 sub indexlink () {
1358         return "<a href=\"$config{url}\">$config{wikiname}</a>";
1359 }
1360
1361 sub check_canedit ($$$;$) {
1362         my $page=shift;
1363         my $q=shift;
1364         my $session=shift;
1365         my $nonfatal=shift;
1366         
1367         my $canedit;
1368         run_hooks(canedit => sub {
1369                 return if defined $canedit;
1370                 my $ret=shift->($page, $q, $session);
1371                 if (defined $ret) {
1372                         if ($ret eq "") {
1373                                 $canedit=1;
1374                         }
1375                         elsif (ref $ret eq 'CODE') {
1376                                 $ret->() unless $nonfatal;
1377                                 $canedit=0;
1378                         }
1379                         elsif (defined $ret) {
1380                                 error($ret) unless $nonfatal;
1381                                 $canedit=0;
1382                         }
1383                 }
1384         });
1385         return defined $canedit ? $canedit : 1;
1386 }
1387
1388 sub check_content (@) {
1389         my %params=@_;
1390         
1391         return 1 if ! exists $hooks{checkcontent}; # optimisation
1392
1393         if (exists $pagesources{$params{page}}) {
1394                 my @diff;
1395                 my %old=map { $_ => 1 }
1396                         split("\n", readfile(srcfile($pagesources{$params{page}})));
1397                 foreach my $line (split("\n", $params{content})) {
1398                         push @diff, $line if ! exists $old{$_};
1399                 }
1400                 $params{diff}=join("\n", @diff);
1401         }
1402
1403         my $ok;
1404         run_hooks(checkcontent => sub {
1405                 return if defined $ok;
1406                 my $ret=shift->(%params);
1407                 if (defined $ret) {
1408                         if ($ret eq "") {
1409                                 $ok=1;
1410                         }
1411                         elsif (ref $ret eq 'CODE') {
1412                                 $ret->() unless $params{nonfatal};
1413                                 $ok=0;
1414                         }
1415                         elsif (defined $ret) {
1416                                 error($ret) unless $params{nonfatal};
1417                                 $ok=0;
1418                         }
1419                 }
1420
1421         });
1422         return defined $ok ? $ok : 1;
1423 }
1424
1425 my $wikilock;
1426
1427 sub lockwiki () {
1428         # Take an exclusive lock on the wiki to prevent multiple concurrent
1429         # run issues. The lock will be dropped on program exit.
1430         if (! -d $config{wikistatedir}) {
1431                 mkdir($config{wikistatedir});
1432         }
1433         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1434                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1435         if (! flock($wikilock, 2)) { # LOCK_EX
1436                 error("failed to get lock");
1437         }
1438         return 1;
1439 }
1440
1441 sub unlockwiki () {
1442         POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1443         return close($wikilock) if $wikilock;
1444         return;
1445 }
1446
1447 my $commitlock;
1448
1449 sub commit_hook_enabled () {
1450         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1451                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1452         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1453                 close($commitlock) || error("failed closing commitlock: $!");
1454                 return 0;
1455         }
1456         close($commitlock) || error("failed closing commitlock: $!");
1457         return 1;
1458 }
1459
1460 sub disable_commit_hook () {
1461         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1462                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1463         if (! flock($commitlock, 2)) { # LOCK_EX
1464                 error("failed to get commit lock");
1465         }
1466         return 1;
1467 }
1468
1469 sub enable_commit_hook () {
1470         return close($commitlock) if $commitlock;
1471         return;
1472 }
1473
1474 sub loadindex () {
1475         %oldrenderedfiles=%pagectime=();
1476         if (! $config{rebuild}) {
1477                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1478                 %destsources=%renderedfiles=%pagecase=%pagestate=
1479                 %depends_simple=();
1480         }
1481         my $in;
1482         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1483                 if (-e "$config{wikistatedir}/index") {
1484                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1485                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1486                 }
1487                 else {
1488                         return;
1489                 }
1490         }
1491
1492         my $index=Storable::fd_retrieve($in);
1493         if (! defined $index) {
1494                 return 0;
1495         }
1496
1497         my $pages;
1498         if (exists $index->{version} && ! ref $index->{version}) {
1499                 $pages=$index->{page};
1500                 %wikistate=%{$index->{state}};
1501         }
1502         else {
1503                 $pages=$index;
1504                 %wikistate=();
1505         }
1506
1507         foreach my $src (keys %$pages) {
1508                 my $d=$pages->{$src};
1509                 my $page=pagename($src);
1510                 $pagectime{$page}=$d->{ctime};
1511                 if (! $config{rebuild}) {
1512                         $pagesources{$page}=$src;
1513                         $pagemtime{$page}=$d->{mtime};
1514                         $renderedfiles{$page}=$d->{dest};
1515                         if (exists $d->{links} && ref $d->{links}) {
1516                                 $links{$page}=$d->{links};
1517                                 $oldlinks{$page}=[@{$d->{links}}];
1518                         }
1519                         if (exists $d->{depends_simple}) {
1520                                 $depends_simple{$page}={
1521                                         map { $_ => 1 } @{$d->{depends_simple}}
1522                                 };
1523                         }
1524                         if (exists $d->{dependslist}) {
1525                                 $depends{$page}={
1526                                         map { $_ => 1 } @{$d->{dependslist}}
1527                                 };
1528                         }
1529                         elsif (exists $d->{depends}) {
1530                                 $depends{$page}={$d->{depends} => 1};
1531                         }
1532                         if (exists $d->{state}) {
1533                                 $pagestate{$page}=$d->{state};
1534                         }
1535                 }
1536                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1537         }
1538         foreach my $page (keys %pagesources) {
1539                 $pagecase{lc $page}=$page;
1540         }
1541         foreach my $page (keys %renderedfiles) {
1542                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1543         }
1544         return close($in);
1545 }
1546
1547 sub saveindex () {
1548         run_hooks(savestate => sub { shift->() });
1549
1550         my %hookids;
1551         foreach my $type (keys %hooks) {
1552                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1553         }
1554         my @hookids=keys %hookids;
1555
1556         if (! -d $config{wikistatedir}) {
1557                 mkdir($config{wikistatedir});
1558         }
1559         my $newfile="$config{wikistatedir}/indexdb.new";
1560         my $cleanup = sub { unlink($newfile) };
1561         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1562
1563         my %index;
1564         foreach my $page (keys %pagemtime) {
1565                 next unless $pagemtime{$page};
1566                 my $src=$pagesources{$page};
1567
1568                 $index{page}{$src}={
1569                         ctime => $pagectime{$page},
1570                         mtime => $pagemtime{$page},
1571                         dest => $renderedfiles{$page},
1572                         links => $links{$page},
1573                 };
1574
1575                 if (exists $depends{$page}) {
1576                         $index{page}{$src}{dependslist} = [ keys %{$depends{$page}} ];
1577                 }
1578
1579                 if (exists $depends_simple{$page}) {
1580                         $index{page}{$src}{depends_simple} = [ keys %{$depends_simple{$page}} ];
1581                 }
1582
1583                 if (exists $pagestate{$page}) {
1584                         foreach my $id (@hookids) {
1585                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1586                                         $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1587                                 }
1588                         }
1589                 }
1590         }
1591
1592         $index{state}={};
1593         foreach my $id (@hookids) {
1594                 foreach my $key (keys %{$wikistate{$id}}) {
1595                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
1596                 }
1597         }
1598         
1599         $index{version}="3";
1600         my $ret=Storable::nstore_fd(\%index, $out);
1601         return if ! defined $ret || ! $ret;
1602         close $out || error("failed saving to $newfile: $!", $cleanup);
1603         rename($newfile, "$config{wikistatedir}/indexdb") ||
1604                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1605         
1606         return 1;
1607 }
1608
1609 sub template_file ($) {
1610         my $template=shift;
1611
1612         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1613                 return "$dir/$template" if -e "$dir/$template";
1614         }
1615         return;
1616 }
1617
1618 sub template_params (@) {
1619         my $filename=template_file(shift);
1620
1621         if (! defined $filename) {
1622                 return if wantarray;
1623                 return "";
1624         }
1625
1626         my @ret=(
1627                 filter => sub {
1628                         my $text_ref = shift;
1629                         ${$text_ref} = decode_utf8(${$text_ref});
1630                 },
1631                 filename => $filename,
1632                 loop_context_vars => 1,
1633                 die_on_bad_params => 0,
1634                 @_
1635         );
1636         return wantarray ? @ret : {@ret};
1637 }
1638
1639 sub template ($;@) {
1640         require HTML::Template;
1641         return HTML::Template->new(template_params(@_));
1642 }
1643
1644 sub misctemplate ($$;@) {
1645         my $title=shift;
1646         my $pagebody=shift;
1647         
1648         my $template=template("misc.tmpl");
1649         $template->param(
1650                 title => $title,
1651                 indexlink => indexlink(),
1652                 wikiname => $config{wikiname},
1653                 pagebody => $pagebody,
1654                 baseurl => baseurl(),
1655                 @_,
1656         );
1657         run_hooks(pagetemplate => sub {
1658                 shift->(page => "", destpage => "", template => $template);
1659         });
1660         return $template->output;
1661 }
1662
1663 sub hook (@) {
1664         my %param=@_;
1665         
1666         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1667                 error 'hook requires type, call, and id parameters';
1668         }
1669
1670         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1671         
1672         $hooks{$param{type}}{$param{id}}=\%param;
1673         return 1;
1674 }
1675
1676 sub run_hooks ($$) {
1677         # Calls the given sub for each hook of the given type,
1678         # passing it the hook function to call.
1679         my $type=shift;
1680         my $sub=shift;
1681
1682         if (exists $hooks{$type}) {
1683                 my (@first, @middle, @last);
1684                 foreach my $id (keys %{$hooks{$type}}) {
1685                         if ($hooks{$type}{$id}{first}) {
1686                                 push @first, $id;
1687                         }
1688                         elsif ($hooks{$type}{$id}{last}) {
1689                                 push @last, $id;
1690                         }
1691                         else {
1692                                 push @middle, $id;
1693                         }
1694                 }
1695                 foreach my $id (@first, @middle, @last) {
1696                         $sub->($hooks{$type}{$id}{call});
1697                 }
1698         }
1699
1700         return 1;
1701 }
1702
1703 sub rcs_update () {
1704         $hooks{rcs}{rcs_update}{call}->(@_);
1705 }
1706
1707 sub rcs_prepedit ($) {
1708         $hooks{rcs}{rcs_prepedit}{call}->(@_);
1709 }
1710
1711 sub rcs_commit ($$$;$$) {
1712         $hooks{rcs}{rcs_commit}{call}->(@_);
1713 }
1714
1715 sub rcs_commit_staged ($$$) {
1716         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1717 }
1718
1719 sub rcs_add ($) {
1720         $hooks{rcs}{rcs_add}{call}->(@_);
1721 }
1722
1723 sub rcs_remove ($) {
1724         $hooks{rcs}{rcs_remove}{call}->(@_);
1725 }
1726
1727 sub rcs_rename ($$) {
1728         $hooks{rcs}{rcs_rename}{call}->(@_);
1729 }
1730
1731 sub rcs_recentchanges ($) {
1732         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1733 }
1734
1735 sub rcs_diff ($) {
1736         $hooks{rcs}{rcs_diff}{call}->(@_);
1737 }
1738
1739 sub rcs_getctime ($) {
1740         $hooks{rcs}{rcs_getctime}{call}->(@_);
1741 }
1742
1743 sub rcs_receive () {
1744         $hooks{rcs}{rcs_receive}{call}->();
1745 }
1746
1747 sub add_depends ($$) {
1748         my $page=shift;
1749         my $pagespec=shift;
1750
1751         if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1752                 $pagespec !~ /[\s*?()!]/) {
1753                 # a simple dependency, which can be matched by string eq
1754                 $depends_simple{$page}{lc $pagespec} = 1;
1755                 return 1;
1756         }
1757
1758         return unless pagespec_valid($pagespec);
1759
1760         $depends{$page}{$pagespec} = 1;
1761         return 1;
1762 }
1763
1764 sub file_pruned ($$) {
1765         require File::Spec;
1766         my $file=File::Spec->canonpath(shift);
1767         my $base=File::Spec->canonpath(shift);
1768         $file =~ s#^\Q$base\E/+##;
1769
1770         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1771         return $file =~ m/$regexp/ && $file ne $base;
1772 }
1773
1774 sub define_gettext () {
1775         # If translation is needed, redefine the gettext function to do it.
1776         # Otherwise, it becomes a quick no-op.
1777         no warnings 'redefine';
1778         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1779             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1780             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1781                 *gettext=sub {
1782                         my $gettext_obj=eval q{
1783                                 use Locale::gettext q{textdomain};
1784                                 Locale::gettext->domain('ikiwiki')
1785                         };
1786
1787                         if ($gettext_obj) {
1788                                 $gettext_obj->get(shift);
1789                         }
1790                         else {
1791                                 return shift;
1792                         }
1793                 };
1794         }
1795         else {
1796                 *gettext=sub { return shift };
1797         }
1798 }
1799
1800 sub gettext {
1801         define_gettext();
1802         gettext(@_);
1803 }
1804
1805 sub yesno ($) {
1806         my $val=shift;
1807
1808         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1809 }
1810
1811 sub inject {
1812         # Injects a new function into the symbol table to replace an
1813         # exported function.
1814         my %params=@_;
1815
1816         # This is deep ugly perl foo, beware.
1817         no strict;
1818         no warnings;
1819         if (! defined $params{parent}) {
1820                 $params{parent}='::';
1821                 $params{old}=\&{$params{name}};
1822                 $params{name}=~s/.*:://;
1823         }
1824         my $parent=$params{parent};
1825         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1826                 $ns = $params{parent} . $ns;
1827                 inject(%params, parent => $ns) unless $ns eq '::main::';
1828                 *{$ns . $params{name}} = $params{call}
1829                         if exists ${$ns}{$params{name}} &&
1830                            \&{${$ns}{$params{name}}} == $params{old};
1831         }
1832         use strict;
1833         use warnings;
1834 }
1835
1836 sub add_link ($$) {
1837         my $page=shift;
1838         my $link=shift;
1839
1840         push @{$links{$page}}, $link
1841                 unless grep { $_ eq $link } @{$links{$page}};
1842 }
1843
1844 sub pagespec_translate ($) {
1845         my $spec=shift;
1846
1847         # Convert spec to perl code.
1848         my $code="";
1849         my @data;
1850         while ($spec=~m{
1851                 \s*             # ignore whitespace
1852                 (               # 1: match a single word
1853                         \!              # !
1854                 |
1855                         \(              # (
1856                 |
1857                         \)              # )
1858                 |
1859                         \w+\([^\)]*\)   # command(params)
1860                 |
1861                         [^\s()]+        # any other text
1862                 )
1863                 \s*             # ignore whitespace
1864         }igx) {
1865                 my $word=$1;
1866                 if (lc $word eq 'and') {
1867                         $code.=' &&';
1868                 }
1869                 elsif (lc $word eq 'or') {
1870                         $code.=' ||';
1871                 }
1872                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1873                         $code.=' '.$word;
1874                 }
1875                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1876                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1877                                 push @data, $2;
1878                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
1879                         }
1880                         else {
1881                                 push @data, qq{unknown function in pagespec "$word"};
1882                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
1883                         }
1884                 }
1885                 else {
1886                         push @data, $word;
1887                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
1888                 }
1889         }
1890
1891         if (! length $code) {
1892                 $code="IkiWiki::FailReason->new('empty pagespec')";
1893         }
1894
1895         no warnings;
1896         return eval 'sub { my $page=shift; '.$code.' }';
1897 }
1898
1899 sub pagespec_match ($$;@) {
1900         my $page=shift;
1901         my $spec=shift;
1902         my @params=@_;
1903
1904         # Backwards compatability with old calling convention.
1905         if (@params == 1) {
1906                 unshift @params, 'location';
1907         }
1908
1909         my $sub=pagespec_translate($spec);
1910         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
1911                 if $@ || ! defined $sub;
1912         return $sub->($page, @params);
1913 }
1914
1915 sub pagespec_match_list ($$;@) {
1916         my $pages=shift;
1917         my $spec=shift;
1918         my @params=@_;
1919
1920         my $sub=pagespec_translate($spec);
1921         error "syntax error in pagespec \"$spec\""
1922                 if $@ || ! defined $sub;
1923         
1924         my @ret;
1925         my $r;
1926         foreach my $page (@$pages) {
1927                 $r=$sub->($page, @params);
1928                 push @ret, $page if $r;
1929         }
1930
1931         if (! @ret && defined $r && $r->isa("IkiWiki::ErrorReason")) {
1932                 error(sprintf(gettext("cannot match pages: %s"), $r));
1933         }
1934         else {
1935                 return @ret;
1936         }
1937 }
1938
1939 sub pagespec_valid ($) {
1940         my $spec=shift;
1941
1942         my $sub=pagespec_translate($spec);
1943         return ! $@;
1944 }
1945
1946 sub glob2re ($) {
1947         my $re=quotemeta(shift);
1948         $re=~s/\\\*/.*/g;
1949         $re=~s/\\\?/./g;
1950         return $re;
1951 }
1952
1953 package IkiWiki::FailReason;
1954
1955 use overload (
1956         '""'    => sub { ${$_[0]} },
1957         '0+'    => sub { 0 },
1958         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1959         fallback => 1,
1960 );
1961
1962 sub new {
1963         my $class = shift;
1964         my $value = shift;
1965         return bless \$value, $class;
1966 }
1967
1968 package IkiWiki::ErrorReason;
1969
1970 our @ISA = 'IkiWiki::FailReason';
1971
1972 package IkiWiki::SuccessReason;
1973
1974 use overload (
1975         '""'    => sub { ${$_[0]} },
1976         '0+'    => sub { 1 },
1977         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
1978         fallback => 1,
1979 );
1980
1981 sub new {
1982         my $class = shift;
1983         my $value = shift;
1984         return bless \$value, $class;
1985 };
1986
1987 package IkiWiki::PageSpec;
1988
1989 sub derel ($$) {
1990         my $path=shift;
1991         my $from=shift;
1992
1993         if ($path =~ m!^\./!) {
1994                 $from=~s#/?[^/]+$## if defined $from;
1995                 $path=~s#^\./##;
1996                 $path="$from/$path" if length $from;
1997         }
1998
1999         return $path;
2000 }
2001
2002 sub match_glob ($$;@) {
2003         my $page=shift;
2004         my $glob=shift;
2005         my %params=@_;
2006         
2007         $glob=derel($glob, $params{location});
2008
2009         my $regexp=IkiWiki::glob2re($glob);
2010         if ($page=~/^$regexp$/i) {
2011                 if (! IkiWiki::isinternal($page) || $params{internal}) {
2012                         return IkiWiki::SuccessReason->new("$glob matches $page");
2013                 }
2014                 else {
2015                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2016                 }
2017         }
2018         else {
2019                 return IkiWiki::FailReason->new("$glob does not match $page");
2020         }
2021 }
2022
2023 sub match_internal ($$;@) {
2024         return match_glob($_[0], $_[1], @_, internal => 1)
2025 }
2026
2027 sub match_link ($$;@) {
2028         my $page=shift;
2029         my $link=lc(shift);
2030         my %params=@_;
2031
2032         $link=derel($link, $params{location});
2033         my $from=exists $params{location} ? $params{location} : '';
2034
2035         my $links = $IkiWiki::links{$page};
2036         return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
2037         my $bestlink = IkiWiki::bestlink($from, $link);
2038         foreach my $p (@{$links}) {
2039                 if (length $bestlink) {
2040                         return IkiWiki::SuccessReason->new("$page links to $link")
2041                                 if $bestlink eq IkiWiki::bestlink($page, $p);
2042                 }
2043                 else {
2044                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
2045                                 if match_glob($p, $link, %params);
2046                         $p=~s/^\///;
2047                         $link=~s/^\///;
2048                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
2049                                 if match_glob($p, $link, %params);
2050                 }
2051         }
2052         return IkiWiki::FailReason->new("$page does not link to $link");
2053 }
2054
2055 sub match_backlink ($$;@) {
2056         return match_link($_[1], $_[0], @_);
2057 }
2058
2059 sub match_created_before ($$;@) {
2060         my $page=shift;
2061         my $testpage=shift;
2062         my %params=@_;
2063         
2064         $testpage=derel($testpage, $params{location});
2065
2066         if (exists $IkiWiki::pagectime{$testpage}) {
2067                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2068                         return IkiWiki::SuccessReason->new("$page created before $testpage");
2069                 }
2070                 else {
2071                         return IkiWiki::FailReason->new("$page not created before $testpage");
2072                 }
2073         }
2074         else {
2075                 return IkiWiki::ErrorReason->new("$testpage does not exist");
2076         }
2077 }
2078
2079 sub match_created_after ($$;@) {
2080         my $page=shift;
2081         my $testpage=shift;
2082         my %params=@_;
2083         
2084         $testpage=derel($testpage, $params{location});
2085
2086         if (exists $IkiWiki::pagectime{$testpage}) {
2087                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2088                         return IkiWiki::SuccessReason->new("$page created after $testpage");
2089                 }
2090                 else {
2091                         return IkiWiki::FailReason->new("$page not created after $testpage");
2092                 }
2093         }
2094         else {
2095                 return IkiWiki::ErrorReason->new("$testpage does not exist");
2096         }
2097 }
2098
2099 sub match_creation_day ($$;@) {
2100         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2101                 return IkiWiki::SuccessReason->new('creation_day matched');
2102         }
2103         else {
2104                 return IkiWiki::FailReason->new('creation_day did not match');
2105         }
2106 }
2107
2108 sub match_creation_month ($$;@) {
2109         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2110                 return IkiWiki::SuccessReason->new('creation_month matched');
2111         }
2112         else {
2113                 return IkiWiki::FailReason->new('creation_month did not match');
2114         }
2115 }
2116
2117 sub match_creation_year ($$;@) {
2118         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2119                 return IkiWiki::SuccessReason->new('creation_year matched');
2120         }
2121         else {
2122                 return IkiWiki::FailReason->new('creation_year did not match');
2123         }
2124 }
2125
2126 sub match_user ($$;@) {
2127         shift;
2128         my $user=shift;
2129         my %params=@_;
2130         
2131         if (! exists $params{user}) {
2132                 return IkiWiki::ErrorReason->new("no user specified");
2133         }
2134
2135         if (defined $params{user} && lc $params{user} eq lc $user) {
2136                 return IkiWiki::SuccessReason->new("user is $user");
2137         }
2138         elsif (! defined $params{user}) {
2139                 return IkiWiki::FailReason->new("not logged in");
2140         }
2141         else {
2142                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2143         }
2144 }
2145
2146 sub match_admin ($$;@) {
2147         shift;
2148         shift;
2149         my %params=@_;
2150         
2151         if (! exists $params{user}) {
2152                 return IkiWiki::ErrorReason->new("no user specified");
2153         }
2154
2155         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2156                 return IkiWiki::SuccessReason->new("user is an admin");
2157         }
2158         elsif (! defined $params{user}) {
2159                 return IkiWiki::FailReason->new("not logged in");
2160         }
2161         else {
2162                 return IkiWiki::FailReason->new("user is not an admin");
2163         }
2164 }
2165
2166 sub match_ip ($$;@) {
2167         shift;
2168         my $ip=shift;
2169         my %params=@_;
2170         
2171         if (! exists $params{ip}) {
2172                 return IkiWiki::ErrorReason->new("no IP specified");
2173         }
2174
2175         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2176                 return IkiWiki::SuccessReason->new("IP is $ip");
2177         }
2178         else {
2179                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2180         }
2181 }
2182
2183 1