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