]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki.pm
check oldrenderedfiles too
[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                 $test=dirname($test);
827         }
828
829         my $dir=dirname("$destdir/$file");
830         if (! -d $dir) {
831                 my $d="";
832                 foreach my $s (split(m!/+!, $dir)) {
833                         $d.="$s/";
834                         if (! -d $d) {
835                                 mkdir($d) || error("failed to create directory $d: $!");
836                         }
837                 }
838         }
839
840         return 1;
841 }
842
843 sub writefile ($$$;$$) {
844         my $file=shift; # can include subdirs
845         my $destdir=shift; # directory to put file in
846         my $content=shift;
847         my $binary=shift;
848         my $writer=shift;
849         
850         prep_writefile($file, $destdir);
851         
852         my $newfile="$destdir/$file.ikiwiki-new";
853         if (-l $newfile) {
854                 error("cannot write to a symlink ($newfile)");
855         }
856         
857         my $cleanup = sub { unlink($newfile) };
858         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
859         binmode($out) if ($binary);
860         if ($writer) {
861                 $writer->(\*$out, $cleanup);
862         }
863         else {
864                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
865         }
866         close $out || error("failed saving $newfile: $!", $cleanup);
867         rename($newfile, "$destdir/$file") || 
868                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
869
870         return 1;
871 }
872
873 my %cleared;
874 sub will_render ($$;$) {
875         my $page=shift;
876         my $dest=shift;
877         my $clear=shift;
878
879         # Important security check.
880         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
881             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
882                 my $from_other_page=0;
883                 foreach my $p (keys %renderedfiles) {
884                         if (grep {
885                                 $_ eq $dest ||
886                                 dirname($_) eq $dest
887                             } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
888                                 $from_other_page=1;
889                                 last;
890                         }
891                 }
892
893                 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
894                         unless $from_other_page;
895         }
896
897         if (! $clear || $cleared{$page}) {
898                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
899         }
900         else {
901                 foreach my $old (@{$renderedfiles{$page}}) {
902                         delete $destsources{$old};
903                 }
904                 $renderedfiles{$page}=[$dest];
905                 $cleared{$page}=1;
906         }
907         $destsources{$dest}=$page;
908
909         return 1;
910 }
911
912 sub bestlink ($$) {
913         my $page=shift;
914         my $link=shift;
915         
916         my $cwd=$page;
917         if ($link=~s/^\/+//) {
918                 # absolute links
919                 $cwd="";
920         }
921         $link=~s/\/$//;
922
923         do {
924                 my $l=$cwd;
925                 $l.="/" if length $l;
926                 $l.=$link;
927
928                 if (exists $pagesources{$l}) {
929                         return $l;
930                 }
931                 elsif (exists $pagecase{lc $l}) {
932                         return $pagecase{lc $l};
933                 }
934         } while $cwd=~s{/?[^/]+$}{};
935
936         if (length $config{userdir}) {
937                 my $l = "$config{userdir}/".lc($link);
938                 if (exists $pagesources{$l}) {
939                         return $l;
940                 }
941                 elsif (exists $pagecase{lc $l}) {
942                         return $pagecase{lc $l};
943                 }
944         }
945
946         #print STDERR "warning: page $page, broken link: $link\n";
947         return "";
948 }
949
950 sub isinlinableimage ($) {
951         my $file=shift;
952         
953         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
954 }
955
956 sub pagetitle ($;$) {
957         my $page=shift;
958         my $unescaped=shift;
959
960         if ($unescaped) {
961                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
962         }
963         else {
964                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
965         }
966
967         return $page;
968 }
969
970 sub titlepage ($) {
971         my $title=shift;
972         # support use w/o %config set
973         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
974         $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
975         return $title;
976 }
977
978 sub linkpage ($) {
979         my $link=shift;
980         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
981         $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
982         return $link;
983 }
984
985 sub cgiurl (@) {
986         my %params=@_;
987
988         my $cgiurl=$config{cgiurl};
989         if (exists $params{cgiurl}) {
990                 $cgiurl=$params{cgiurl};
991                 delete $params{cgiurl};
992         }
993         return $cgiurl."?".
994                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
995 }
996
997 sub baseurl (;$) {
998         my $page=shift;
999
1000         return "$config{url}/" if ! defined $page;
1001         
1002         $page=htmlpage($page);
1003         $page=~s/[^\/]+$//;
1004         $page=~s/[^\/]+\//..\//g;
1005         return $page;
1006 }
1007
1008 sub abs2rel ($$) {
1009         # Work around very innefficient behavior in File::Spec if abs2rel
1010         # is passed two relative paths. It's much faster if paths are
1011         # absolute! (Debian bug #376658; fixed in debian unstable now)
1012         my $path="/".shift;
1013         my $base="/".shift;
1014
1015         require File::Spec;
1016         my $ret=File::Spec->abs2rel($path, $base);
1017         $ret=~s/^// if defined $ret;
1018         return $ret;
1019 }
1020
1021 sub displaytime ($;$$) {
1022         # Plugins can override this function to mark up the time to
1023         # display.
1024         my $time=formattime($_[0], $_[1]);
1025         if ($config{html5}) {
1026                 return '<time datetime="'.date_3339($_[0]).'"'.
1027                         ($_[2] ? ' pubdate="pubdate"' : '').
1028                         '>'.$time.'</time>';
1029         }
1030         else {
1031                 return '<span class="date">'.$time.'</span>';
1032         }
1033 }
1034
1035 sub formattime ($;$) {
1036         # Plugins can override this function to format the time.
1037         my $time=shift;
1038         my $format=shift;
1039         if (! defined $format) {
1040                 $format=$config{timeformat};
1041         }
1042
1043         # strftime doesn't know about encodings, so make sure
1044         # its output is properly treated as utf8
1045         return decode_utf8(POSIX::strftime($format, localtime($time)));
1046 }
1047
1048 sub date_3339 ($) {
1049         my $time=shift;
1050
1051         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1052         POSIX::setlocale(&POSIX::LC_TIME, "C");
1053         my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1054         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1055         return $ret;
1056 }
1057
1058 sub beautify_urlpath ($) {
1059         my $url=shift;
1060
1061         # Ensure url is not an empty link, and if necessary,
1062         # add ./ to avoid colon confusion.
1063         if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1064                 $url="./$url";
1065         }
1066
1067         if ($config{usedirs}) {
1068                 $url =~ s!/index.$config{htmlext}$!/!;
1069         }
1070
1071         return $url;
1072 }
1073
1074 sub urlto ($$;$) {
1075         my $to=shift;
1076         my $from=shift;
1077         my $absolute=shift;
1078         
1079         if (! length $to) {
1080                 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1081         }
1082
1083         if (! $destsources{$to}) {
1084                 $to=htmlpage($to);
1085         }
1086
1087         if ($absolute) {
1088                 return $config{url}.beautify_urlpath("/".$to);
1089         }
1090
1091         my $link = abs2rel($to, dirname(htmlpage($from)));
1092
1093         return beautify_urlpath($link);
1094 }
1095
1096 sub htmllink ($$$;@) {
1097         my $lpage=shift; # the page doing the linking
1098         my $page=shift; # the page that will contain the link (different for inline)
1099         my $link=shift;
1100         my %opts=@_;
1101
1102         $link=~s/\/$//;
1103
1104         my $bestlink;
1105         if (! $opts{forcesubpage}) {
1106                 $bestlink=bestlink($lpage, $link);
1107         }
1108         else {
1109                 $bestlink="$lpage/".lc($link);
1110         }
1111
1112         my $linktext;
1113         if (defined $opts{linktext}) {
1114                 $linktext=$opts{linktext};
1115         }
1116         else {
1117                 $linktext=pagetitle(basename($link));
1118         }
1119         
1120         return "<span class=\"selflink\">$linktext</span>"
1121                 if length $bestlink && $page eq $bestlink &&
1122                    ! defined $opts{anchor};
1123         
1124         if (! $destsources{$bestlink}) {
1125                 $bestlink=htmlpage($bestlink);
1126
1127                 if (! $destsources{$bestlink}) {
1128                         my $cgilink = "";
1129                         if (length $config{cgiurl}) {
1130                                 $cgilink = "<a href=\"".
1131                                         cgiurl(
1132                                                 do => "create",
1133                                                 page => lc($link),
1134                                                 from => $lpage
1135                                         )."\" rel=\"nofollow\">?</a>";
1136                         }
1137                         return "<span class=\"createlink\">$cgilink$linktext</span>"
1138                 }
1139         }
1140         
1141         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1142         $bestlink=beautify_urlpath($bestlink);
1143         
1144         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1145                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1146         }
1147
1148         if (defined $opts{anchor}) {
1149                 $bestlink.="#".$opts{anchor};
1150         }
1151
1152         my @attrs;
1153         foreach my $attr (qw{rel class title}) {
1154                 if (defined $opts{$attr}) {
1155                         push @attrs, " $attr=\"$opts{$attr}\"";
1156                 }
1157         }
1158
1159         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1160 }
1161
1162 sub userpage ($) {
1163         my $user=shift;
1164         return length $config{userdir} ? "$config{userdir}/$user" : $user;
1165 }
1166
1167 sub openiduser ($) {
1168         my $user=shift;
1169
1170         if ($user =~ m!^https?://! &&
1171             eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1172                 my $display;
1173
1174                 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1175                         $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1176                 }
1177                 else {
1178                         # backcompat with old version
1179                         my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1180                         $display=$oid->display;
1181                 }
1182
1183                 # Convert "user.somehost.com" to "user [somehost.com]"
1184                 # (also "user.somehost.co.uk")
1185                 if ($display !~ /\[/) {
1186                         $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1187                 }
1188                 # Convert "http://somehost.com/user" to "user [somehost.com]".
1189                 # (also "https://somehost.com/user/")
1190                 if ($display !~ /\[/) {
1191                         $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1192                 }
1193                 $display=~s!^https?://!!; # make sure this is removed
1194                 eval q{use CGI 'escapeHTML'};
1195                 error($@) if $@;
1196                 return escapeHTML($display);
1197         }
1198         return;
1199 }
1200
1201 sub htmlize ($$$$) {
1202         my $page=shift;
1203         my $destpage=shift;
1204         my $type=shift;
1205         my $content=shift;
1206         
1207         my $oneline = $content !~ /\n/;
1208         
1209         if (exists $hooks{htmlize}{$type}) {
1210                 $content=$hooks{htmlize}{$type}{call}->(
1211                         page => $page,
1212                         content => $content,
1213                 );
1214         }
1215         else {
1216                 error("htmlization of $type not supported");
1217         }
1218
1219         run_hooks(sanitize => sub {
1220                 $content=shift->(
1221                         page => $page,
1222                         destpage => $destpage,
1223                         content => $content,
1224                 );
1225         });
1226         
1227         if ($oneline) {
1228                 # hack to get rid of enclosing junk added by markdown
1229                 # and other htmlizers/sanitizers
1230                 $content=~s/^<p>//i;
1231                 $content=~s/<\/p>\n*$//i;
1232         }
1233
1234         return $content;
1235 }
1236
1237 sub linkify ($$$) {
1238         my $page=shift;
1239         my $destpage=shift;
1240         my $content=shift;
1241
1242         run_hooks(linkify => sub {
1243                 $content=shift->(
1244                         page => $page,
1245                         destpage => $destpage,
1246                         content => $content,
1247                 );
1248         });
1249         
1250         return $content;
1251 }
1252
1253 our %preprocessing;
1254 our $preprocess_preview=0;
1255 sub preprocess ($$$;$$) {
1256         my $page=shift; # the page the data comes from
1257         my $destpage=shift; # the page the data will appear in (different for inline)
1258         my $content=shift;
1259         my $scan=shift;
1260         my $preview=shift;
1261
1262         # Using local because it needs to be set within any nested calls
1263         # of this function.
1264         local $preprocess_preview=$preview if defined $preview;
1265
1266         my $handle=sub {
1267                 my $escape=shift;
1268                 my $prefix=shift;
1269                 my $command=shift;
1270                 my $params=shift;
1271                 $params="" if ! defined $params;
1272
1273                 if (length $escape) {
1274                         return "[[$prefix$command $params]]";
1275                 }
1276                 elsif (exists $hooks{preprocess}{$command}) {
1277                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1278                         # Note: preserve order of params, some plugins may
1279                         # consider it significant.
1280                         my @params;
1281                         while ($params =~ m{
1282                                 (?:([-\w]+)=)?          # 1: named parameter key?
1283                                 (?:
1284                                         """(.*?)"""     # 2: triple-quoted value
1285                                 |
1286                                         "([^"]*?)"      # 3: single-quoted value
1287                                 |
1288                                         (\S+)           # 4: unquoted value
1289                                 )
1290                                 (?:\s+|$)               # delimiter to next param
1291                         }sgx) {
1292                                 my $key=$1;
1293                                 my $val;
1294                                 if (defined $2) {
1295                                         $val=$2;
1296                                         $val=~s/\r\n/\n/mg;
1297                                         $val=~s/^\n+//g;
1298                                         $val=~s/\n+$//g;
1299                                 }
1300                                 elsif (defined $3) {
1301                                         $val=$3;
1302                                 }
1303                                 elsif (defined $4) {
1304                                         $val=$4;
1305                                 }
1306
1307                                 if (defined $key) {
1308                                         push @params, $key, $val;
1309                                 }
1310                                 else {
1311                                         push @params, $val, '';
1312                                 }
1313                         }
1314                         if ($preprocessing{$page}++ > 3) {
1315                                 # Avoid loops of preprocessed pages preprocessing
1316                                 # other pages that preprocess them, etc.
1317                                 return "[[!$command <span class=\"error\">".
1318                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1319                                                 $page, $preprocessing{$page}).
1320                                         "</span>]]";
1321                         }
1322                         my $ret;
1323                         if (! $scan) {
1324                                 $ret=eval {
1325                                         $hooks{preprocess}{$command}{call}->(
1326                                                 @params,
1327                                                 page => $page,
1328                                                 destpage => $destpage,
1329                                                 preview => $preprocess_preview,
1330                                         );
1331                                 };
1332                                 if ($@) {
1333                                         my $error=$@;
1334                                         chomp $error;
1335                                         $ret="[[!$command <span class=\"error\">".
1336                                                 gettext("Error").": $error"."</span>]]";
1337                                 }
1338                         }
1339                         else {
1340                                 # use void context during scan pass
1341                                 eval {
1342                                         $hooks{preprocess}{$command}{call}->(
1343                                                 @params,
1344                                                 page => $page,
1345                                                 destpage => $destpage,
1346                                                 preview => $preprocess_preview,
1347                                         );
1348                                 };
1349                                 $ret="";
1350                         }
1351                         $preprocessing{$page}--;
1352                         return $ret;
1353                 }
1354                 else {
1355                         return "[[$prefix$command $params]]";
1356                 }
1357         };
1358         
1359         my $regex;
1360         if ($config{prefix_directives}) {
1361                 $regex = qr{
1362                         (\\?)           # 1: escape?
1363                         \[\[(!)         # directive open; 2: prefix
1364                         ([-\w]+)        # 3: command
1365                         (               # 4: the parameters..
1366                                 \s+     # Must have space if parameters present
1367                                 (?:
1368                                         (?:[-\w]+=)?            # named parameter key?
1369                                         (?:
1370                                                 """.*?"""       # triple-quoted value
1371                                                 |
1372                                                 "[^"]*?"        # single-quoted value
1373                                                 |
1374                                                 [^"\s\]]+       # unquoted value
1375                                         )
1376                                         \s*                     # whitespace or end
1377                                                                 # of directive
1378                                 )
1379                         *)?             # 0 or more parameters
1380                         \]\]            # directive closed
1381                 }sx;
1382         }
1383         else {
1384                 $regex = qr{
1385                         (\\?)           # 1: escape?
1386                         \[\[(!?)        # directive open; 2: optional prefix
1387                         ([-\w]+)        # 3: command
1388                         \s+
1389                         (               # 4: the parameters..
1390                                 (?:
1391                                         (?:[-\w]+=)?            # named parameter key?
1392                                         (?:
1393                                                 """.*?"""       # triple-quoted value
1394                                                 |
1395                                                 "[^"]*?"        # single-quoted value
1396                                                 |
1397                                                 [^"\s\]]+       # unquoted value
1398                                         )
1399                                         \s*                     # whitespace or end
1400                                                                 # of directive
1401                                 )
1402                         *)              # 0 or more parameters
1403                         \]\]            # directive closed
1404                 }sx;
1405         }
1406
1407         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1408         return $content;
1409 }
1410
1411 sub filter ($$$) {
1412         my $page=shift;
1413         my $destpage=shift;
1414         my $content=shift;
1415
1416         run_hooks(filter => sub {
1417                 $content=shift->(page => $page, destpage => $destpage, 
1418                         content => $content);
1419         });
1420
1421         return $content;
1422 }
1423
1424 sub check_canedit ($$$;$) {
1425         my $page=shift;
1426         my $q=shift;
1427         my $session=shift;
1428         my $nonfatal=shift;
1429         
1430         my $canedit;
1431         run_hooks(canedit => sub {
1432                 return if defined $canedit;
1433                 my $ret=shift->($page, $q, $session);
1434                 if (defined $ret) {
1435                         if ($ret eq "") {
1436                                 $canedit=1;
1437                         }
1438                         elsif (ref $ret eq 'CODE') {
1439                                 $ret->() unless $nonfatal;
1440                                 $canedit=0;
1441                         }
1442                         elsif (defined $ret) {
1443                                 error($ret) unless $nonfatal;
1444                                 $canedit=0;
1445                         }
1446                 }
1447         });
1448         return defined $canedit ? $canedit : 1;
1449 }
1450
1451 sub check_content (@) {
1452         my %params=@_;
1453         
1454         return 1 if ! exists $hooks{checkcontent}; # optimisation
1455
1456         if (exists $pagesources{$params{page}}) {
1457                 my @diff;
1458                 my %old=map { $_ => 1 }
1459                         split("\n", readfile(srcfile($pagesources{$params{page}})));
1460                 foreach my $line (split("\n", $params{content})) {
1461                         push @diff, $line if ! exists $old{$line};
1462                 }
1463                 $params{diff}=join("\n", @diff);
1464         }
1465
1466         my $ok;
1467         run_hooks(checkcontent => sub {
1468                 return if defined $ok;
1469                 my $ret=shift->(%params);
1470                 if (defined $ret) {
1471                         if ($ret eq "") {
1472                                 $ok=1;
1473                         }
1474                         elsif (ref $ret eq 'CODE') {
1475                                 $ret->() unless $params{nonfatal};
1476                                 $ok=0;
1477                         }
1478                         elsif (defined $ret) {
1479                                 error($ret) unless $params{nonfatal};
1480                                 $ok=0;
1481                         }
1482                 }
1483
1484         });
1485         return defined $ok ? $ok : 1;
1486 }
1487
1488 my $wikilock;
1489
1490 sub lockwiki () {
1491         # Take an exclusive lock on the wiki to prevent multiple concurrent
1492         # run issues. The lock will be dropped on program exit.
1493         if (! -d $config{wikistatedir}) {
1494                 mkdir($config{wikistatedir});
1495         }
1496         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1497                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1498         if (! flock($wikilock, 2)) { # LOCK_EX
1499                 error("failed to get lock");
1500         }
1501         return 1;
1502 }
1503
1504 sub unlockwiki () {
1505         POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1506         return close($wikilock) if $wikilock;
1507         return;
1508 }
1509
1510 my $commitlock;
1511
1512 sub commit_hook_enabled () {
1513         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1514                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1515         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1516                 close($commitlock) || error("failed closing commitlock: $!");
1517                 return 0;
1518         }
1519         close($commitlock) || error("failed closing commitlock: $!");
1520         return 1;
1521 }
1522
1523 sub disable_commit_hook () {
1524         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1525                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1526         if (! flock($commitlock, 2)) { # LOCK_EX
1527                 error("failed to get commit lock");
1528         }
1529         return 1;
1530 }
1531
1532 sub enable_commit_hook () {
1533         return close($commitlock) if $commitlock;
1534         return;
1535 }
1536
1537 sub loadindex () {
1538         %oldrenderedfiles=%pagectime=();
1539         if (! $config{rebuild}) {
1540                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1541                 %destsources=%renderedfiles=%pagecase=%pagestate=
1542                 %depends_simple=%typedlinks=%oldtypedlinks=();
1543         }
1544         my $in;
1545         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1546                 if (-e "$config{wikistatedir}/index") {
1547                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1548                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1549                 }
1550                 else {
1551                         $config{gettime}=1; # first build
1552                         return;
1553                 }
1554         }
1555
1556         my $index=Storable::fd_retrieve($in);
1557         if (! defined $index) {
1558                 return 0;
1559         }
1560
1561         my $pages;
1562         if (exists $index->{version} && ! ref $index->{version}) {
1563                 $pages=$index->{page};
1564                 %wikistate=%{$index->{state}};
1565         }
1566         else {
1567                 $pages=$index;
1568                 %wikistate=();
1569         }
1570
1571         foreach my $src (keys %$pages) {
1572                 my $d=$pages->{$src};
1573                 my $page=pagename($src);
1574                 $pagectime{$page}=$d->{ctime};
1575                 $pagesources{$page}=$src;
1576                 if (! $config{rebuild}) {
1577                         $pagemtime{$page}=$d->{mtime};
1578                         $renderedfiles{$page}=$d->{dest};
1579                         if (exists $d->{links} && ref $d->{links}) {
1580                                 $links{$page}=$d->{links};
1581                                 $oldlinks{$page}=[@{$d->{links}}];
1582                         }
1583                         if (ref $d->{depends_simple} eq 'ARRAY') {
1584                                 # old format
1585                                 $depends_simple{$page}={
1586                                         map { $_ => 1 } @{$d->{depends_simple}}
1587                                 };
1588                         }
1589                         elsif (exists $d->{depends_simple}) {
1590                                 $depends_simple{$page}=$d->{depends_simple};
1591                         }
1592                         if (exists $d->{dependslist}) {
1593                                 # old format
1594                                 $depends{$page}={
1595                                         map { $_ => $DEPEND_CONTENT }
1596                                                 @{$d->{dependslist}}
1597                                 };
1598                         }
1599                         elsif (exists $d->{depends} && ! ref $d->{depends}) {
1600                                 # old format
1601                                 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1602                         }
1603                         elsif (exists $d->{depends}) {
1604                                 $depends{$page}=$d->{depends};
1605                         }
1606                         if (exists $d->{state}) {
1607                                 $pagestate{$page}=$d->{state};
1608                         }
1609                         if (exists $d->{typedlinks}) {
1610                                 $typedlinks{$page}=$d->{typedlinks};
1611
1612                                 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1613                                         next unless %$links;
1614                                         $oldtypedlinks{$page}{$type} = {%$links};
1615                                 }
1616                         }
1617                 }
1618                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1619         }
1620         foreach my $page (keys %pagesources) {
1621                 $pagecase{lc $page}=$page;
1622         }
1623         foreach my $page (keys %renderedfiles) {
1624                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1625         }
1626         return close($in);
1627 }
1628
1629 sub saveindex () {
1630         run_hooks(savestate => sub { shift->() });
1631
1632         my %hookids;
1633         foreach my $type (keys %hooks) {
1634                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1635         }
1636         my @hookids=keys %hookids;
1637
1638         if (! -d $config{wikistatedir}) {
1639                 mkdir($config{wikistatedir});
1640         }
1641         my $newfile="$config{wikistatedir}/indexdb.new";
1642         my $cleanup = sub { unlink($newfile) };
1643         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1644
1645         my %index;
1646         foreach my $page (keys %pagemtime) {
1647                 next unless $pagemtime{$page};
1648                 my $src=$pagesources{$page};
1649
1650                 $index{page}{$src}={
1651                         ctime => $pagectime{$page},
1652                         mtime => $pagemtime{$page},
1653                         dest => $renderedfiles{$page},
1654                         links => $links{$page},
1655                 };
1656
1657                 if (exists $depends{$page}) {
1658                         $index{page}{$src}{depends} = $depends{$page};
1659                 }
1660
1661                 if (exists $depends_simple{$page}) {
1662                         $index{page}{$src}{depends_simple} = $depends_simple{$page};
1663                 }
1664
1665                 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1666                         $index{page}{$src}{typedlinks} = $typedlinks{$page};
1667                 }
1668
1669                 if (exists $pagestate{$page}) {
1670                         foreach my $id (@hookids) {
1671                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1672                                         $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1673                                 }
1674                         }
1675                 }
1676         }
1677
1678         $index{state}={};
1679         foreach my $id (@hookids) {
1680                 foreach my $key (keys %{$wikistate{$id}}) {
1681                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
1682                 }
1683         }
1684         
1685         $index{version}="3";
1686         my $ret=Storable::nstore_fd(\%index, $out);
1687         return if ! defined $ret || ! $ret;
1688         close $out || error("failed saving to $newfile: $!", $cleanup);
1689         rename($newfile, "$config{wikistatedir}/indexdb") ||
1690                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1691         
1692         return 1;
1693 }
1694
1695 sub template_file ($) {
1696         my $name=shift;
1697         
1698         my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1699         if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1700                 $tpage=$pagesources{$tpage};
1701                 $name.=".tmpl";
1702         }
1703
1704         my $template=srcfile($tpage, 1);
1705         if (defined $template) {
1706                 return $template, $tpage, 1 if wantarray;
1707                 return $template;
1708         }
1709         else {
1710                 $name=~s:/::; # avoid path traversal
1711                 foreach my $dir ($config{templatedir},
1712                                  "$installdir/share/ikiwiki/templates") {
1713                         if (-e "$dir/$name") {
1714                                 $template="$dir/$name";
1715                                 last;
1716                         }
1717                 }
1718                 if (defined $template) {        
1719                         return $template, $tpage if wantarray;
1720                         return $template;
1721                 }
1722         }
1723
1724         return;
1725 }
1726
1727 sub template_depends ($$;@) {
1728         my $name=shift;
1729         my $page=shift;
1730         
1731         my ($filename, $tpage, $untrusted)=template_file($name);
1732         if (defined $page && defined $tpage) {
1733                 add_depends($page, $tpage);
1734         }
1735
1736         return unless defined $filename;
1737
1738         my @opts=(
1739                 filter => sub {
1740                         my $text_ref = shift;
1741                         ${$text_ref} = decode_utf8(${$text_ref});
1742                 },
1743                 loop_context_vars => 1,
1744                 die_on_bad_params => 0,
1745                 filename => $filename,
1746                 @_,
1747                 ($untrusted ? (no_includes => 1) : ()),
1748         );
1749         return @opts if wantarray;
1750
1751         require HTML::Template;
1752         return HTML::Template->new(@opts);
1753 }
1754
1755 sub template ($;@) {
1756         template_depends(shift, undef, @_);
1757 }
1758
1759 sub misctemplate ($$;@) {
1760         my $title=shift;
1761         my $content=shift;
1762         my %params=@_;
1763         
1764         my $template=template("page.tmpl");
1765
1766         my $page="";
1767         if (exists $params{page}) {
1768                 $page=delete $params{page};
1769         }
1770         run_hooks(pagetemplate => sub {
1771                 shift->(
1772                         page => $page,
1773                         destpage => $page,
1774                         template => $template,
1775                 );
1776         });
1777         templateactions($template, "");
1778
1779         $template->param(
1780                 dynamic => 1,
1781                 title => $title,
1782                 wikiname => $config{wikiname},
1783                 content => $content,
1784                 baseurl => baseurl(),
1785                 html5 => $config{html5},
1786                 %params,
1787         );
1788         
1789         return $template->output;
1790 }
1791
1792 sub templateactions ($$) {
1793         my $template=shift;
1794         my $page=shift;
1795
1796         my $have_actions=0;
1797         my @actions;
1798         run_hooks(pageactions => sub {
1799                 push @actions, map { { action => $_ } } 
1800                         grep { defined } shift->(page => $page);
1801         });
1802         $template->param(actions => \@actions);
1803
1804         if ($config{cgiurl} && exists $hooks{auth}) {
1805                 $template->param(prefsurl => cgiurl(do => "prefs"));
1806                 $have_actions=1;
1807         }
1808
1809         if ($have_actions || @actions) {
1810                 $template->param(have_actions => 1);
1811         }
1812 }
1813
1814 sub hook (@) {
1815         my %param=@_;
1816         
1817         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1818                 error 'hook requires type, call, and id parameters';
1819         }
1820
1821         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1822         
1823         $hooks{$param{type}}{$param{id}}=\%param;
1824         return 1;
1825 }
1826
1827 sub run_hooks ($$) {
1828         # Calls the given sub for each hook of the given type,
1829         # passing it the hook function to call.
1830         my $type=shift;
1831         my $sub=shift;
1832
1833         if (exists $hooks{$type}) {
1834                 my (@first, @middle, @last);
1835                 foreach my $id (keys %{$hooks{$type}}) {
1836                         if ($hooks{$type}{$id}{first}) {
1837                                 push @first, $id;
1838                         }
1839                         elsif ($hooks{$type}{$id}{last}) {
1840                                 push @last, $id;
1841                         }
1842                         else {
1843                                 push @middle, $id;
1844                         }
1845                 }
1846                 foreach my $id (@first, @middle, @last) {
1847                         $sub->($hooks{$type}{$id}{call});
1848                 }
1849         }
1850
1851         return 1;
1852 }
1853
1854 sub rcs_update () {
1855         $hooks{rcs}{rcs_update}{call}->(@_);
1856 }
1857
1858 sub rcs_prepedit ($) {
1859         $hooks{rcs}{rcs_prepedit}{call}->(@_);
1860 }
1861
1862 sub rcs_commit (@) {
1863         $hooks{rcs}{rcs_commit}{call}->(@_);
1864 }
1865
1866 sub rcs_commit_staged (@) {
1867         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1868 }
1869
1870 sub rcs_add ($) {
1871         $hooks{rcs}{rcs_add}{call}->(@_);
1872 }
1873
1874 sub rcs_remove ($) {
1875         $hooks{rcs}{rcs_remove}{call}->(@_);
1876 }
1877
1878 sub rcs_rename ($$) {
1879         $hooks{rcs}{rcs_rename}{call}->(@_);
1880 }
1881
1882 sub rcs_recentchanges ($) {
1883         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1884 }
1885
1886 sub rcs_diff ($) {
1887         $hooks{rcs}{rcs_diff}{call}->(@_);
1888 }
1889
1890 sub rcs_getctime ($) {
1891         $hooks{rcs}{rcs_getctime}{call}->(@_);
1892 }
1893
1894 sub rcs_getmtime ($) {
1895         $hooks{rcs}{rcs_getmtime}{call}->(@_);
1896 }
1897
1898 sub rcs_receive () {
1899         $hooks{rcs}{rcs_receive}{call}->();
1900 }
1901
1902 sub add_depends ($$;$) {
1903         my $page=shift;
1904         my $pagespec=shift;
1905         my $deptype=shift || $DEPEND_CONTENT;
1906
1907         # Is the pagespec a simple page name?
1908         if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1909             $pagespec !~ /[\s*?()!]/) {
1910                 $depends_simple{$page}{lc $pagespec} |= $deptype;
1911                 return 1;
1912         }
1913
1914         # Add explicit dependencies for influences.
1915         my $sub=pagespec_translate($pagespec);
1916         return unless defined $sub;
1917         foreach my $p (keys %pagesources) {
1918                 my $r=$sub->($p, location => $page);
1919                 my $i=$r->influences;
1920                 my $static=$r->influences_static;
1921                 foreach my $k (keys %$i) {
1922                         next unless $r || $static || $k eq $page;
1923                         $depends_simple{$page}{lc $k} |= $i->{$k};
1924                 }
1925                 last if $static;
1926         }
1927
1928         $depends{$page}{$pagespec} |= $deptype;
1929         return 1;
1930 }
1931
1932 sub deptype (@) {
1933         my $deptype=0;
1934         foreach my $type (@_) {
1935                 if ($type eq 'presence') {
1936                         $deptype |= $DEPEND_PRESENCE;
1937                 }
1938                 elsif ($type eq 'links') { 
1939                         $deptype |= $DEPEND_LINKS;
1940                 }
1941                 elsif ($type eq 'content') {
1942                         $deptype |= $DEPEND_CONTENT;
1943                 }
1944         }
1945         return $deptype;
1946 }
1947
1948 my $file_prune_regexp;
1949 sub file_pruned ($) {
1950         my $file=shift;
1951
1952         if (defined $config{include} && length $config{include}) {
1953                 return 0 if $file =~ m/$config{include}/;
1954         }
1955
1956         if (! defined $file_prune_regexp) {
1957                 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1958                 $file_prune_regexp=qr/$file_prune_regexp/;
1959         }
1960         return $file =~ m/$file_prune_regexp/;
1961 }
1962
1963 sub define_gettext () {
1964         # If translation is needed, redefine the gettext function to do it.
1965         # Otherwise, it becomes a quick no-op.
1966         my $gettext_obj;
1967         my $getobj;
1968         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1969             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1970             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1971                 $getobj=sub {
1972                         $gettext_obj=eval q{
1973                                 use Locale::gettext q{textdomain};
1974                                 Locale::gettext->domain('ikiwiki')
1975                         };
1976                 };
1977         }
1978
1979         no warnings 'redefine';
1980         *gettext=sub {
1981                 $getobj->() if $getobj;
1982                 if ($gettext_obj) {
1983                         $gettext_obj->get(shift);
1984                 }
1985                 else {
1986                         return shift;
1987                 }
1988         };
1989         *ngettext=sub {
1990                 $getobj->() if $getobj;
1991                 if ($gettext_obj) {
1992                         $gettext_obj->nget(@_);
1993                 }
1994                 else {
1995                         return ($_[2] == 1 ? $_[0] : $_[1])
1996                 }
1997         };
1998 }
1999
2000 sub gettext {
2001         define_gettext();
2002         gettext(@_);
2003 }
2004
2005 sub ngettext {
2006         define_gettext();
2007         ngettext(@_);
2008 }
2009
2010 sub yesno ($) {
2011         my $val=shift;
2012
2013         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2014 }
2015
2016 sub inject {
2017         # Injects a new function into the symbol table to replace an
2018         # exported function.
2019         my %params=@_;
2020
2021         # This is deep ugly perl foo, beware.
2022         no strict;
2023         no warnings;
2024         if (! defined $params{parent}) {
2025                 $params{parent}='::';
2026                 $params{old}=\&{$params{name}};
2027                 $params{name}=~s/.*:://;
2028         }
2029         my $parent=$params{parent};
2030         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2031                 $ns = $params{parent} . $ns;
2032                 inject(%params, parent => $ns) unless $ns eq '::main::';
2033                 *{$ns . $params{name}} = $params{call}
2034                         if exists ${$ns}{$params{name}} &&
2035                            \&{${$ns}{$params{name}}} == $params{old};
2036         }
2037         use strict;
2038         use warnings;
2039 }
2040
2041 sub add_link ($$;$) {
2042         my $page=shift;
2043         my $link=shift;
2044         my $type=shift;
2045
2046         push @{$links{$page}}, $link
2047                 unless grep { $_ eq $link } @{$links{$page}};
2048
2049         if (defined $type) {
2050                 $typedlinks{$page}{$type}{$link} = 1;
2051         }
2052 }
2053
2054 sub add_autofile ($$$) {
2055         my $file=shift;
2056         my $plugin=shift;
2057         my $generator=shift;
2058         
2059         $autofiles{$file}{plugin}=$plugin;
2060         $autofiles{$file}{generator}=$generator;
2061 }
2062
2063 sub sortspec_translate ($$) {
2064         my $spec = shift;
2065         my $reverse = shift;
2066
2067         my $code = "";
2068         my @data;
2069         while ($spec =~ m{
2070                 \s*
2071                 (-?)            # group 1: perhaps negated
2072                 \s*
2073                 (               # group 2: a word
2074                         \w+\([^\)]*\)   # command(params)
2075                         |
2076                         [^\s]+          # or anything else
2077                 )
2078                 \s*
2079         }gx) {
2080                 my $negated = $1;
2081                 my $word = $2;
2082                 my $params = undef;
2083
2084                 if ($word =~ m/^(\w+)\((.*)\)$/) {
2085                         # command with parameters
2086                         $params = $2;
2087                         $word = $1;
2088                 }
2089                 elsif ($word !~ m/^\w+$/) {
2090                         error(sprintf(gettext("invalid sort type %s"), $word));
2091                 }
2092
2093                 if (length $code) {
2094                         $code .= " || ";
2095                 }
2096
2097                 if ($negated) {
2098                         $code .= "-";
2099                 }
2100
2101                 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2102                         if (defined $params) {
2103                                 push @data, $params;
2104                                 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2105                         }
2106                         else {
2107                                 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2108                         }
2109                 }
2110                 else {
2111                         error(sprintf(gettext("unknown sort type %s"), $word));
2112                 }
2113         }
2114
2115         if (! length $code) {
2116                 # undefined sorting method... sort arbitrarily
2117                 return sub { 0 };
2118         }
2119
2120         if ($reverse) {
2121                 $code="-($code)";
2122         }
2123
2124         no warnings;
2125         return eval 'sub { '.$code.' }';
2126 }
2127
2128 sub pagespec_translate ($) {
2129         my $spec=shift;
2130
2131         # Convert spec to perl code.
2132         my $code="";
2133         my @data;
2134         while ($spec=~m{
2135                 \s*             # ignore whitespace
2136                 (               # 1: match a single word
2137                         \!              # !
2138                 |
2139                         \(              # (
2140                 |
2141                         \)              # )
2142                 |
2143                         \w+\([^\)]*\)   # command(params)
2144                 |
2145                         [^\s()]+        # any other text
2146                 )
2147                 \s*             # ignore whitespace
2148         }gx) {
2149                 my $word=$1;
2150                 if (lc $word eq 'and') {
2151                         $code.=' &';
2152                 }
2153                 elsif (lc $word eq 'or') {
2154                         $code.=' |';
2155                 }
2156                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2157                         $code.=' '.$word;
2158                 }
2159                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2160                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2161                                 push @data, $2;
2162                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2163                         }
2164                         else {
2165                                 push @data, qq{unknown function in pagespec "$word"};
2166                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2167                         }
2168                 }
2169                 else {
2170                         push @data, $word;
2171                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2172                 }
2173         }
2174
2175         if (! length $code) {
2176                 $code="IkiWiki::FailReason->new('empty pagespec')";
2177         }
2178
2179         no warnings;
2180         return eval 'sub { my $page=shift; '.$code.' }';
2181 }
2182
2183 sub pagespec_match ($$;@) {
2184         my $page=shift;
2185         my $spec=shift;
2186         my @params=@_;
2187
2188         # Backwards compatability with old calling convention.
2189         if (@params == 1) {
2190                 unshift @params, 'location';
2191         }
2192
2193         my $sub=pagespec_translate($spec);
2194         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2195                 if ! defined $sub;
2196         return $sub->($page, @params);
2197 }
2198
2199 sub pagespec_match_list ($$;@) {
2200         my $page=shift;
2201         my $pagespec=shift;
2202         my %params=@_;
2203
2204         # Backwards compatability with old calling convention.
2205         if (ref $page) {
2206                 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2207                 $params{list}=$page;
2208                 $page=$params{location}; # ugh!
2209         }
2210
2211         my $sub=pagespec_translate($pagespec);
2212         error "syntax error in pagespec \"$pagespec\""
2213                 if ! defined $sub;
2214         my $sort=sortspec_translate($params{sort}, $params{reverse})
2215                 if defined $params{sort};
2216
2217         my @candidates;
2218         if (exists $params{list}) {
2219                 @candidates=exists $params{filter}
2220                         ? grep { ! $params{filter}->($_) } @{$params{list}}
2221                         : @{$params{list}};
2222         }
2223         else {
2224                 @candidates=exists $params{filter}
2225                         ? grep { ! $params{filter}->($_) } keys %pagesources
2226                         : keys %pagesources;
2227         }
2228         
2229         # clear params, remainder is passed to pagespec
2230         $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2231         my $num=$params{num};
2232         delete @params{qw{num deptype reverse sort filter list}};
2233         
2234         # when only the top matches will be returned, it's efficient to
2235         # sort before matching to pagespec,
2236         if (defined $num && defined $sort) {
2237                 @candidates=IkiWiki::SortSpec::sort_pages(
2238                         $sort, @candidates);
2239         }
2240         
2241         my @matches;
2242         my $firstfail;
2243         my $count=0;
2244         my $accum=IkiWiki::SuccessReason->new();
2245         foreach my $p (@candidates) {
2246                 my $r=$sub->($p, %params, location => $page);
2247                 error(sprintf(gettext("cannot match pages: %s"), $r))
2248                         if $r->isa("IkiWiki::ErrorReason");
2249                 unless ($r || $r->influences_static) {
2250                         $r->remove_influence($p);
2251                 }
2252                 $accum |= $r;
2253                 if ($r) {
2254                         push @matches, $p;
2255                         last if defined $num && ++$count == $num;
2256                 }
2257         }
2258
2259         # Add simple dependencies for accumulated influences.
2260         my $i=$accum->influences;
2261         foreach my $k (keys %$i) {
2262                 $depends_simple{$page}{lc $k} |= $i->{$k};
2263         }
2264
2265         # when all matches will be returned, it's efficient to
2266         # sort after matching
2267         if (! defined $num && defined $sort) {
2268                 return IkiWiki::SortSpec::sort_pages(
2269                         $sort, @matches);
2270         }
2271         else {
2272                 return @matches;
2273         }
2274 }
2275
2276 sub pagespec_valid ($) {
2277         my $spec=shift;
2278
2279         return defined pagespec_translate($spec);
2280 }
2281
2282 sub glob2re ($) {
2283         my $re=quotemeta(shift);
2284         $re=~s/\\\*/.*/g;
2285         $re=~s/\\\?/./g;
2286         return $re;
2287 }
2288
2289 package IkiWiki::FailReason;
2290
2291 use overload (
2292         '""'    => sub { $_[0][0] },
2293         '0+'    => sub { 0 },
2294         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2295         '&'     => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2296         '|'     => sub { $_[1]->merge_influences($_[0]); $_[1] },
2297         fallback => 1,
2298 );
2299
2300 our @ISA = 'IkiWiki::SuccessReason';
2301
2302 package IkiWiki::SuccessReason;
2303
2304 use overload (
2305         '""'    => sub { $_[0][0] },
2306         '0+'    => sub { 1 },
2307         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
2308         '&'     => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2309         '|'     => sub { $_[0]->merge_influences($_[1]); $_[0] },
2310         fallback => 1,
2311 );
2312
2313 sub new {
2314         my $class = shift;
2315         my $value = shift;
2316         return bless [$value, {@_}], $class;
2317 }
2318
2319 sub influences {
2320         my $this=shift;
2321         $this->[1]={@_} if @_;
2322         my %i=%{$this->[1]};
2323         delete $i{""};
2324         return \%i;
2325 }
2326
2327 sub influences_static {
2328         return ! $_[0][1]->{""};
2329 }
2330
2331 sub merge_influences {
2332         my $this=shift;
2333         my $other=shift;
2334         my $anded=shift;
2335
2336         if (! $anded || (($this || %{$this->[1]}) &&
2337                          ($other || %{$other->[1]}))) {
2338                 foreach my $influence (keys %{$other->[1]}) {
2339                         $this->[1]{$influence} |= $other->[1]{$influence};
2340                 }
2341         }
2342         else {
2343                 # influence blocker
2344                 $this->[1]={};
2345         }
2346 }
2347
2348 sub remove_influence {
2349         my $this=shift;
2350         my $torm=shift;
2351
2352         delete $this->[1]{$torm};
2353 }
2354
2355 package IkiWiki::ErrorReason;
2356
2357 our @ISA = 'IkiWiki::FailReason';
2358
2359 package IkiWiki::PageSpec;
2360
2361 sub derel ($$) {
2362         my $path=shift;
2363         my $from=shift;
2364
2365         if ($path =~ m!^\./!) {
2366                 $from=~s#/?[^/]+$## if defined $from;
2367                 $path=~s#^\./##;
2368                 $path="$from/$path" if defined $from && length $from;
2369         }
2370
2371         return $path;
2372 }
2373
2374 sub match_glob ($$;@) {
2375         my $page=shift;
2376         my $glob=shift;
2377         my %params=@_;
2378         
2379         $glob=derel($glob, $params{location});
2380
2381         my $regexp=IkiWiki::glob2re($glob);
2382         if ($page=~/^$regexp$/i) {
2383                 if (! IkiWiki::isinternal($page) || $params{internal}) {
2384                         return IkiWiki::SuccessReason->new("$glob matches $page");
2385                 }
2386                 else {
2387                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2388                 }
2389         }
2390         else {
2391                 return IkiWiki::FailReason->new("$glob does not match $page");
2392         }
2393 }
2394
2395 sub match_internal ($$;@) {
2396         return match_glob(shift, shift, @_, internal => 1)
2397 }
2398
2399 sub match_page ($$;@) {
2400         my $page=shift;
2401         my $match=match_glob($page, shift, @_);
2402         if ($match && ! (exists $IkiWiki::pagesources{$page}
2403             && defined IkiWiki::pagetype($IkiWiki::pagesources{$page}))) {
2404                 return IkiWiki::FailReason->new("$page is not a page");
2405         }
2406         else {
2407                 return $match;
2408         }
2409 }
2410
2411 sub match_link ($$;@) {
2412         my $page=shift;
2413         my $link=lc(shift);
2414         my %params=@_;
2415
2416         $link=derel($link, $params{location});
2417         my $from=exists $params{location} ? $params{location} : '';
2418         my $linktype=$params{linktype};
2419         my $qualifier='';
2420         if (defined $linktype) {
2421                 $qualifier=" with type $linktype";
2422         }
2423
2424         my $links = $IkiWiki::links{$page};
2425         return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2426                 unless $links && @{$links};
2427         my $bestlink = IkiWiki::bestlink($from, $link);
2428         foreach my $p (@{$links}) {
2429                 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2430
2431                 if (length $bestlink) {
2432                         if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2433                                 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2434                         }
2435                 }
2436                 else {
2437                         if (match_glob($p, $link, %params)) {
2438                                 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2439                         }
2440                         my ($p_rel)=$p=~/^\/?(.*)/;
2441                         $link=~s/^\///;
2442                         if (match_glob($p_rel, $link, %params)) {
2443                                 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2444                         }
2445                 }
2446         }
2447         return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2448 }
2449
2450 sub match_backlink ($$;@) {
2451         my $ret=match_link($_[1], $_[0], @_);
2452         $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2453         return $ret;
2454 }
2455
2456 sub match_created_before ($$;@) {
2457         my $page=shift;
2458         my $testpage=shift;
2459         my %params=@_;
2460         
2461         $testpage=derel($testpage, $params{location});
2462
2463         if (exists $IkiWiki::pagectime{$testpage}) {
2464                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2465                         return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2466                 }
2467                 else {
2468                         return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2469                 }
2470         }
2471         else {
2472                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2473         }
2474 }
2475
2476 sub match_created_after ($$;@) {
2477         my $page=shift;
2478         my $testpage=shift;
2479         my %params=@_;
2480         
2481         $testpage=derel($testpage, $params{location});
2482
2483         if (exists $IkiWiki::pagectime{$testpage}) {
2484                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2485                         return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2486                 }
2487                 else {
2488                         return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2489                 }
2490         }
2491         else {
2492                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2493         }
2494 }
2495
2496 sub match_creation_day ($$;@) {
2497         if ((localtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2498                 return IkiWiki::SuccessReason->new('creation_day matched');
2499         }
2500         else {
2501                 return IkiWiki::FailReason->new('creation_day did not match');
2502         }
2503 }
2504
2505 sub match_creation_month ($$;@) {
2506         if ((localtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2507                 return IkiWiki::SuccessReason->new('creation_month matched');
2508         }
2509         else {
2510                 return IkiWiki::FailReason->new('creation_month did not match');
2511         }
2512 }
2513
2514 sub match_creation_year ($$;@) {
2515         if ((localtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2516                 return IkiWiki::SuccessReason->new('creation_year matched');
2517         }
2518         else {
2519                 return IkiWiki::FailReason->new('creation_year did not match');
2520         }
2521 }
2522
2523 sub match_user ($$;@) {
2524         shift;
2525         my $user=shift;
2526         my %params=@_;
2527         
2528         my $regexp=IkiWiki::glob2re($user);
2529         
2530         if (! exists $params{user}) {
2531                 return IkiWiki::ErrorReason->new("no user specified");
2532         }
2533
2534         if (defined $params{user} && $params{user}=~/^$regexp$/i) {
2535                 return IkiWiki::SuccessReason->new("user is $user");
2536         }
2537         elsif (! defined $params{user}) {
2538                 return IkiWiki::FailReason->new("not logged in");
2539         }
2540         else {
2541                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2542         }
2543 }
2544
2545 sub match_admin ($$;@) {
2546         shift;
2547         shift;
2548         my %params=@_;
2549         
2550         if (! exists $params{user}) {
2551                 return IkiWiki::ErrorReason->new("no user specified");
2552         }
2553
2554         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2555                 return IkiWiki::SuccessReason->new("user is an admin");
2556         }
2557         elsif (! defined $params{user}) {
2558                 return IkiWiki::FailReason->new("not logged in");
2559         }
2560         else {
2561                 return IkiWiki::FailReason->new("user is not an admin");
2562         }
2563 }
2564
2565 sub match_ip ($$;@) {
2566         shift;
2567         my $ip=shift;
2568         my %params=@_;
2569         
2570         if (! exists $params{ip}) {
2571                 return IkiWiki::ErrorReason->new("no IP specified");
2572         }
2573
2574         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2575                 return IkiWiki::SuccessReason->new("IP is $ip");
2576         }
2577         else {
2578                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2579         }
2580 }
2581
2582 package IkiWiki::SortSpec;
2583
2584 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2585 # are easily available in this namespace, for cmp functions to use them.
2586 sub sort_pages {
2587         my $f=shift;
2588         sort $f @_
2589 }
2590
2591 sub cmp_title {
2592         IkiWiki::pagetitle(IkiWiki::basename($a))
2593         cmp
2594         IkiWiki::pagetitle(IkiWiki::basename($b))
2595 }
2596
2597 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2598 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }
2599
2600 1