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