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