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