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