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