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