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