better handling of relative permalinks
[ikiwiki] / IkiWiki.pm
1 #!/usr/bin/perl
2
3 package IkiWiki;
4
5 use warnings;
6 use strict;
7 use Encode;
8 use URI::Escape q{uri_escape_utf8};
9 use POSIX ();
10 use Storable;
11 use open qw{:utf8 :std};
12
13 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
14         %pagestate %wikistate %renderedfiles %oldrenderedfiles
15         %pagesources %delpagesources %destsources %depends %depends_simple
16         @mass_depends %hooks %forcerebuild %loaded_plugins %typedlinks
17         %oldtypedlinks %autofiles};
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 (defined $config{url} && 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 urlabs ($$) {
1072         my $url=shift;
1073         my $urlbase=shift;
1074
1075         return $url unless defined $urlbase && length $urlbase;
1076
1077         eval q{use URI};
1078         URI->new_abs($url, $urlbase)->as_string;
1079 }
1080
1081 sub abs2rel ($$) {
1082         # Work around very innefficient behavior in File::Spec if abs2rel
1083         # is passed two relative paths. It's much faster if paths are
1084         # absolute! (Debian bug #376658; fixed in debian unstable now)
1085         my $path="/".shift;
1086         my $base="/".shift;
1087
1088         require File::Spec;
1089         my $ret=File::Spec->abs2rel($path, $base);
1090         $ret=~s/^// if defined $ret;
1091         return $ret;
1092 }
1093
1094 sub displaytime ($;$$) {
1095         # Plugins can override this function to mark up the time to
1096         # display.
1097         my $time=formattime($_[0], $_[1]);
1098         if ($config{html5}) {
1099                 return '<time datetime="'.date_3339($_[0]).'"'.
1100                         ($_[2] ? ' pubdate="pubdate"' : '').
1101                         '>'.$time.'</time>';
1102         }
1103         else {
1104                 return '<span class="date">'.$time.'</span>';
1105         }
1106 }
1107
1108 sub formattime ($;$) {
1109         # Plugins can override this function to format the time.
1110         my $time=shift;
1111         my $format=shift;
1112         if (! defined $format) {
1113                 $format=$config{timeformat};
1114         }
1115
1116         # strftime doesn't know about encodings, so make sure
1117         # its output is properly treated as utf8
1118         return decode_utf8(POSIX::strftime($format, localtime($time)));
1119 }
1120
1121 sub date_3339 ($) {
1122         my $time=shift;
1123
1124         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1125         POSIX::setlocale(&POSIX::LC_TIME, "C");
1126         my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1127         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1128         return $ret;
1129 }
1130
1131 sub beautify_urlpath ($) {
1132         my $url=shift;
1133
1134         # Ensure url is not an empty link, and if necessary,
1135         # add ./ to avoid colon confusion.
1136         if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1137                 $url="./$url";
1138         }
1139
1140         if ($config{usedirs}) {
1141                 $url =~ s!/index.$config{htmlext}$!/!;
1142         }
1143
1144         return $url;
1145 }
1146
1147 sub urlto ($;$$) {
1148         my $to=shift;
1149         my $from=shift;
1150         my $absolute=shift;
1151         
1152         if (! length $to) {
1153                 $to = 'index';
1154         }
1155
1156         if (! $destsources{$to}) {
1157                 $to=htmlpage($to);
1158         }
1159
1160         if ($absolute) {
1161                 return $config{url}.beautify_urlpath("/".$to);
1162         }
1163
1164         if (! defined $from) {
1165                 my $u = $local_url;
1166                 $u =~ s{/$}{};
1167                 return $u.beautify_urlpath("/".$to);
1168         }
1169
1170         my $link = abs2rel($to, dirname(htmlpage($from)));
1171
1172         return beautify_urlpath($link);
1173 }
1174
1175 sub isselflink ($$) {
1176         # Plugins can override this function to support special types
1177         # of selflinks.
1178         my $page=shift;
1179         my $link=shift;
1180
1181         return $page eq $link;
1182 }
1183
1184 sub htmllink ($$$;@) {
1185         my $lpage=shift; # the page doing the linking
1186         my $page=shift; # the page that will contain the link (different for inline)
1187         my $link=shift;
1188         my %opts=@_;
1189
1190         $link=~s/\/$//;
1191
1192         my $bestlink;
1193         if (! $opts{forcesubpage}) {
1194                 $bestlink=bestlink($lpage, $link);
1195         }
1196         else {
1197                 $bestlink="$lpage/".lc($link);
1198         }
1199
1200         my $linktext;
1201         if (defined $opts{linktext}) {
1202                 $linktext=$opts{linktext};
1203         }
1204         else {
1205                 $linktext=pagetitle(basename($link));
1206         }
1207         
1208         return "<span class=\"selflink\">$linktext</span>"
1209                 if length $bestlink && isselflink($page, $bestlink) &&
1210                    ! defined $opts{anchor};
1211         
1212         if (! $destsources{$bestlink}) {
1213                 $bestlink=htmlpage($bestlink);
1214
1215                 if (! $destsources{$bestlink}) {
1216                         my $cgilink = "";
1217                         if (length $config{cgiurl}) {
1218                                 $cgilink = "<a href=\"".
1219                                         cgiurl(
1220                                                 do => "create",
1221                                                 page => lc($link),
1222                                                 from => $lpage
1223                                         )."\" rel=\"nofollow\">?</a>";
1224                         }
1225                         return "<span class=\"createlink\">$cgilink$linktext</span>"
1226                 }
1227         }
1228         
1229         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1230         $bestlink=beautify_urlpath($bestlink);
1231         
1232         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1233                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1234         }
1235
1236         if (defined $opts{anchor}) {
1237                 $bestlink.="#".$opts{anchor};
1238         }
1239
1240         my @attrs;
1241         foreach my $attr (qw{rel class title}) {
1242                 if (defined $opts{$attr}) {
1243                         push @attrs, " $attr=\"$opts{$attr}\"";
1244                 }
1245         }
1246
1247         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1248 }
1249
1250 sub userpage ($) {
1251         my $user=shift;
1252         return length $config{userdir} ? "$config{userdir}/$user" : $user;
1253 }
1254
1255 sub openiduser ($) {
1256         my $user=shift;
1257
1258         if (defined $user && $user =~ m!^https?://! &&
1259             eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1260                 my $display;
1261
1262                 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1263                         $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1264                 }
1265                 else {
1266                         # backcompat with old version
1267                         my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1268                         $display=$oid->display;
1269                 }
1270
1271                 # Convert "user.somehost.com" to "user [somehost.com]"
1272                 # (also "user.somehost.co.uk")
1273                 if ($display !~ /\[/) {
1274                         $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1275                 }
1276                 # Convert "http://somehost.com/user" to "user [somehost.com]".
1277                 # (also "https://somehost.com/user/")
1278                 if ($display !~ /\[/) {
1279                         $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1280                 }
1281                 $display=~s!^https?://!!; # make sure this is removed
1282                 eval q{use CGI 'escapeHTML'};
1283                 error($@) if $@;
1284                 return escapeHTML($display);
1285         }
1286         return;
1287 }
1288
1289 sub htmlize ($$$$) {
1290         my $page=shift;
1291         my $destpage=shift;
1292         my $type=shift;
1293         my $content=shift;
1294         
1295         my $oneline = $content !~ /\n/;
1296         
1297         if (exists $hooks{htmlize}{$type}) {
1298                 $content=$hooks{htmlize}{$type}{call}->(
1299                         page => $page,
1300                         content => $content,
1301                 );
1302         }
1303         else {
1304                 error("htmlization of $type not supported");
1305         }
1306
1307         run_hooks(sanitize => sub {
1308                 $content=shift->(
1309                         page => $page,
1310                         destpage => $destpage,
1311                         content => $content,
1312                 );
1313         });
1314         
1315         if ($oneline) {
1316                 # hack to get rid of enclosing junk added by markdown
1317                 # and other htmlizers/sanitizers
1318                 $content=~s/^<p>//i;
1319                 $content=~s/<\/p>\n*$//i;
1320         }
1321
1322         return $content;
1323 }
1324
1325 sub linkify ($$$) {
1326         my $page=shift;
1327         my $destpage=shift;
1328         my $content=shift;
1329
1330         run_hooks(linkify => sub {
1331                 $content=shift->(
1332                         page => $page,
1333                         destpage => $destpage,
1334                         content => $content,
1335                 );
1336         });
1337         
1338         return $content;
1339 }
1340
1341 our %preprocessing;
1342 our $preprocess_preview=0;
1343 sub preprocess ($$$;$$) {
1344         my $page=shift; # the page the data comes from
1345         my $destpage=shift; # the page the data will appear in (different for inline)
1346         my $content=shift;
1347         my $scan=shift;
1348         my $preview=shift;
1349
1350         # Using local because it needs to be set within any nested calls
1351         # of this function.
1352         local $preprocess_preview=$preview if defined $preview;
1353
1354         my $handle=sub {
1355                 my $escape=shift;
1356                 my $prefix=shift;
1357                 my $command=shift;
1358                 my $params=shift;
1359                 $params="" if ! defined $params;
1360
1361                 if (length $escape) {
1362                         return "[[$prefix$command $params]]";
1363                 }
1364                 elsif (exists $hooks{preprocess}{$command}) {
1365                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1366                         # Note: preserve order of params, some plugins may
1367                         # consider it significant.
1368                         my @params;
1369                         while ($params =~ m{
1370                                 (?:([-\w]+)=)?          # 1: named parameter key?
1371                                 (?:
1372                                         """(.*?)"""     # 2: triple-quoted value
1373                                 |
1374                                         "([^"]*?)"      # 3: single-quoted value
1375                                 |
1376                                         (\S+)           # 4: unquoted value
1377                                 )
1378                                 (?:\s+|$)               # delimiter to next param
1379                         }sgx) {
1380                                 my $key=$1;
1381                                 my $val;
1382                                 if (defined $2) {
1383                                         $val=$2;
1384                                         $val=~s/\r\n/\n/mg;
1385                                         $val=~s/^\n+//g;
1386                                         $val=~s/\n+$//g;
1387                                 }
1388                                 elsif (defined $3) {
1389                                         $val=$3;
1390                                 }
1391                                 elsif (defined $4) {
1392                                         $val=$4;
1393                                 }
1394
1395                                 if (defined $key) {
1396                                         push @params, $key, $val;
1397                                 }
1398                                 else {
1399                                         push @params, $val, '';
1400                                 }
1401                         }
1402                         if ($preprocessing{$page}++ > 3) {
1403                                 # Avoid loops of preprocessed pages preprocessing
1404                                 # other pages that preprocess them, etc.
1405                                 return "[[!$command <span class=\"error\">".
1406                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1407                                                 $page, $preprocessing{$page}).
1408                                         "</span>]]";
1409                         }
1410                         my $ret;
1411                         if (! $scan) {
1412                                 $ret=eval {
1413                                         $hooks{preprocess}{$command}{call}->(
1414                                                 @params,
1415                                                 page => $page,
1416                                                 destpage => $destpage,
1417                                                 preview => $preprocess_preview,
1418                                         );
1419                                 };
1420                                 if ($@) {
1421                                         my $error=$@;
1422                                         chomp $error;
1423                                         $ret="[[!$command <span class=\"error\">".
1424                                                 gettext("Error").": $error"."</span>]]";
1425                                 }
1426                         }
1427                         else {
1428                                 # use void context during scan pass
1429                                 eval {
1430                                         $hooks{preprocess}{$command}{call}->(
1431                                                 @params,
1432                                                 page => $page,
1433                                                 destpage => $destpage,
1434                                                 preview => $preprocess_preview,
1435                                         );
1436                                 };
1437                                 $ret="";
1438                         }
1439                         $preprocessing{$page}--;
1440                         return $ret;
1441                 }
1442                 else {
1443                         return "[[$prefix$command $params]]";
1444                 }
1445         };
1446         
1447         my $regex;
1448         if ($config{prefix_directives}) {
1449                 $regex = qr{
1450                         (\\?)           # 1: escape?
1451                         \[\[(!)         # directive open; 2: prefix
1452                         ([-\w]+)        # 3: command
1453                         (               # 4: the parameters..
1454                                 \s+     # Must have space if parameters present
1455                                 (?:
1456                                         (?:[-\w]+=)?            # named parameter key?
1457                                         (?:
1458                                                 """.*?"""       # triple-quoted value
1459                                                 |
1460                                                 "[^"]*?"        # single-quoted value
1461                                                 |
1462                                                 [^"\s\]]+       # unquoted value
1463                                         )
1464                                         \s*                     # whitespace or end
1465                                                                 # of directive
1466                                 )
1467                         *)?             # 0 or more parameters
1468                         \]\]            # directive closed
1469                 }sx;
1470         }
1471         else {
1472                 $regex = qr{
1473                         (\\?)           # 1: escape?
1474                         \[\[(!?)        # directive open; 2: optional prefix
1475                         ([-\w]+)        # 3: command
1476                         \s+
1477                         (               # 4: the parameters..
1478                                 (?:
1479                                         (?:[-\w]+=)?            # named parameter key?
1480                                         (?:
1481                                                 """.*?"""       # triple-quoted value
1482                                                 |
1483                                                 "[^"]*?"        # single-quoted value
1484                                                 |
1485                                                 [^"\s\]]+       # unquoted value
1486                                         )
1487                                         \s*                     # whitespace or end
1488                                                                 # of directive
1489                                 )
1490                         *)              # 0 or more parameters
1491                         \]\]            # directive closed
1492                 }sx;
1493         }
1494
1495         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1496         return $content;
1497 }
1498
1499 sub filter ($$$) {
1500         my $page=shift;
1501         my $destpage=shift;
1502         my $content=shift;
1503
1504         run_hooks(filter => sub {
1505                 $content=shift->(page => $page, destpage => $destpage, 
1506                         content => $content);
1507         });
1508
1509         return $content;
1510 }
1511
1512 sub check_canedit ($$$;$) {
1513         my $page=shift;
1514         my $q=shift;
1515         my $session=shift;
1516         my $nonfatal=shift;
1517         
1518         my $canedit;
1519         run_hooks(canedit => sub {
1520                 return if defined $canedit;
1521                 my $ret=shift->($page, $q, $session);
1522                 if (defined $ret) {
1523                         if ($ret eq "") {
1524                                 $canedit=1;
1525                         }
1526                         elsif (ref $ret eq 'CODE') {
1527                                 $ret->() unless $nonfatal;
1528                                 $canedit=0;
1529                         }
1530                         elsif (defined $ret) {
1531                                 error($ret) unless $nonfatal;
1532                                 $canedit=0;
1533                         }
1534                 }
1535         });
1536         return defined $canedit ? $canedit : 1;
1537 }
1538
1539 sub check_content (@) {
1540         my %params=@_;
1541         
1542         return 1 if ! exists $hooks{checkcontent}; # optimisation
1543
1544         if (exists $pagesources{$params{page}}) {
1545                 my @diff;
1546                 my %old=map { $_ => 1 }
1547                         split("\n", readfile(srcfile($pagesources{$params{page}})));
1548                 foreach my $line (split("\n", $params{content})) {
1549                         push @diff, $line if ! exists $old{$line};
1550                 }
1551                 $params{diff}=join("\n", @diff);
1552         }
1553
1554         my $ok;
1555         run_hooks(checkcontent => sub {
1556                 return if defined $ok;
1557                 my $ret=shift->(%params);
1558                 if (defined $ret) {
1559                         if ($ret eq "") {
1560                                 $ok=1;
1561                         }
1562                         elsif (ref $ret eq 'CODE') {
1563                                 $ret->() unless $params{nonfatal};
1564                                 $ok=0;
1565                         }
1566                         elsif (defined $ret) {
1567                                 error($ret) unless $params{nonfatal};
1568                                 $ok=0;
1569                         }
1570                 }
1571
1572         });
1573         return defined $ok ? $ok : 1;
1574 }
1575
1576 sub check_canchange (@) {
1577         my %params = @_;
1578         my $cgi = $params{cgi};
1579         my $session = $params{session};
1580         my @changes = @{$params{changes}};
1581
1582         my %newfiles;
1583         foreach my $change (@changes) {
1584                 # This untaint is safe because we check file_pruned and
1585                 # wiki_file_regexp.
1586                 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1587                 $file=possibly_foolish_untaint($file);
1588                 if (! defined $file || ! length $file ||
1589                     file_pruned($file)) {
1590                         error(gettext("bad file name %s"), $file);
1591                 }
1592
1593                 my $type=pagetype($file);
1594                 my $page=pagename($file) if defined $type;
1595
1596                 if ($change->{action} eq 'add') {
1597                         $newfiles{$file}=1;
1598                 }
1599
1600                 if ($change->{action} eq 'change' ||
1601                     $change->{action} eq 'add') {
1602                         if (defined $page) {
1603                                 check_canedit($page, $cgi, $session);
1604                                 next;
1605                         }
1606                         else {
1607                                 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1608                                         IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1609                                         check_canedit($file, $cgi, $session);
1610                                         next;
1611                                 }
1612                         }
1613                 }
1614                 elsif ($change->{action} eq 'remove') {
1615                         # check_canremove tests to see if the file is present
1616                         # on disk. This will fail when a single commit adds a
1617                         # file and then removes it again. Avoid the problem
1618                         # by not testing the removal in such pairs of changes.
1619                         # (The add is still tested, just to make sure that
1620                         # no data is added to the repo that a web edit
1621                         # could not add.)
1622                         next if $newfiles{$file};
1623
1624                         if (IkiWiki::Plugin::remove->can("check_canremove")) {
1625                                 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1626                                 check_canedit(defined $page ? $page : $file, $cgi, $session);
1627                                 next;
1628                         }
1629                 }
1630                 else {
1631                         error "unknown action ".$change->{action};
1632                 }
1633
1634                 error sprintf(gettext("you are not allowed to change %s"), $file);
1635         }
1636 }
1637
1638
1639 my $wikilock;
1640
1641 sub lockwiki () {
1642         # Take an exclusive lock on the wiki to prevent multiple concurrent
1643         # run issues. The lock will be dropped on program exit.
1644         if (! -d $config{wikistatedir}) {
1645                 mkdir($config{wikistatedir});
1646         }
1647         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1648                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1649         if (! flock($wikilock, 2)) { # LOCK_EX
1650                 error("failed to get lock");
1651         }
1652         return 1;
1653 }
1654
1655 sub unlockwiki () {
1656         POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1657         return close($wikilock) if $wikilock;
1658         return;
1659 }
1660
1661 my $commitlock;
1662
1663 sub commit_hook_enabled () {
1664         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1665                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1666         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1667                 close($commitlock) || error("failed closing commitlock: $!");
1668                 return 0;
1669         }
1670         close($commitlock) || error("failed closing commitlock: $!");
1671         return 1;
1672 }
1673
1674 sub disable_commit_hook () {
1675         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1676                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1677         if (! flock($commitlock, 2)) { # LOCK_EX
1678                 error("failed to get commit lock");
1679         }
1680         return 1;
1681 }
1682
1683 sub enable_commit_hook () {
1684         return close($commitlock) if $commitlock;
1685         return;
1686 }
1687
1688 sub loadindex () {
1689         %oldrenderedfiles=%pagectime=();
1690         if (! $config{rebuild}) {
1691                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1692                 %destsources=%renderedfiles=%pagecase=%pagestate=
1693                 %depends_simple=%typedlinks=%oldtypedlinks=();
1694         }
1695         my $in;
1696         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1697                 if (-e "$config{wikistatedir}/index") {
1698                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1699                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1700                 }
1701                 else {
1702                         $config{gettime}=1; # first build
1703                         return;
1704                 }
1705         }
1706
1707         my $index=Storable::fd_retrieve($in);
1708         if (! defined $index) {
1709                 return 0;
1710         }
1711
1712         my $pages;
1713         if (exists $index->{version} && ! ref $index->{version}) {
1714                 $pages=$index->{page};
1715                 %wikistate=%{$index->{state}};
1716                 # Handle plugins that got disabled by loading a new setup.
1717                 if (exists $config{setupfile}) {
1718                         require IkiWiki::Setup;
1719                         IkiWiki::Setup::disabled_plugins(
1720                                 grep { ! $loaded_plugins{$_} } keys %wikistate);
1721                 }
1722         }
1723         else {
1724                 $pages=$index;
1725                 %wikistate=();
1726         }
1727
1728         foreach my $src (keys %$pages) {
1729                 my $d=$pages->{$src};
1730                 my $page=pagename($src);
1731                 $pagectime{$page}=$d->{ctime};
1732                 $pagesources{$page}=$src;
1733                 if (! $config{rebuild}) {
1734                         $pagemtime{$page}=$d->{mtime};
1735                         $renderedfiles{$page}=$d->{dest};
1736                         if (exists $d->{links} && ref $d->{links}) {
1737                                 $links{$page}=$d->{links};
1738                                 $oldlinks{$page}=[@{$d->{links}}];
1739                         }
1740                         if (ref $d->{depends_simple} eq 'ARRAY') {
1741                                 # old format
1742                                 $depends_simple{$page}={
1743                                         map { $_ => 1 } @{$d->{depends_simple}}
1744                                 };
1745                         }
1746                         elsif (exists $d->{depends_simple}) {
1747                                 $depends_simple{$page}=$d->{depends_simple};
1748                         }
1749                         if (exists $d->{dependslist}) {
1750                                 # old format
1751                                 $depends{$page}={
1752                                         map { $_ => $DEPEND_CONTENT }
1753                                                 @{$d->{dependslist}}
1754                                 };
1755                         }
1756                         elsif (exists $d->{depends} && ! ref $d->{depends}) {
1757                                 # old format
1758                                 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1759                         }
1760                         elsif (exists $d->{depends}) {
1761                                 $depends{$page}=$d->{depends};
1762                         }
1763                         if (exists $d->{state}) {
1764                                 $pagestate{$page}=$d->{state};
1765                         }
1766                         if (exists $d->{typedlinks}) {
1767                                 $typedlinks{$page}=$d->{typedlinks};
1768
1769                                 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1770                                         next unless %$links;
1771                                         $oldtypedlinks{$page}{$type} = {%$links};
1772                                 }
1773                         }
1774                 }
1775                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1776         }
1777         foreach my $page (keys %pagesources) {
1778                 $pagecase{lc $page}=$page;
1779         }
1780         foreach my $page (keys %renderedfiles) {
1781                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1782         }
1783         return close($in);
1784 }
1785
1786 sub saveindex () {
1787         run_hooks(savestate => sub { shift->() });
1788
1789         my @plugins=keys %loaded_plugins;
1790
1791         if (! -d $config{wikistatedir}) {
1792                 mkdir($config{wikistatedir});
1793         }
1794         my $newfile="$config{wikistatedir}/indexdb.new";
1795         my $cleanup = sub { unlink($newfile) };
1796         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1797
1798         my %index;
1799         foreach my $page (keys %pagemtime) {
1800                 next unless $pagemtime{$page};
1801                 my $src=$pagesources{$page};
1802
1803                 $index{page}{$src}={
1804                         ctime => $pagectime{$page},
1805                         mtime => $pagemtime{$page},
1806                         dest => $renderedfiles{$page},
1807                         links => $links{$page},
1808                 };
1809
1810                 if (exists $depends{$page}) {
1811                         $index{page}{$src}{depends} = $depends{$page};
1812                 }
1813
1814                 if (exists $depends_simple{$page}) {
1815                         $index{page}{$src}{depends_simple} = $depends_simple{$page};
1816                 }
1817
1818                 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1819                         $index{page}{$src}{typedlinks} = $typedlinks{$page};
1820                 }
1821
1822                 if (exists $pagestate{$page}) {
1823                         foreach my $id (@plugins) {
1824                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1825                                         $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1826                                 }
1827                         }
1828                 }
1829         }
1830
1831         $index{state}={};
1832         foreach my $id (@plugins) {
1833                 $index{state}{$id}={}; # used to detect disabled plugins
1834                 foreach my $key (keys %{$wikistate{$id}}) {
1835                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
1836                 }
1837         }
1838         
1839         $index{version}="3";
1840         my $ret=Storable::nstore_fd(\%index, $out);
1841         return if ! defined $ret || ! $ret;
1842         close $out || error("failed saving to $newfile: $!", $cleanup);
1843         rename($newfile, "$config{wikistatedir}/indexdb") ||
1844                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1845         
1846         return 1;
1847 }
1848
1849 sub template_file ($) {
1850         my $name=shift;
1851         
1852         my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1853         my $template;
1854         if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1855                 $template=srcfile($pagesources{$tpage}, 1);
1856                 $name.=".tmpl";
1857         }
1858         else {
1859                 $template=srcfile($tpage, 1);
1860         }
1861
1862         if (defined $template) {
1863                 return $template, $tpage, 1 if wantarray;
1864                 return $template;
1865         }
1866         else {
1867                 $name=~s:/::; # avoid path traversal
1868                 foreach my $dir ($config{templatedir},
1869                                  "$installdir/share/ikiwiki/templates") {
1870                         if (-e "$dir/$name") {
1871                                 $template="$dir/$name";
1872                                 last;
1873                         }
1874                 }
1875                 if (defined $template) {        
1876                         return $template, $tpage if wantarray;
1877                         return $template;
1878                 }
1879         }
1880
1881         return;
1882 }
1883
1884 sub template_depends ($$;@) {
1885         my $name=shift;
1886         my $page=shift;
1887         
1888         my ($filename, $tpage, $untrusted)=template_file($name);
1889         if (! defined $filename) {
1890                 error(sprintf(gettext("template %s not found"), $name))
1891         }
1892
1893         if (defined $page && defined $tpage) {
1894                 add_depends($page, $tpage);
1895         }
1896         
1897         my @opts=(
1898                 filter => sub {
1899                         my $text_ref = shift;
1900                         ${$text_ref} = decode_utf8(${$text_ref});
1901                 },
1902                 loop_context_vars => 1,
1903                 die_on_bad_params => 0,
1904                 parent_global_vars => 1,
1905                 filename => $filename,
1906                 @_,
1907                 ($untrusted ? (no_includes => 1) : ()),
1908         );
1909         return @opts if wantarray;
1910
1911         require HTML::Template;
1912         return HTML::Template->new(@opts);
1913 }
1914
1915 sub template ($;@) {
1916         template_depends(shift, undef, @_);
1917 }
1918
1919 sub misctemplate ($$;@) {
1920         my $title=shift;
1921         my $content=shift;
1922         my %params=@_;
1923         
1924         my $template=template("page.tmpl");
1925
1926         my $page="";
1927         if (exists $params{page}) {
1928                 $page=delete $params{page};
1929         }
1930         run_hooks(pagetemplate => sub {
1931                 shift->(
1932                         page => $page,
1933                         destpage => $page,
1934                         template => $template,
1935                 );
1936         });
1937         templateactions($template, "");
1938
1939         $template->param(
1940                 dynamic => 1,
1941                 title => $title,
1942                 wikiname => $config{wikiname},
1943                 content => $content,
1944                 baseurl => $config{url}.'/',
1945                 html5 => $config{html5},
1946                 %params,
1947         );
1948         
1949         return $template->output;
1950 }
1951
1952 sub templateactions ($$) {
1953         my $template=shift;
1954         my $page=shift;
1955
1956         my $have_actions=0;
1957         my @actions;
1958         run_hooks(pageactions => sub {
1959                 push @actions, map { { action => $_ } } 
1960                         grep { defined } shift->(page => $page);
1961         });
1962         $template->param(actions => \@actions);
1963
1964         if ($config{cgiurl} && exists $hooks{auth}) {
1965                 $template->param(prefsurl => cgiurl(do => "prefs"));
1966                 $have_actions=1;
1967         }
1968
1969         if ($have_actions || @actions) {
1970                 $template->param(have_actions => 1);
1971         }
1972 }
1973
1974 sub hook (@) {
1975         my %param=@_;
1976         
1977         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1978                 error 'hook requires type, call, and id parameters';
1979         }
1980
1981         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1982         
1983         $hooks{$param{type}}{$param{id}}=\%param;
1984         return 1;
1985 }
1986
1987 sub run_hooks ($$) {
1988         # Calls the given sub for each hook of the given type,
1989         # passing it the hook function to call.
1990         my $type=shift;
1991         my $sub=shift;
1992
1993         if (exists $hooks{$type}) {
1994                 my (@first, @middle, @last);
1995                 foreach my $id (keys %{$hooks{$type}}) {
1996                         if ($hooks{$type}{$id}{first}) {
1997                                 push @first, $id;
1998                         }
1999                         elsif ($hooks{$type}{$id}{last}) {
2000                                 push @last, $id;
2001                         }
2002                         else {
2003                                 push @middle, $id;
2004                         }
2005                 }
2006                 foreach my $id (@first, @middle, @last) {
2007                         $sub->($hooks{$type}{$id}{call});
2008                 }
2009         }
2010
2011         return 1;
2012 }
2013
2014 sub rcs_update () {
2015         $hooks{rcs}{rcs_update}{call}->(@_);
2016 }
2017
2018 sub rcs_prepedit ($) {
2019         $hooks{rcs}{rcs_prepedit}{call}->(@_);
2020 }
2021
2022 sub rcs_commit (@) {
2023         $hooks{rcs}{rcs_commit}{call}->(@_);
2024 }
2025
2026 sub rcs_commit_staged (@) {
2027         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2028 }
2029
2030 sub rcs_add ($) {
2031         $hooks{rcs}{rcs_add}{call}->(@_);
2032 }
2033
2034 sub rcs_remove ($) {
2035         $hooks{rcs}{rcs_remove}{call}->(@_);
2036 }
2037
2038 sub rcs_rename ($$) {
2039         $hooks{rcs}{rcs_rename}{call}->(@_);
2040 }
2041
2042 sub rcs_recentchanges ($) {
2043         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2044 }
2045
2046 sub rcs_diff ($;$) {
2047         $hooks{rcs}{rcs_diff}{call}->(@_);
2048 }
2049
2050 sub rcs_getctime ($) {
2051         $hooks{rcs}{rcs_getctime}{call}->(@_);
2052 }
2053
2054 sub rcs_getmtime ($) {
2055         $hooks{rcs}{rcs_getmtime}{call}->(@_);
2056 }
2057
2058 sub rcs_receive () {
2059         $hooks{rcs}{rcs_receive}{call}->();
2060 }
2061
2062 sub add_depends ($$;$) {
2063         my $page=shift;
2064         my $pagespec=shift;
2065         my $deptype=shift || $DEPEND_CONTENT;
2066
2067         # Is the pagespec a simple page name?
2068         if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2069             $pagespec !~ /[\s*?()!]/) {
2070                 $depends_simple{$page}{lc $pagespec} |= $deptype;
2071                 return 1;
2072         }
2073
2074         # Add explicit dependencies for influences.
2075         my $sub=pagespec_translate($pagespec);
2076         return unless defined $sub;
2077         foreach my $p (keys %pagesources) {
2078                 my $r=$sub->($p, location => $page);
2079                 my $i=$r->influences;
2080                 my $static=$r->influences_static;
2081                 foreach my $k (keys %$i) {
2082                         next unless $r || $static || $k eq $page;
2083                         $depends_simple{$page}{lc $k} |= $i->{$k};
2084                 }
2085                 last if $static;
2086         }
2087
2088         $depends{$page}{$pagespec} |= $deptype;
2089         return 1;
2090 }
2091
2092 sub deptype (@) {
2093         my $deptype=0;
2094         foreach my $type (@_) {
2095                 if ($type eq 'presence') {
2096                         $deptype |= $DEPEND_PRESENCE;
2097                 }
2098                 elsif ($type eq 'links') { 
2099                         $deptype |= $DEPEND_LINKS;
2100                 }
2101                 elsif ($type eq 'content') {
2102                         $deptype |= $DEPEND_CONTENT;
2103                 }
2104         }
2105         return $deptype;
2106 }
2107
2108 my $file_prune_regexp;
2109 sub file_pruned ($) {
2110         my $file=shift;
2111
2112         if (defined $config{include} && length $config{include}) {
2113                 return 0 if $file =~ m/$config{include}/;
2114         }
2115
2116         if (! defined $file_prune_regexp) {
2117                 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2118                 $file_prune_regexp=qr/$file_prune_regexp/;
2119         }
2120         return $file =~ m/$file_prune_regexp/;
2121 }
2122
2123 sub define_gettext () {
2124         # If translation is needed, redefine the gettext function to do it.
2125         # Otherwise, it becomes a quick no-op.
2126         my $gettext_obj;
2127         my $getobj;
2128         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2129             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2130             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2131                 $getobj=sub {
2132                         $gettext_obj=eval q{
2133                                 use Locale::gettext q{textdomain};
2134                                 Locale::gettext->domain('ikiwiki')
2135                         };
2136                 };
2137         }
2138
2139         no warnings 'redefine';
2140         *gettext=sub {
2141                 $getobj->() if $getobj;
2142                 if ($gettext_obj) {
2143                         $gettext_obj->get(shift);
2144                 }
2145                 else {
2146                         return shift;
2147                 }
2148         };
2149         *ngettext=sub {
2150                 $getobj->() if $getobj;
2151                 if ($gettext_obj) {
2152                         $gettext_obj->nget(@_);
2153                 }
2154                 else {
2155                         return ($_[2] == 1 ? $_[0] : $_[1])
2156                 }
2157         };
2158 }
2159
2160 sub gettext {
2161         define_gettext();
2162         gettext(@_);
2163 }
2164
2165 sub ngettext {
2166         define_gettext();
2167         ngettext(@_);
2168 }
2169
2170 sub yesno ($) {
2171         my $val=shift;
2172
2173         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2174 }
2175
2176 sub inject {
2177         # Injects a new function into the symbol table to replace an
2178         # exported function.
2179         my %params=@_;
2180
2181         # This is deep ugly perl foo, beware.
2182         no strict;
2183         no warnings;
2184         if (! defined $params{parent}) {
2185                 $params{parent}='::';
2186                 $params{old}=\&{$params{name}};
2187                 $params{name}=~s/.*:://;
2188         }
2189         my $parent=$params{parent};
2190         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2191                 $ns = $params{parent} . $ns;
2192                 inject(%params, parent => $ns) unless $ns eq '::main::';
2193                 *{$ns . $params{name}} = $params{call}
2194                         if exists ${$ns}{$params{name}} &&
2195                            \&{${$ns}{$params{name}}} == $params{old};
2196         }
2197         use strict;
2198         use warnings;
2199 }
2200
2201 sub add_link ($$;$) {
2202         my $page=shift;
2203         my $link=shift;
2204         my $type=shift;
2205
2206         push @{$links{$page}}, $link
2207                 unless grep { $_ eq $link } @{$links{$page}};
2208
2209         if (defined $type) {
2210                 $typedlinks{$page}{$type}{$link} = 1;
2211         }
2212 }
2213
2214 sub add_autofile ($$$) {
2215         my $file=shift;
2216         my $plugin=shift;
2217         my $generator=shift;
2218         
2219         $autofiles{$file}{plugin}=$plugin;
2220         $autofiles{$file}{generator}=$generator;
2221 }
2222
2223 sub sortspec_translate ($$) {
2224         my $spec = shift;
2225         my $reverse = shift;
2226
2227         my $code = "";
2228         my @data;
2229         while ($spec =~ m{
2230                 \s*
2231                 (-?)            # group 1: perhaps negated
2232                 \s*
2233                 (               # group 2: a word
2234                         \w+\([^\)]*\)   # command(params)
2235                         |
2236                         [^\s]+          # or anything else
2237                 )
2238                 \s*
2239         }gx) {
2240                 my $negated = $1;
2241                 my $word = $2;
2242                 my $params = undef;
2243
2244                 if ($word =~ m/^(\w+)\((.*)\)$/) {
2245                         # command with parameters
2246                         $params = $2;
2247                         $word = $1;
2248                 }
2249                 elsif ($word !~ m/^\w+$/) {
2250                         error(sprintf(gettext("invalid sort type %s"), $word));
2251                 }
2252
2253                 if (length $code) {
2254                         $code .= " || ";
2255                 }
2256
2257                 if ($negated) {
2258                         $code .= "-";
2259                 }
2260
2261                 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2262                         if (defined $params) {
2263                                 push @data, $params;
2264                                 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2265                         }
2266                         else {
2267                                 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2268                         }
2269                 }
2270                 else {
2271                         error(sprintf(gettext("unknown sort type %s"), $word));
2272                 }
2273         }
2274
2275         if (! length $code) {
2276                 # undefined sorting method... sort arbitrarily
2277                 return sub { 0 };
2278         }
2279
2280         if ($reverse) {
2281                 $code="-($code)";
2282         }
2283
2284         no warnings;
2285         return eval 'sub { '.$code.' }';
2286 }
2287
2288 sub pagespec_translate ($) {
2289         my $spec=shift;
2290
2291         # Convert spec to perl code.
2292         my $code="";
2293         my @data;
2294         while ($spec=~m{
2295                 \s*             # ignore whitespace
2296                 (               # 1: match a single word
2297                         \!              # !
2298                 |
2299                         \(              # (
2300                 |
2301                         \)              # )
2302                 |
2303                         \w+\([^\)]*\)   # command(params)
2304                 |
2305                         [^\s()]+        # any other text
2306                 )
2307                 \s*             # ignore whitespace
2308         }gx) {
2309                 my $word=$1;
2310                 if (lc $word eq 'and') {
2311                         $code.=' &';
2312                 }
2313                 elsif (lc $word eq 'or') {
2314                         $code.=' |';
2315                 }
2316                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2317                         $code.=' '.$word;
2318                 }
2319                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2320                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2321                                 push @data, $2;
2322                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2323                         }
2324                         else {
2325                                 push @data, qq{unknown function in pagespec "$word"};
2326                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2327                         }
2328                 }
2329                 else {
2330                         push @data, $word;
2331                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2332                 }
2333         }
2334
2335         if (! length $code) {
2336                 $code="IkiWiki::FailReason->new('empty pagespec')";
2337         }
2338
2339         no warnings;
2340         return eval 'sub { my $page=shift; '.$code.' }';
2341 }
2342
2343 sub pagespec_match ($$;@) {
2344         my $page=shift;
2345         my $spec=shift;
2346         my @params=@_;
2347
2348         # Backwards compatability with old calling convention.
2349         if (@params == 1) {
2350                 unshift @params, 'location';
2351         }
2352
2353         my $sub=pagespec_translate($spec);
2354         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2355                 if ! defined $sub;
2356         return $sub->($page, @params);
2357 }
2358
2359 sub pagespec_match_list ($$;@) {
2360         my $page=shift;
2361         my $pagespec=shift;
2362         my %params=@_;
2363
2364         # Backwards compatability with old calling convention.
2365         if (ref $page) {
2366                 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2367                 $params{list}=$page;
2368                 $page=$params{location}; # ugh!
2369         }
2370
2371         my $sub=pagespec_translate($pagespec);
2372         error "syntax error in pagespec \"$pagespec\""
2373                 if ! defined $sub;
2374         my $sort=sortspec_translate($params{sort}, $params{reverse})
2375                 if defined $params{sort};
2376
2377         my @candidates;
2378         if (exists $params{list}) {
2379                 @candidates=exists $params{filter}
2380                         ? grep { ! $params{filter}->($_) } @{$params{list}}
2381                         : @{$params{list}};
2382         }
2383         else {
2384                 @candidates=exists $params{filter}
2385                         ? grep { ! $params{filter}->($_) } keys %pagesources
2386                         : keys %pagesources;
2387         }
2388         
2389         # clear params, remainder is passed to pagespec
2390         $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2391         my $num=$params{num};
2392         delete @params{qw{num deptype reverse sort filter list}};
2393         
2394         # when only the top matches will be returned, it's efficient to
2395         # sort before matching to pagespec,
2396         if (defined $num && defined $sort) {
2397                 @candidates=IkiWiki::SortSpec::sort_pages(
2398                         $sort, @candidates);
2399         }
2400         
2401         my @matches;
2402         my $firstfail;
2403         my $count=0;
2404         my $accum=IkiWiki::SuccessReason->new();
2405         foreach my $p (@candidates) {
2406                 my $r=$sub->($p, %params, location => $page);
2407                 error(sprintf(gettext("cannot match pages: %s"), $r))
2408                         if $r->isa("IkiWiki::ErrorReason");
2409                 unless ($r || $r->influences_static) {
2410                         $r->remove_influence($p);
2411                 }
2412                 $accum |= $r;
2413                 if ($r) {
2414                         push @matches, $p;
2415                         last if defined $num && ++$count == $num;
2416                 }
2417         }
2418
2419         # Add simple dependencies for accumulated influences.
2420         my $i=$accum->influences;
2421         foreach my $k (keys %$i) {
2422                 $depends_simple{$page}{lc $k} |= $i->{$k};
2423         }
2424
2425         # when all matches will be returned, it's efficient to
2426         # sort after matching
2427         if (! defined $num && defined $sort) {
2428                 return IkiWiki::SortSpec::sort_pages(
2429                         $sort, @matches);
2430         }
2431         else {
2432                 return @matches;
2433         }
2434 }
2435
2436 sub pagespec_valid ($) {
2437         my $spec=shift;
2438
2439         return defined pagespec_translate($spec);
2440 }
2441
2442 sub glob2re ($) {
2443         my $re=quotemeta(shift);
2444         $re=~s/\\\*/.*/g;
2445         $re=~s/\\\?/./g;
2446         return qr/^$re$/i;
2447 }
2448
2449 package IkiWiki::FailReason;
2450
2451 use overload (
2452         '""'    => sub { $_[0][0] },
2453         '0+'    => sub { 0 },
2454         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2455         '&'     => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2456         '|'     => sub { $_[1]->merge_influences($_[0]); $_[1] },
2457         fallback => 1,
2458 );
2459
2460 our @ISA = 'IkiWiki::SuccessReason';
2461
2462 package IkiWiki::SuccessReason;
2463
2464 use overload (
2465         '""'    => sub { $_[0][0] },
2466         '0+'    => sub { 1 },
2467         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
2468         '&'     => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2469         '|'     => sub { $_[0]->merge_influences($_[1]); $_[0] },
2470         fallback => 1,
2471 );
2472
2473 sub new {
2474         my $class = shift;
2475         my $value = shift;
2476         return bless [$value, {@_}], $class;
2477 }
2478
2479 sub influences {
2480         my $this=shift;
2481         $this->[1]={@_} if @_;
2482         my %i=%{$this->[1]};
2483         delete $i{""};
2484         return \%i;
2485 }
2486
2487 sub influences_static {
2488         return ! $_[0][1]->{""};
2489 }
2490
2491 sub merge_influences {
2492         my $this=shift;
2493         my $other=shift;
2494         my $anded=shift;
2495
2496         if (! $anded || (($this || %{$this->[1]}) &&
2497                          ($other || %{$other->[1]}))) {
2498                 foreach my $influence (keys %{$other->[1]}) {
2499                         $this->[1]{$influence} |= $other->[1]{$influence};
2500                 }
2501         }
2502         else {
2503                 # influence blocker
2504                 $this->[1]={};
2505         }
2506 }
2507
2508 sub remove_influence {
2509         my $this=shift;
2510         my $torm=shift;
2511
2512         delete $this->[1]{$torm};
2513 }
2514
2515 package IkiWiki::ErrorReason;
2516
2517 our @ISA = 'IkiWiki::FailReason';
2518
2519 package IkiWiki::PageSpec;
2520
2521 sub derel ($$) {
2522         my $path=shift;
2523         my $from=shift;
2524
2525         if ($path =~ m!^\.(/|$)!) {
2526                 if ($1) {
2527                         $from=~s#/?[^/]+$## if defined $from;
2528                         $path=~s#^\./##;
2529                         $path="$from/$path" if defined $from && length $from;
2530                 }
2531                 else {
2532                         $path = $from;
2533                         $path = "" unless defined $path;
2534                 }
2535         }
2536
2537         return $path;
2538 }
2539
2540 my %glob_cache;
2541
2542 sub match_glob ($$;@) {
2543         my $page=shift;
2544         my $glob=shift;
2545         my %params=@_;
2546         
2547         $glob=derel($glob, $params{location});
2548
2549         # Instead of converting the glob to a regex every time,
2550         # cache the compiled regex to save time.
2551         my $re=$glob_cache{$glob};
2552         unless (defined $re) {
2553                 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2554         }
2555         if ($page =~ $re) {
2556                 if (! IkiWiki::isinternal($page) || $params{internal}) {
2557                         return IkiWiki::SuccessReason->new("$glob matches $page");
2558                 }
2559                 else {
2560                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2561                 }
2562         }
2563         else {
2564                 return IkiWiki::FailReason->new("$glob does not match $page");
2565         }
2566 }
2567
2568 sub match_internal ($$;@) {
2569         return match_glob(shift, shift, @_, internal => 1)
2570 }
2571
2572 sub match_page ($$;@) {
2573         my $page=shift;
2574         my $match=match_glob($page, shift, @_);
2575         if ($match) {
2576                 my $source=exists $IkiWiki::pagesources{$page} ?
2577                         $IkiWiki::pagesources{$page} :
2578                         $IkiWiki::delpagesources{$page};
2579                 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2580                 if (! defined $type) {  
2581                         return IkiWiki::FailReason->new("$page is not a page");
2582                 }
2583         }
2584         return $match;
2585 }
2586
2587 sub match_link ($$;@) {
2588         my $page=shift;
2589         my $link=lc(shift);
2590         my %params=@_;
2591
2592         $link=derel($link, $params{location});
2593         my $from=exists $params{location} ? $params{location} : '';
2594         my $linktype=$params{linktype};
2595         my $qualifier='';
2596         if (defined $linktype) {
2597                 $qualifier=" with type $linktype";
2598         }
2599
2600         my $links = $IkiWiki::links{$page};
2601         return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2602                 unless $links && @{$links};
2603         my $bestlink = IkiWiki::bestlink($from, $link);
2604         foreach my $p (@{$links}) {
2605                 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2606
2607                 if (length $bestlink) {
2608                         if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2609                                 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2610                         }
2611                 }
2612                 else {
2613                         if (match_glob($p, $link, %params)) {
2614                                 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2615                         }
2616                         my ($p_rel)=$p=~/^\/?(.*)/;
2617                         $link=~s/^\///;
2618                         if (match_glob($p_rel, $link, %params)) {
2619                                 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2620                         }
2621                 }
2622         }
2623         return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2624 }
2625
2626 sub match_backlink ($$;@) {
2627         my $ret=match_link($_[1], $_[0], @_);
2628         $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2629         return $ret;
2630 }
2631
2632 sub match_created_before ($$;@) {
2633         my $page=shift;
2634         my $testpage=shift;
2635         my %params=@_;
2636         
2637         $testpage=derel($testpage, $params{location});
2638
2639         if (exists $IkiWiki::pagectime{$testpage}) {
2640                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2641                         return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2642                 }
2643                 else {
2644                         return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2645                 }
2646         }
2647         else {
2648                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2649         }
2650 }
2651
2652 sub match_created_after ($$;@) {
2653         my $page=shift;
2654         my $testpage=shift;
2655         my %params=@_;
2656         
2657         $testpage=derel($testpage, $params{location});
2658
2659         if (exists $IkiWiki::pagectime{$testpage}) {
2660                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2661                         return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2662                 }
2663                 else {
2664                         return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2665                 }
2666         }
2667         else {
2668                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2669         }
2670 }
2671
2672 sub match_creation_day ($$;@) {
2673         my $page=shift;
2674         my $d=shift;
2675         if ($d !~ /^\d+$/) {
2676                 return IkiWiki::ErrorReason->new("invalid day $d");
2677         }
2678         if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2679                 return IkiWiki::SuccessReason->new('creation_day matched');
2680         }
2681         else {
2682                 return IkiWiki::FailReason->new('creation_day did not match');
2683         }
2684 }
2685
2686 sub match_creation_month ($$;@) {
2687         my $page=shift;
2688         my $m=shift;
2689         if ($m !~ /^\d+$/) {
2690                 return IkiWiki::ErrorReason->new("invalid month $m");
2691         }
2692         if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2693                 return IkiWiki::SuccessReason->new('creation_month matched');
2694         }
2695         else {
2696                 return IkiWiki::FailReason->new('creation_month did not match');
2697         }
2698 }
2699
2700 sub match_creation_year ($$;@) {
2701         my $page=shift;
2702         my $y=shift;
2703         if ($y !~ /^\d+$/) {
2704                 return IkiWiki::ErrorReason->new("invalid year $y");
2705         }
2706         if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2707                 return IkiWiki::SuccessReason->new('creation_year matched');
2708         }
2709         else {
2710                 return IkiWiki::FailReason->new('creation_year did not match');
2711         }
2712 }
2713
2714 sub match_user ($$;@) {
2715         shift;
2716         my $user=shift;
2717         my %params=@_;
2718         
2719         my $regexp=IkiWiki::glob2re($user);
2720         
2721         if (! exists $params{user}) {
2722                 return IkiWiki::ErrorReason->new("no user specified");
2723         }
2724
2725         if (defined $params{user} && $params{user}=~$regexp) {
2726                 return IkiWiki::SuccessReason->new("user is $user");
2727         }
2728         elsif (! defined $params{user}) {
2729                 return IkiWiki::FailReason->new("not logged in");
2730         }
2731         else {
2732                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2733         }
2734 }
2735
2736 sub match_admin ($$;@) {
2737         shift;
2738         shift;
2739         my %params=@_;
2740         
2741         if (! exists $params{user}) {
2742                 return IkiWiki::ErrorReason->new("no user specified");
2743         }
2744
2745         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2746                 return IkiWiki::SuccessReason->new("user is an admin");
2747         }
2748         elsif (! defined $params{user}) {
2749                 return IkiWiki::FailReason->new("not logged in");
2750         }
2751         else {
2752                 return IkiWiki::FailReason->new("user is not an admin");
2753         }
2754 }
2755
2756 sub match_ip ($$;@) {
2757         shift;
2758         my $ip=shift;
2759         my %params=@_;
2760         
2761         if (! exists $params{ip}) {
2762                 return IkiWiki::ErrorReason->new("no IP specified");
2763         }
2764
2765         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2766                 return IkiWiki::SuccessReason->new("IP is $ip");
2767         }
2768         else {
2769                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2770         }
2771 }
2772
2773 package IkiWiki::SortSpec;
2774
2775 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2776 # are easily available in this namespace, for cmp functions to use them.
2777 sub sort_pages {
2778         my $f=shift;
2779         sort $f @_
2780 }
2781
2782 sub cmp_title {
2783         IkiWiki::pagetitle(IkiWiki::basename($a))
2784         cmp
2785         IkiWiki::pagetitle(IkiWiki::basename($b))
2786 }
2787
2788 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2789 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }
2790
2791 1