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