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