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