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