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