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