Fixed unncessary tight loop hash copy in saveindex where a pointer can be used instea...
[ikiwiki.git] / IkiWiki.pm
1 #!/usr/bin/perl
2
3 package IkiWiki;
4
5 use warnings;
6 use strict;
7 use Encode;
8 use URI::Escape q{uri_escape_utf8};
9 use POSIX ();
10 use Storable;
11 use open qw{:utf8 :std};
12
13 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
14         %pagestate %wikistate %renderedfiles %oldrenderedfiles
15         %pagesources %delpagesources %destsources %depends %depends_simple
16         @mass_depends %hooks %forcerebuild %loaded_plugins %typedlinks
17         %oldtypedlinks %autofiles};
18
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error htmlpage template template_depends
21         deptype add_depends pagespec_match pagespec_match_list bestlink
22         htmllink readfile writefile pagetype srcfile pagename
23         displaytime 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         if (! $config{rebuild}) {
1785                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1786                 %destsources=%renderedfiles=%pagecase=%pagestate=
1787                 %depends_simple=%typedlinks=%oldtypedlinks=();
1788         }
1789         my $in;
1790         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1791                 if (-e "$config{wikistatedir}/index") {
1792                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1793                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1794                 }
1795                 else {
1796                         $config{gettime}=1; # first build
1797                         return;
1798                 }
1799         }
1800
1801         my $index=Storable::fd_retrieve($in);
1802         if (! defined $index) {
1803                 return 0;
1804         }
1805
1806         my $pages;
1807         if (exists $index->{version} && ! ref $index->{version}) {
1808                 $pages=$index->{page};
1809                 %wikistate=%{$index->{state}};
1810                 # Handle plugins that got disabled by loading a new setup.
1811                 if (exists $config{setupfile}) {
1812                         require IkiWiki::Setup;
1813                         IkiWiki::Setup::disabled_plugins(
1814                                 grep { ! $loaded_plugins{$_} } keys %wikistate);
1815                 }
1816         }
1817         else {
1818                 $pages=$index;
1819                 %wikistate=();
1820         }
1821
1822         foreach my $src (keys %$pages) {
1823                 my $d=$pages->{$src};
1824                 my $page=pagename($src);
1825                 $pagectime{$page}=$d->{ctime};
1826                 $pagesources{$page}=$src;
1827                 if (! $config{rebuild}) {
1828                         $pagemtime{$page}=$d->{mtime};
1829                         $renderedfiles{$page}=$d->{dest};
1830                         if (exists $d->{links} && ref $d->{links}) {
1831                                 $links{$page}=$d->{links};
1832                                 $oldlinks{$page}=[@{$d->{links}}];
1833                         }
1834                         if (ref $d->{depends_simple} eq 'ARRAY') {
1835                                 # old format
1836                                 $depends_simple{$page}={
1837                                         map { $_ => 1 } @{$d->{depends_simple}}
1838                                 };
1839                         }
1840                         elsif (exists $d->{depends_simple}) {
1841                                 $depends_simple{$page}=$d->{depends_simple};
1842                         }
1843                         if (exists $d->{dependslist}) {
1844                                 # old format
1845                                 $depends{$page}={
1846                                         map { $_ => $DEPEND_CONTENT }
1847                                                 @{$d->{dependslist}}
1848                                 };
1849                         }
1850                         elsif (exists $d->{depends} && ! ref $d->{depends}) {
1851                                 # old format
1852                                 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1853                         }
1854                         elsif (exists $d->{depends}) {
1855                                 $depends{$page}=$d->{depends};
1856                         }
1857                         if (exists $d->{state}) {
1858                                 $pagestate{$page}=$d->{state};
1859                         }
1860                         if (exists $d->{typedlinks}) {
1861                                 $typedlinks{$page}=$d->{typedlinks};
1862
1863                                 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1864                                         next unless %$links;
1865                                         $oldtypedlinks{$page}{$type} = {%$links};
1866                                 }
1867                         }
1868                 }
1869                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1870         }
1871         foreach my $page (keys %pagesources) {
1872                 $pagecase{lc $page}=$page;
1873         }
1874         foreach my $page (keys %renderedfiles) {
1875                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1876         }
1877         return close($in);
1878 }
1879
1880 sub saveindex () {
1881         run_hooks(savestate => sub { shift->() });
1882
1883         my @plugins=keys %loaded_plugins;
1884
1885         if (! -d $config{wikistatedir}) {
1886                 mkdir($config{wikistatedir});
1887         }
1888         my $newfile="$config{wikistatedir}/indexdb.new";
1889         my $cleanup = sub { unlink($newfile) };
1890         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1891
1892         my %index;
1893         foreach my $page (keys %pagemtime) {
1894                 next unless $pagemtime{$page};
1895                 my $src=$pagesources{$page};
1896
1897                 $index{page}{$src}={
1898                         ctime => $pagectime{$page},
1899                         mtime => $pagemtime{$page},
1900                         dest => $renderedfiles{$page},
1901                         links => $links{$page},
1902                 };
1903
1904                 if (exists $depends{$page}) {
1905                         $index{page}{$src}{depends} = $depends{$page};
1906                 }
1907
1908                 if (exists $depends_simple{$page}) {
1909                         $index{page}{$src}{depends_simple} = $depends_simple{$page};
1910                 }
1911
1912                 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1913                         $index{page}{$src}{typedlinks} = $typedlinks{$page};
1914                 }
1915
1916                 if (exists $pagestate{$page}) {
1917                         $index{page}{$src}{state}=$pagestate{$page};
1918                 }
1919         }
1920
1921         $index{state}={};
1922         foreach my $id (@plugins) {
1923                 $index{state}{$id}={}; # used to detect disabled plugins
1924                 foreach my $key (keys %{$wikistate{$id}}) {
1925                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
1926                 }
1927         }
1928         
1929         $index{version}="3";
1930         my $ret=Storable::nstore_fd(\%index, $out);
1931         return if ! defined $ret || ! $ret;
1932         close $out || error("failed saving to $newfile: $!", $cleanup);
1933         rename($newfile, "$config{wikistatedir}/indexdb") ||
1934                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1935         
1936         return 1;
1937 }
1938
1939 sub template_file ($) {
1940         my $name=shift;
1941         
1942         my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1943         my $template;
1944         if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1945                 $template=srcfile($pagesources{$tpage}, 1);
1946                 $name.=".tmpl";
1947         }
1948         else {
1949                 $template=srcfile($tpage, 1);
1950         }
1951
1952         if (defined $template) {
1953                 return $template, $tpage, 1 if wantarray;
1954                 return $template;
1955         }
1956         else {
1957                 $name=~s:/::; # avoid path traversal
1958                 foreach my $dir ($config{templatedir},
1959                                  "$installdir/share/ikiwiki/templates") {
1960                         if (-e "$dir/$name") {
1961                                 $template="$dir/$name";
1962                                 last;
1963                         }
1964                 }
1965                 if (defined $template) {        
1966                         return $template, $tpage if wantarray;
1967                         return $template;
1968                 }
1969         }
1970
1971         return;
1972 }
1973
1974 sub template_depends ($$;@) {
1975         my $name=shift;
1976         my $page=shift;
1977         
1978         my ($filename, $tpage, $untrusted)=template_file($name);
1979         if (! defined $filename) {
1980                 error(sprintf(gettext("template %s not found"), $name))
1981         }
1982
1983         if (defined $page && defined $tpage) {
1984                 add_depends($page, $tpage);
1985         }
1986         
1987         my @opts=(
1988                 filter => sub {
1989                         my $text_ref = shift;
1990                         ${$text_ref} = decode_utf8(${$text_ref});
1991                 },
1992                 loop_context_vars => 1,
1993                 die_on_bad_params => 0,
1994                 parent_global_vars => 1,
1995                 filename => $filename,
1996                 @_,
1997                 ($untrusted ? (no_includes => 1) : ()),
1998         );
1999         return @opts if wantarray;
2000
2001         require HTML::Template;
2002         return HTML::Template->new(@opts);
2003 }
2004
2005 sub template ($;@) {
2006         template_depends(shift, undef, @_);
2007 }
2008
2009 sub templateactions ($$) {
2010         my $template=shift;
2011         my $page=shift;
2012
2013         my $have_actions=0;
2014         my @actions;
2015         run_hooks(pageactions => sub {
2016                 push @actions, map { { action => $_ } } 
2017                         grep { defined } shift->(page => $page);
2018         });
2019         $template->param(actions => \@actions);
2020
2021         if ($config{cgiurl} && exists $hooks{auth}) {
2022                 $template->param(prefsurl => cgiurl(do => "prefs"));
2023                 $have_actions=1;
2024         }
2025
2026         if ($have_actions || @actions) {
2027                 $template->param(have_actions => 1);
2028         }
2029 }
2030
2031 sub hook (@) {
2032         my %param=@_;
2033         
2034         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2035                 error 'hook requires type, call, and id parameters';
2036         }
2037
2038         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2039         
2040         $hooks{$param{type}}{$param{id}}=\%param;
2041         return 1;
2042 }
2043
2044 sub run_hooks ($$) {
2045         # Calls the given sub for each hook of the given type,
2046         # passing it the hook function to call.
2047         my $type=shift;
2048         my $sub=shift;
2049
2050         if (exists $hooks{$type}) {
2051                 my (@first, @middle, @last);
2052                 foreach my $id (keys %{$hooks{$type}}) {
2053                         if ($hooks{$type}{$id}{first}) {
2054                                 push @first, $id;
2055                         }
2056                         elsif ($hooks{$type}{$id}{last}) {
2057                                 push @last, $id;
2058                         }
2059                         else {
2060                                 push @middle, $id;
2061                         }
2062                 }
2063                 foreach my $id (@first, @middle, @last) {
2064                         $sub->($hooks{$type}{$id}{call});
2065                 }
2066         }
2067
2068         return 1;
2069 }
2070
2071 sub rcs_update () {
2072         $hooks{rcs}{rcs_update}{call}->(@_);
2073 }
2074
2075 sub rcs_prepedit ($) {
2076         $hooks{rcs}{rcs_prepedit}{call}->(@_);
2077 }
2078
2079 sub rcs_commit (@) {
2080         $hooks{rcs}{rcs_commit}{call}->(@_);
2081 }
2082
2083 sub rcs_commit_staged (@) {
2084         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2085 }
2086
2087 sub rcs_add ($) {
2088         $hooks{rcs}{rcs_add}{call}->(@_);
2089 }
2090
2091 sub rcs_remove ($) {
2092         $hooks{rcs}{rcs_remove}{call}->(@_);
2093 }
2094
2095 sub rcs_rename ($$) {
2096         $hooks{rcs}{rcs_rename}{call}->(@_);
2097 }
2098
2099 sub rcs_recentchanges ($) {
2100         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2101 }
2102
2103 sub rcs_diff ($;$) {
2104         $hooks{rcs}{rcs_diff}{call}->(@_);
2105 }
2106
2107 sub rcs_getctime ($) {
2108         $hooks{rcs}{rcs_getctime}{call}->(@_);
2109 }
2110
2111 sub rcs_getmtime ($) {
2112         $hooks{rcs}{rcs_getmtime}{call}->(@_);
2113 }
2114
2115 sub rcs_receive () {
2116         $hooks{rcs}{rcs_receive}{call}->();
2117 }
2118
2119 sub add_depends ($$;$) {
2120         my $page=shift;
2121         my $pagespec=shift;
2122         my $deptype=shift || $DEPEND_CONTENT;
2123
2124         # Is the pagespec a simple page name?
2125         if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2126             $pagespec !~ /[\s*?()!]/) {
2127                 $depends_simple{$page}{lc $pagespec} |= $deptype;
2128                 return 1;
2129         }
2130
2131         # Add explicit dependencies for influences.
2132         my $sub=pagespec_translate($pagespec);
2133         return unless defined $sub;
2134         foreach my $p (keys %pagesources) {
2135                 my $r=$sub->($p, location => $page);
2136                 my $i=$r->influences;
2137                 my $static=$r->influences_static;
2138                 foreach my $k (keys %$i) {
2139                         next unless $r || $static || $k eq $page;
2140                         $depends_simple{$page}{lc $k} |= $i->{$k};
2141                 }
2142                 last if $static;
2143         }
2144
2145         $depends{$page}{$pagespec} |= $deptype;
2146         return 1;
2147 }
2148
2149 sub deptype (@) {
2150         my $deptype=0;
2151         foreach my $type (@_) {
2152                 if ($type eq 'presence') {
2153                         $deptype |= $DEPEND_PRESENCE;
2154                 }
2155                 elsif ($type eq 'links') { 
2156                         $deptype |= $DEPEND_LINKS;
2157                 }
2158                 elsif ($type eq 'content') {
2159                         $deptype |= $DEPEND_CONTENT;
2160                 }
2161         }
2162         return $deptype;
2163 }
2164
2165 my $file_prune_regexp;
2166 sub file_pruned ($) {
2167         my $file=shift;
2168
2169         if (defined $config{include} && length $config{include}) {
2170                 return 0 if $file =~ m/$config{include}/;
2171         }
2172
2173         if (! defined $file_prune_regexp) {
2174                 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2175                 $file_prune_regexp=qr/$file_prune_regexp/;
2176         }
2177         return $file =~ m/$file_prune_regexp/;
2178 }
2179
2180 sub define_gettext () {
2181         # If translation is needed, redefine the gettext function to do it.
2182         # Otherwise, it becomes a quick no-op.
2183         my $gettext_obj;
2184         my $getobj;
2185         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2186             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2187             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2188                 $getobj=sub {
2189                         $gettext_obj=eval q{
2190                                 use Locale::gettext q{textdomain};
2191                                 Locale::gettext->domain('ikiwiki')
2192                         };
2193                 };
2194         }
2195
2196         no warnings 'redefine';
2197         *gettext=sub {
2198                 $getobj->() if $getobj;
2199                 if ($gettext_obj) {
2200                         $gettext_obj->get(shift);
2201                 }
2202                 else {
2203                         return shift;
2204                 }
2205         };
2206         *ngettext=sub {
2207                 $getobj->() if $getobj;
2208                 if ($gettext_obj) {
2209                         $gettext_obj->nget(@_);
2210                 }
2211                 else {
2212                         return ($_[2] == 1 ? $_[0] : $_[1])
2213                 }
2214         };
2215 }
2216
2217 sub gettext {
2218         define_gettext();
2219         gettext(@_);
2220 }
2221
2222 sub ngettext {
2223         define_gettext();
2224         ngettext(@_);
2225 }
2226
2227 sub yesno ($) {
2228         my $val=shift;
2229
2230         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2231 }
2232
2233 sub inject {
2234         # Injects a new function into the symbol table to replace an
2235         # exported function.
2236         my %params=@_;
2237
2238         # This is deep ugly perl foo, beware.
2239         no strict;
2240         no warnings;
2241         if (! defined $params{parent}) {
2242                 $params{parent}='::';
2243                 $params{old}=\&{$params{name}};
2244                 $params{name}=~s/.*:://;
2245         }
2246         my $parent=$params{parent};
2247         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2248                 $ns = $params{parent} . $ns;
2249                 inject(%params, parent => $ns) unless $ns eq '::main::';
2250                 *{$ns . $params{name}} = $params{call}
2251                         if exists ${$ns}{$params{name}} &&
2252                            \&{${$ns}{$params{name}}} == $params{old};
2253         }
2254         use strict;
2255         use warnings;
2256 }
2257
2258 sub add_link ($$;$) {
2259         my $page=shift;
2260         my $link=shift;
2261         my $type=shift;
2262
2263         push @{$links{$page}}, $link
2264                 unless grep { $_ eq $link } @{$links{$page}};
2265
2266         if (defined $type) {
2267                 $typedlinks{$page}{$type}{$link} = 1;
2268         }
2269 }
2270
2271 sub add_autofile ($$$) {
2272         my $file=shift;
2273         my $plugin=shift;
2274         my $generator=shift;
2275         
2276         $autofiles{$file}{plugin}=$plugin;
2277         $autofiles{$file}{generator}=$generator;
2278 }
2279
2280 sub useragent () {
2281         return LWP::UserAgent->new(
2282                 cookie_jar => $config{cookiejar},
2283                 env_proxy => 1,         # respect proxy env vars
2284         );
2285 }
2286
2287 sub sortspec_translate ($$) {
2288         my $spec = shift;
2289         my $reverse = shift;
2290
2291         my $code = "";
2292         my @data;
2293         while ($spec =~ m{
2294                 \s*
2295                 (-?)            # group 1: perhaps negated
2296                 \s*
2297                 (               # group 2: a word
2298                         \w+\([^\)]*\)   # command(params)
2299                         |
2300                         [^\s]+          # or anything else
2301                 )
2302                 \s*
2303         }gx) {
2304                 my $negated = $1;
2305                 my $word = $2;
2306                 my $params = undef;
2307
2308                 if ($word =~ m/^(\w+)\((.*)\)$/) {
2309                         # command with parameters
2310                         $params = $2;
2311                         $word = $1;
2312                 }
2313                 elsif ($word !~ m/^\w+$/) {
2314                         error(sprintf(gettext("invalid sort type %s"), $word));
2315                 }
2316
2317                 if (length $code) {
2318                         $code .= " || ";
2319                 }
2320
2321                 if ($negated) {
2322                         $code .= "-";
2323                 }
2324
2325                 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2326                         if (defined $params) {
2327                                 push @data, $params;
2328                                 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2329                         }
2330                         else {
2331                                 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2332                         }
2333                 }
2334                 else {
2335                         error(sprintf(gettext("unknown sort type %s"), $word));
2336                 }
2337         }
2338
2339         if (! length $code) {
2340                 # undefined sorting method... sort arbitrarily
2341                 return sub { 0 };
2342         }
2343
2344         if ($reverse) {
2345                 $code="-($code)";
2346         }
2347
2348         no warnings;
2349         return eval 'sub { '.$code.' }';
2350 }
2351
2352 sub pagespec_translate ($) {
2353         my $spec=shift;
2354
2355         # Convert spec to perl code.
2356         my $code="";
2357         my @data;
2358         while ($spec=~m{
2359                 \s*             # ignore whitespace
2360                 (               # 1: match a single word
2361                         \!              # !
2362                 |
2363                         \(              # (
2364                 |
2365                         \)              # )
2366                 |
2367                         \w+\([^\)]*\)   # command(params)
2368                 |
2369                         [^\s()]+        # any other text
2370                 )
2371                 \s*             # ignore whitespace
2372         }gx) {
2373                 my $word=$1;
2374                 if (lc $word eq 'and') {
2375                         $code.=' &';
2376                 }
2377                 elsif (lc $word eq 'or') {
2378                         $code.=' |';
2379                 }
2380                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2381                         $code.=' '.$word;
2382                 }
2383                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2384                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2385                                 push @data, $2;
2386                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2387                         }
2388                         else {
2389                                 push @data, qq{unknown function in pagespec "$word"};
2390                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2391                         }
2392                 }
2393                 else {
2394                         push @data, $word;
2395                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2396                 }
2397         }
2398
2399         if (! length $code) {
2400                 $code="IkiWiki::FailReason->new('empty pagespec')";
2401         }
2402
2403         no warnings;
2404         return eval 'sub { my $page=shift; '.$code.' }';
2405 }
2406
2407 sub pagespec_match ($$;@) {
2408         my $page=shift;
2409         my $spec=shift;
2410         my @params=@_;
2411
2412         # Backwards compatability with old calling convention.
2413         if (@params == 1) {
2414                 unshift @params, 'location';
2415         }
2416
2417         my $sub=pagespec_translate($spec);
2418         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2419                 if ! defined $sub;
2420         return $sub->($page, @params);
2421 }
2422
2423 sub pagespec_match_list ($$;@) {
2424         my $page=shift;
2425         my $pagespec=shift;
2426         my %params=@_;
2427
2428         # Backwards compatability with old calling convention.
2429         if (ref $page) {
2430                 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2431                 $params{list}=$page;
2432                 $page=$params{location}; # ugh!
2433         }
2434
2435         my $sub=pagespec_translate($pagespec);
2436         error "syntax error in pagespec \"$pagespec\""
2437                 if ! defined $sub;
2438         my $sort=sortspec_translate($params{sort}, $params{reverse})
2439                 if defined $params{sort};
2440
2441         my @candidates;
2442         if (exists $params{list}) {
2443                 @candidates=exists $params{filter}
2444                         ? grep { ! $params{filter}->($_) } @{$params{list}}
2445                         : @{$params{list}};
2446         }
2447         else {
2448                 @candidates=exists $params{filter}
2449                         ? grep { ! $params{filter}->($_) } keys %pagesources
2450                         : keys %pagesources;
2451         }
2452         
2453         # clear params, remainder is passed to pagespec
2454         $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2455         my $num=$params{num};
2456         delete @params{qw{num deptype reverse sort filter list}};
2457         
2458         # when only the top matches will be returned, it's efficient to
2459         # sort before matching to pagespec,
2460         if (defined $num && defined $sort) {
2461                 @candidates=IkiWiki::SortSpec::sort_pages(
2462                         $sort, @candidates);
2463         }
2464         
2465         my @matches;
2466         my $firstfail;
2467         my $count=0;
2468         my $accum=IkiWiki::SuccessReason->new();
2469         foreach my $p (@candidates) {
2470                 my $r=$sub->($p, %params, location => $page);
2471                 error(sprintf(gettext("cannot match pages: %s"), $r))
2472                         if $r->isa("IkiWiki::ErrorReason");
2473                 unless ($r || $r->influences_static) {
2474                         $r->remove_influence($p);
2475                 }
2476                 $accum |= $r;
2477                 if ($r) {
2478                         push @matches, $p;
2479                         last if defined $num && ++$count == $num;
2480                 }
2481         }
2482
2483         # Add simple dependencies for accumulated influences.
2484         my $i=$accum->influences;
2485         foreach my $k (keys %$i) {
2486                 $depends_simple{$page}{lc $k} |= $i->{$k};
2487         }
2488
2489         # when all matches will be returned, it's efficient to
2490         # sort after matching
2491         if (! defined $num && defined $sort) {
2492                 return IkiWiki::SortSpec::sort_pages(
2493                         $sort, @matches);
2494         }
2495         else {
2496                 return @matches;
2497         }
2498 }
2499
2500 sub pagespec_valid ($) {
2501         my $spec=shift;
2502
2503         return defined pagespec_translate($spec);
2504 }
2505
2506 sub glob2re ($) {
2507         my $re=quotemeta(shift);
2508         $re=~s/\\\*/.*/g;
2509         $re=~s/\\\?/./g;
2510         return qr/^$re$/i;
2511 }
2512
2513 package IkiWiki::FailReason;
2514
2515 use overload (
2516         '""'    => sub { $_[0][0] },
2517         '0+'    => sub { 0 },
2518         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2519         '&'     => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2520         '|'     => sub { $_[1]->merge_influences($_[0]); $_[1] },
2521         fallback => 1,
2522 );
2523
2524 our @ISA = 'IkiWiki::SuccessReason';
2525
2526 package IkiWiki::SuccessReason;
2527
2528 use overload (
2529         '""'    => sub { $_[0][0] },
2530         '0+'    => sub { 1 },
2531         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
2532         '&'     => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2533         '|'     => sub { $_[0]->merge_influences($_[1]); $_[0] },
2534         fallback => 1,
2535 );
2536
2537 sub new {
2538         my $class = shift;
2539         my $value = shift;
2540         return bless [$value, {@_}], $class;
2541 }
2542
2543 sub influences {
2544         my $this=shift;
2545         $this->[1]={@_} if @_;
2546         my %i=%{$this->[1]};
2547         delete $i{""};
2548         return \%i;
2549 }
2550
2551 sub influences_static {
2552         return ! $_[0][1]->{""};
2553 }
2554
2555 sub merge_influences {
2556         my $this=shift;
2557         my $other=shift;
2558         my $anded=shift;
2559
2560         if (! $anded || (($this || %{$this->[1]}) &&
2561                          ($other || %{$other->[1]}))) {
2562                 foreach my $influence (keys %{$other->[1]}) {
2563                         $this->[1]{$influence} |= $other->[1]{$influence};
2564                 }
2565         }
2566         else {
2567                 # influence blocker
2568                 $this->[1]={};
2569         }
2570 }
2571
2572 sub remove_influence {
2573         my $this=shift;
2574         my $torm=shift;
2575
2576         delete $this->[1]{$torm};
2577 }
2578
2579 package IkiWiki::ErrorReason;
2580
2581 our @ISA = 'IkiWiki::FailReason';
2582
2583 package IkiWiki::PageSpec;
2584
2585 sub derel ($$) {
2586         my $path=shift;
2587         my $from=shift;
2588
2589         if ($path =~ m!^\.(/|$)!) {
2590                 if ($1) {
2591                         $from=~s#/?[^/]+$## if defined $from;
2592                         $path=~s#^\./##;
2593                         $path="$from/$path" if defined $from && length $from;
2594                 }
2595                 else {
2596                         $path = $from;
2597                         $path = "" unless defined $path;
2598                 }
2599         }
2600
2601         return $path;
2602 }
2603
2604 my %glob_cache;
2605
2606 sub match_glob ($$;@) {
2607         my $page=shift;
2608         my $glob=shift;
2609         my %params=@_;
2610         
2611         $glob=derel($glob, $params{location});
2612
2613         # Instead of converting the glob to a regex every time,
2614         # cache the compiled regex to save time.
2615         my $re=$glob_cache{$glob};
2616         unless (defined $re) {
2617                 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2618         }
2619         if ($page =~ $re) {
2620                 if (! IkiWiki::isinternal($page) || $params{internal}) {
2621                         return IkiWiki::SuccessReason->new("$glob matches $page");
2622                 }
2623                 else {
2624                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2625                 }
2626         }
2627         else {
2628                 return IkiWiki::FailReason->new("$glob does not match $page");
2629         }
2630 }
2631
2632 sub match_internal ($$;@) {
2633         return match_glob(shift, shift, @_, internal => 1)
2634 }
2635
2636 sub match_page ($$;@) {
2637         my $page=shift;
2638         my $match=match_glob($page, shift, @_);
2639         if ($match) {
2640                 my $source=exists $IkiWiki::pagesources{$page} ?
2641                         $IkiWiki::pagesources{$page} :
2642                         $IkiWiki::delpagesources{$page};
2643                 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2644                 if (! defined $type) {  
2645                         return IkiWiki::FailReason->new("$page is not a page");
2646                 }
2647         }
2648         return $match;
2649 }
2650
2651 sub match_link ($$;@) {
2652         my $page=shift;
2653         my $link=lc(shift);
2654         my %params=@_;
2655
2656         $link=derel($link, $params{location});
2657         my $from=exists $params{location} ? $params{location} : '';
2658         my $linktype=$params{linktype};
2659         my $qualifier='';
2660         if (defined $linktype) {
2661                 $qualifier=" with type $linktype";
2662         }
2663
2664         my $links = $IkiWiki::links{$page};
2665         return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2666                 unless $links && @{$links};
2667         my $bestlink = IkiWiki::bestlink($from, $link);
2668         foreach my $p (@{$links}) {
2669                 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2670
2671                 if (length $bestlink) {
2672                         if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2673                                 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2674                         }
2675                 }
2676                 else {
2677                         if (match_glob($p, $link, %params)) {
2678                                 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2679                         }
2680                         my ($p_rel)=$p=~/^\/?(.*)/;
2681                         $link=~s/^\///;
2682                         if (match_glob($p_rel, $link, %params)) {
2683                                 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2684                         }
2685                 }
2686         }
2687         return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2688 }
2689
2690 sub match_backlink ($$;@) {
2691         my $page=shift;
2692         my $testpage=shift;
2693         my %params=@_;
2694         if ($testpage eq '.') {
2695                 $testpage = $params{'location'}
2696         }
2697         my $ret=match_link($testpage, $page, @_);
2698         $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2699         return $ret;
2700 }
2701
2702 sub match_created_before ($$;@) {
2703         my $page=shift;
2704         my $testpage=shift;
2705         my %params=@_;
2706         
2707         $testpage=derel($testpage, $params{location});
2708
2709         if (exists $IkiWiki::pagectime{$testpage}) {
2710                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2711                         return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2712                 }
2713                 else {
2714                         return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2715                 }
2716         }
2717         else {
2718                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2719         }
2720 }
2721
2722 sub match_created_after ($$;@) {
2723         my $page=shift;
2724         my $testpage=shift;
2725         my %params=@_;
2726         
2727         $testpage=derel($testpage, $params{location});
2728
2729         if (exists $IkiWiki::pagectime{$testpage}) {
2730                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2731                         return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2732                 }
2733                 else {
2734                         return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2735                 }
2736         }
2737         else {
2738                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2739         }
2740 }
2741
2742 sub match_creation_day ($$;@) {
2743         my $page=shift;
2744         my $d=shift;
2745         if ($d !~ /^\d+$/) {
2746                 return IkiWiki::ErrorReason->new("invalid day $d");
2747         }
2748         if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2749                 return IkiWiki::SuccessReason->new('creation_day matched');
2750         }
2751         else {
2752                 return IkiWiki::FailReason->new('creation_day did not match');
2753         }
2754 }
2755
2756 sub match_creation_month ($$;@) {
2757         my $page=shift;
2758         my $m=shift;
2759         if ($m !~ /^\d+$/) {
2760                 return IkiWiki::ErrorReason->new("invalid month $m");
2761         }
2762         if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2763                 return IkiWiki::SuccessReason->new('creation_month matched');
2764         }
2765         else {
2766                 return IkiWiki::FailReason->new('creation_month did not match');
2767         }
2768 }
2769
2770 sub match_creation_year ($$;@) {
2771         my $page=shift;
2772         my $y=shift;
2773         if ($y !~ /^\d+$/) {
2774                 return IkiWiki::ErrorReason->new("invalid year $y");
2775         }
2776         if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2777                 return IkiWiki::SuccessReason->new('creation_year matched');
2778         }
2779         else {
2780                 return IkiWiki::FailReason->new('creation_year did not match');
2781         }
2782 }
2783
2784 sub match_user ($$;@) {
2785         shift;
2786         my $user=shift;
2787         my %params=@_;
2788         
2789         if (! exists $params{user}) {
2790                 return IkiWiki::ErrorReason->new("no user specified");
2791         }
2792
2793         my $regexp=IkiWiki::glob2re($user);
2794         
2795         if (defined $params{user} && $params{user}=~$regexp) {
2796                 return IkiWiki::SuccessReason->new("user is $user");
2797         }
2798         elsif (! defined $params{user}) {
2799                 return IkiWiki::FailReason->new("not logged in");
2800         }
2801         else {
2802                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2803         }
2804 }
2805
2806 sub match_admin ($$;@) {
2807         shift;
2808         shift;
2809         my %params=@_;
2810         
2811         if (! exists $params{user}) {
2812                 return IkiWiki::ErrorReason->new("no user specified");
2813         }
2814
2815         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2816                 return IkiWiki::SuccessReason->new("user is an admin");
2817         }
2818         elsif (! defined $params{user}) {
2819                 return IkiWiki::FailReason->new("not logged in");
2820         }
2821         else {
2822                 return IkiWiki::FailReason->new("user is not an admin");
2823         }
2824 }
2825
2826 sub match_ip ($$;@) {
2827         shift;
2828         my $ip=shift;
2829         my %params=@_;
2830         
2831         if (! exists $params{ip}) {
2832                 return IkiWiki::ErrorReason->new("no IP specified");
2833         }
2834         
2835         my $regexp=IkiWiki::glob2re(lc $ip);
2836
2837         if (defined $params{ip} && lc $params{ip}=~$regexp) {
2838                 return IkiWiki::SuccessReason->new("IP is $ip");
2839         }
2840         else {
2841                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2842         }
2843 }
2844
2845 package IkiWiki::SortSpec;
2846
2847 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2848 # are easily available in this namespace, for cmp functions to use them.
2849 sub sort_pages {
2850         my $f=shift;
2851         sort $f @_
2852 }
2853
2854 sub cmp_title {
2855         IkiWiki::pagetitle(IkiWiki::basename($a))
2856         cmp
2857         IkiWiki::pagetitle(IkiWiki::basename($b))
2858 }
2859
2860 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
2861 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2862 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }
2863
2864 1