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