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