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