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