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