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