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