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