]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki.pm
cgiurl: don't append "?" if there are no parameters
[ikiwiki.git] / IkiWiki.pm
1 #!/usr/bin/perl
2
3 package IkiWiki;
4
5 use warnings;
6 use strict;
7 use Encode;
8 use URI::Escape q{uri_escape_utf8};
9 use POSIX ();
10 use Storable;
11 use open qw{:utf8 :std};
12
13 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
14         %pagestate %wikistate %renderedfiles %oldrenderedfiles
15         %pagesources %delpagesources %destsources %depends %depends_simple
16         @mass_depends %hooks %forcerebuild %loaded_plugins %typedlinks
17         %oldtypedlinks %autofiles};
18
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error htmlpage template template_depends
21         deptype add_depends pagespec_match pagespec_match_list bestlink
22         htmllink readfile writefile pagetype srcfile pagename
23         displaytime 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=$config{cgiurl};
1043         if (exists $params{cgiurl}) {
1044                 $cgiurl=$params{cgiurl};
1045                 delete $params{cgiurl};
1046         }
1047
1048         unless (%params) {
1049                 return $cgiurl;
1050         }
1051
1052         return $cgiurl."?".
1053                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1054 }
1055
1056 sub baseurl (;$) {
1057         my $page=shift;
1058
1059         return "$config{url}/" if ! defined $page;
1060         
1061         $page=htmlpage($page);
1062         $page=~s/[^\/]+$//;
1063         $page=~s/[^\/]+\//..\//g;
1064         return $page;
1065 }
1066
1067 sub abs2rel ($$) {
1068         # Work around very innefficient behavior in File::Spec if abs2rel
1069         # is passed two relative paths. It's much faster if paths are
1070         # absolute! (Debian bug #376658; fixed in debian unstable now)
1071         my $path="/".shift;
1072         my $base="/".shift;
1073
1074         require File::Spec;
1075         my $ret=File::Spec->abs2rel($path, $base);
1076         $ret=~s/^// if defined $ret;
1077         return $ret;
1078 }
1079
1080 sub displaytime ($;$$) {
1081         # Plugins can override this function to mark up the time to
1082         # display.
1083         my $time=formattime($_[0], $_[1]);
1084         if ($config{html5}) {
1085                 return '<time datetime="'.date_3339($_[0]).'"'.
1086                         ($_[2] ? ' pubdate="pubdate"' : '').
1087                         '>'.$time.'</time>';
1088         }
1089         else {
1090                 return '<span class="date">'.$time.'</span>';
1091         }
1092 }
1093
1094 sub formattime ($;$) {
1095         # Plugins can override this function to format the time.
1096         my $time=shift;
1097         my $format=shift;
1098         if (! defined $format) {
1099                 $format=$config{timeformat};
1100         }
1101
1102         # strftime doesn't know about encodings, so make sure
1103         # its output is properly treated as utf8
1104         return decode_utf8(POSIX::strftime($format, localtime($time)));
1105 }
1106
1107 sub date_3339 ($) {
1108         my $time=shift;
1109
1110         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1111         POSIX::setlocale(&POSIX::LC_TIME, "C");
1112         my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1113         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1114         return $ret;
1115 }
1116
1117 sub beautify_urlpath ($) {
1118         my $url=shift;
1119
1120         # Ensure url is not an empty link, and if necessary,
1121         # add ./ to avoid colon confusion.
1122         if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1123                 $url="./$url";
1124         }
1125
1126         if ($config{usedirs}) {
1127                 $url =~ s!/index.$config{htmlext}$!/!;
1128         }
1129
1130         return $url;
1131 }
1132
1133 sub urlto ($$;$) {
1134         my $to=shift;
1135         my $from=shift;
1136         my $absolute=shift;
1137         
1138         if (! length $to) {
1139                 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1140         }
1141
1142         if (! $destsources{$to}) {
1143                 $to=htmlpage($to);
1144         }
1145
1146         if ($absolute) {
1147                 return $config{url}.beautify_urlpath("/".$to);
1148         }
1149
1150         my $link = abs2rel($to, dirname(htmlpage($from)));
1151
1152         return beautify_urlpath($link);
1153 }
1154
1155 sub isselflink ($$) {
1156         # Plugins can override this function to support special types
1157         # of selflinks.
1158         my $page=shift;
1159         my $link=shift;
1160
1161         return $page eq $link;
1162 }
1163
1164 sub htmllink ($$$;@) {
1165         my $lpage=shift; # the page doing the linking
1166         my $page=shift; # the page that will contain the link (different for inline)
1167         my $link=shift;
1168         my %opts=@_;
1169
1170         $link=~s/\/$//;
1171
1172         my $bestlink;
1173         if (! $opts{forcesubpage}) {
1174                 $bestlink=bestlink($lpage, $link);
1175         }
1176         else {
1177                 $bestlink="$lpage/".lc($link);
1178         }
1179
1180         my $linktext;
1181         if (defined $opts{linktext}) {
1182                 $linktext=$opts{linktext};
1183         }
1184         else {
1185                 $linktext=pagetitle(basename($link));
1186         }
1187         
1188         return "<span class=\"selflink\">$linktext</span>"
1189                 if length $bestlink && isselflink($page, $bestlink) &&
1190                    ! defined $opts{anchor};
1191         
1192         if (! $destsources{$bestlink}) {
1193                 $bestlink=htmlpage($bestlink);
1194
1195                 if (! $destsources{$bestlink}) {
1196                         my $cgilink = "";
1197                         if (length $config{cgiurl}) {
1198                                 $cgilink = "<a href=\"".
1199                                         cgiurl(
1200                                                 do => "create",
1201                                                 page => lc($link),
1202                                                 from => $lpage
1203                                         )."\" rel=\"nofollow\">?</a>";
1204                         }
1205                         return "<span class=\"createlink\">$cgilink$linktext</span>"
1206                 }
1207         }
1208         
1209         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1210         $bestlink=beautify_urlpath($bestlink);
1211         
1212         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1213                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1214         }
1215
1216         if (defined $opts{anchor}) {
1217                 $bestlink.="#".$opts{anchor};
1218         }
1219
1220         my @attrs;
1221         foreach my $attr (qw{rel class title}) {
1222                 if (defined $opts{$attr}) {
1223                         push @attrs, " $attr=\"$opts{$attr}\"";
1224                 }
1225         }
1226
1227         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1228 }
1229
1230 sub userpage ($) {
1231         my $user=shift;
1232         return length $config{userdir} ? "$config{userdir}/$user" : $user;
1233 }
1234
1235 sub openiduser ($) {
1236         my $user=shift;
1237
1238         if ($user =~ m!^https?://! &&
1239             eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1240                 my $display;
1241
1242                 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1243                         $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1244                 }
1245                 else {
1246                         # backcompat with old version
1247                         my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1248                         $display=$oid->display;
1249                 }
1250
1251                 # Convert "user.somehost.com" to "user [somehost.com]"
1252                 # (also "user.somehost.co.uk")
1253                 if ($display !~ /\[/) {
1254                         $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1255                 }
1256                 # Convert "http://somehost.com/user" to "user [somehost.com]".
1257                 # (also "https://somehost.com/user/")
1258                 if ($display !~ /\[/) {
1259                         $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1260                 }
1261                 $display=~s!^https?://!!; # make sure this is removed
1262                 eval q{use CGI 'escapeHTML'};
1263                 error($@) if $@;
1264                 return escapeHTML($display);
1265         }
1266         return;
1267 }
1268
1269 sub htmlize ($$$$) {
1270         my $page=shift;
1271         my $destpage=shift;
1272         my $type=shift;
1273         my $content=shift;
1274         
1275         my $oneline = $content !~ /\n/;
1276         
1277         if (exists $hooks{htmlize}{$type}) {
1278                 $content=$hooks{htmlize}{$type}{call}->(
1279                         page => $page,
1280                         content => $content,
1281                 );
1282         }
1283         else {
1284                 error("htmlization of $type not supported");
1285         }
1286
1287         run_hooks(sanitize => sub {
1288                 $content=shift->(
1289                         page => $page,
1290                         destpage => $destpage,
1291                         content => $content,
1292                 );
1293         });
1294         
1295         if ($oneline) {
1296                 # hack to get rid of enclosing junk added by markdown
1297                 # and other htmlizers/sanitizers
1298                 $content=~s/^<p>//i;
1299                 $content=~s/<\/p>\n*$//i;
1300         }
1301
1302         return $content;
1303 }
1304
1305 sub linkify ($$$) {
1306         my $page=shift;
1307         my $destpage=shift;
1308         my $content=shift;
1309
1310         run_hooks(linkify => sub {
1311                 $content=shift->(
1312                         page => $page,
1313                         destpage => $destpage,
1314                         content => $content,
1315                 );
1316         });
1317         
1318         return $content;
1319 }
1320
1321 our %preprocessing;
1322 our $preprocess_preview=0;
1323 sub preprocess ($$$;$$) {
1324         my $page=shift; # the page the data comes from
1325         my $destpage=shift; # the page the data will appear in (different for inline)
1326         my $content=shift;
1327         my $scan=shift;
1328         my $preview=shift;
1329
1330         # Using local because it needs to be set within any nested calls
1331         # of this function.
1332         local $preprocess_preview=$preview if defined $preview;
1333
1334         my $handle=sub {
1335                 my $escape=shift;
1336                 my $prefix=shift;
1337                 my $command=shift;
1338                 my $params=shift;
1339                 $params="" if ! defined $params;
1340
1341                 if (length $escape) {
1342                         return "[[$prefix$command $params]]";
1343                 }
1344                 elsif (exists $hooks{preprocess}{$command}) {
1345                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1346                         # Note: preserve order of params, some plugins may
1347                         # consider it significant.
1348                         my @params;
1349                         while ($params =~ m{
1350                                 (?:([-\w]+)=)?          # 1: named parameter key?
1351                                 (?:
1352                                         """(.*?)"""     # 2: triple-quoted value
1353                                 |
1354                                         "([^"]*?)"      # 3: single-quoted value
1355                                 |
1356                                         (\S+)           # 4: unquoted value
1357                                 )
1358                                 (?:\s+|$)               # delimiter to next param
1359                         }sgx) {
1360                                 my $key=$1;
1361                                 my $val;
1362                                 if (defined $2) {
1363                                         $val=$2;
1364                                         $val=~s/\r\n/\n/mg;
1365                                         $val=~s/^\n+//g;
1366                                         $val=~s/\n+$//g;
1367                                 }
1368                                 elsif (defined $3) {
1369                                         $val=$3;
1370                                 }
1371                                 elsif (defined $4) {
1372                                         $val=$4;
1373                                 }
1374
1375                                 if (defined $key) {
1376                                         push @params, $key, $val;
1377                                 }
1378                                 else {
1379                                         push @params, $val, '';
1380                                 }
1381                         }
1382                         if ($preprocessing{$page}++ > 3) {
1383                                 # Avoid loops of preprocessed pages preprocessing
1384                                 # other pages that preprocess them, etc.
1385                                 return "[[!$command <span class=\"error\">".
1386                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1387                                                 $page, $preprocessing{$page}).
1388                                         "</span>]]";
1389                         }
1390                         my $ret;
1391                         if (! $scan) {
1392                                 $ret=eval {
1393                                         $hooks{preprocess}{$command}{call}->(
1394                                                 @params,
1395                                                 page => $page,
1396                                                 destpage => $destpage,
1397                                                 preview => $preprocess_preview,
1398                                         );
1399                                 };
1400                                 if ($@) {
1401                                         my $error=$@;
1402                                         chomp $error;
1403                                         $ret="[[!$command <span class=\"error\">".
1404                                                 gettext("Error").": $error"."</span>]]";
1405                                 }
1406                         }
1407                         else {
1408                                 # use void context during scan pass
1409                                 eval {
1410                                         $hooks{preprocess}{$command}{call}->(
1411                                                 @params,
1412                                                 page => $page,
1413                                                 destpage => $destpage,
1414                                                 preview => $preprocess_preview,
1415                                         );
1416                                 };
1417                                 $ret="";
1418                         }
1419                         $preprocessing{$page}--;
1420                         return $ret;
1421                 }
1422                 else {
1423                         return "[[$prefix$command $params]]";
1424                 }
1425         };
1426         
1427         my $regex;
1428         if ($config{prefix_directives}) {
1429                 $regex = qr{
1430                         (\\?)           # 1: escape?
1431                         \[\[(!)         # directive open; 2: prefix
1432                         ([-\w]+)        # 3: command
1433                         (               # 4: the parameters..
1434                                 \s+     # Must have space if parameters present
1435                                 (?:
1436                                         (?:[-\w]+=)?            # named parameter key?
1437                                         (?:
1438                                                 """.*?"""       # triple-quoted value
1439                                                 |
1440                                                 "[^"]*?"        # single-quoted value
1441                                                 |
1442                                                 [^"\s\]]+       # unquoted value
1443                                         )
1444                                         \s*                     # whitespace or end
1445                                                                 # of directive
1446                                 )
1447                         *)?             # 0 or more parameters
1448                         \]\]            # directive closed
1449                 }sx;
1450         }
1451         else {
1452                 $regex = qr{
1453                         (\\?)           # 1: escape?
1454                         \[\[(!?)        # directive open; 2: optional prefix
1455                         ([-\w]+)        # 3: command
1456                         \s+
1457                         (               # 4: the parameters..
1458                                 (?:
1459                                         (?:[-\w]+=)?            # named parameter key?
1460                                         (?:
1461                                                 """.*?"""       # triple-quoted value
1462                                                 |
1463                                                 "[^"]*?"        # single-quoted value
1464                                                 |
1465                                                 [^"\s\]]+       # unquoted value
1466                                         )
1467                                         \s*                     # whitespace or end
1468                                                                 # of directive
1469                                 )
1470                         *)              # 0 or more parameters
1471                         \]\]            # directive closed
1472                 }sx;
1473         }
1474
1475         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1476         return $content;
1477 }
1478
1479 sub filter ($$$) {
1480         my $page=shift;
1481         my $destpage=shift;
1482         my $content=shift;
1483
1484         run_hooks(filter => sub {
1485                 $content=shift->(page => $page, destpage => $destpage, 
1486                         content => $content);
1487         });
1488
1489         return $content;
1490 }
1491
1492 sub check_canedit ($$$;$) {
1493         my $page=shift;
1494         my $q=shift;
1495         my $session=shift;
1496         my $nonfatal=shift;
1497         
1498         my $canedit;
1499         run_hooks(canedit => sub {
1500                 return if defined $canedit;
1501                 my $ret=shift->($page, $q, $session);
1502                 if (defined $ret) {
1503                         if ($ret eq "") {
1504                                 $canedit=1;
1505                         }
1506                         elsif (ref $ret eq 'CODE') {
1507                                 $ret->() unless $nonfatal;
1508                                 $canedit=0;
1509                         }
1510                         elsif (defined $ret) {
1511                                 error($ret) unless $nonfatal;
1512                                 $canedit=0;
1513                         }
1514                 }
1515         });
1516         return defined $canedit ? $canedit : 1;
1517 }
1518
1519 sub check_content (@) {
1520         my %params=@_;
1521         
1522         return 1 if ! exists $hooks{checkcontent}; # optimisation
1523
1524         if (exists $pagesources{$params{page}}) {
1525                 my @diff;
1526                 my %old=map { $_ => 1 }
1527                         split("\n", readfile(srcfile($pagesources{$params{page}})));
1528                 foreach my $line (split("\n", $params{content})) {
1529                         push @diff, $line if ! exists $old{$line};
1530                 }
1531                 $params{diff}=join("\n", @diff);
1532         }
1533
1534         my $ok;
1535         run_hooks(checkcontent => sub {
1536                 return if defined $ok;
1537                 my $ret=shift->(%params);
1538                 if (defined $ret) {
1539                         if ($ret eq "") {
1540                                 $ok=1;
1541                         }
1542                         elsif (ref $ret eq 'CODE') {
1543                                 $ret->() unless $params{nonfatal};
1544                                 $ok=0;
1545                         }
1546                         elsif (defined $ret) {
1547                                 error($ret) unless $params{nonfatal};
1548                                 $ok=0;
1549                         }
1550                 }
1551
1552         });
1553         return defined $ok ? $ok : 1;
1554 }
1555
1556 sub check_canchange (@) {
1557         my %params = @_;
1558         my $cgi = $params{cgi};
1559         my $session = $params{session};
1560         my @changes = @{$params{changes}};
1561
1562         my %newfiles;
1563         foreach my $change (@changes) {
1564                 # This untaint is safe because we check file_pruned and
1565                 # wiki_file_regexp.
1566                 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1567                 $file=possibly_foolish_untaint($file);
1568                 if (! defined $file || ! length $file ||
1569                     file_pruned($file)) {
1570                         error(gettext("bad file name %s"), $file);
1571                 }
1572
1573                 my $type=pagetype($file);
1574                 my $page=pagename($file) if defined $type;
1575
1576                 if ($change->{action} eq 'add') {
1577                         $newfiles{$file}=1;
1578                 }
1579
1580                 if ($change->{action} eq 'change' ||
1581                     $change->{action} eq 'add') {
1582                         if (defined $page) {
1583                                 check_canedit($page, $cgi, $session);
1584                                 next;
1585                         }
1586                         else {
1587                                 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1588                                         IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1589                                         check_canedit($file, $cgi, $session);
1590                                         next;
1591                                 }
1592                         }
1593                 }
1594                 elsif ($change->{action} eq 'remove') {
1595                         # check_canremove tests to see if the file is present
1596                         # on disk. This will fail when a single commit adds a
1597                         # file and then removes it again. Avoid the problem
1598                         # by not testing the removal in such pairs of changes.
1599                         # (The add is still tested, just to make sure that
1600                         # no data is added to the repo that a web edit
1601                         # could not add.)
1602                         next if $newfiles{$file};
1603
1604                         if (IkiWiki::Plugin::remove->can("check_canremove")) {
1605                                 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1606                                 check_canedit(defined $page ? $page : $file, $cgi, $session);
1607                                 next;
1608                         }
1609                 }
1610                 else {
1611                         error "unknown action ".$change->{action};
1612                 }
1613
1614                 error sprintf(gettext("you are not allowed to change %s"), $file);
1615         }
1616 }
1617
1618
1619 my $wikilock;
1620
1621 sub lockwiki () {
1622         # Take an exclusive lock on the wiki to prevent multiple concurrent
1623         # run issues. The lock will be dropped on program exit.
1624         if (! -d $config{wikistatedir}) {
1625                 mkdir($config{wikistatedir});
1626         }
1627         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1628                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1629         if (! flock($wikilock, 2)) { # LOCK_EX
1630                 error("failed to get lock");
1631         }
1632         return 1;
1633 }
1634
1635 sub unlockwiki () {
1636         POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1637         return close($wikilock) if $wikilock;
1638         return;
1639 }
1640
1641 my $commitlock;
1642
1643 sub commit_hook_enabled () {
1644         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1645                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1646         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1647                 close($commitlock) || error("failed closing commitlock: $!");
1648                 return 0;
1649         }
1650         close($commitlock) || error("failed closing commitlock: $!");
1651         return 1;
1652 }
1653
1654 sub disable_commit_hook () {
1655         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1656                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1657         if (! flock($commitlock, 2)) { # LOCK_EX
1658                 error("failed to get commit lock");
1659         }
1660         return 1;
1661 }
1662
1663 sub enable_commit_hook () {
1664         return close($commitlock) if $commitlock;
1665         return;
1666 }
1667
1668 sub loadindex () {
1669         %oldrenderedfiles=%pagectime=();
1670         if (! $config{rebuild}) {
1671                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1672                 %destsources=%renderedfiles=%pagecase=%pagestate=
1673                 %depends_simple=%typedlinks=%oldtypedlinks=();
1674         }
1675         my $in;
1676         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1677                 if (-e "$config{wikistatedir}/index") {
1678                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1679                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1680                 }
1681                 else {
1682                         $config{gettime}=1; # first build
1683                         return;
1684                 }
1685         }
1686
1687         my $index=Storable::fd_retrieve($in);
1688         if (! defined $index) {
1689                 return 0;
1690         }
1691
1692         my $pages;
1693         if (exists $index->{version} && ! ref $index->{version}) {
1694                 $pages=$index->{page};
1695                 %wikistate=%{$index->{state}};
1696                 # Handle plugins that got disabled by loading a new setup.
1697                 if (exists $config{setupfile}) {
1698                         require IkiWiki::Setup;
1699                         IkiWiki::Setup::disabled_plugins(
1700                                 grep { ! $loaded_plugins{$_} } keys %wikistate);
1701                 }
1702         }
1703         else {
1704                 $pages=$index;
1705                 %wikistate=();
1706         }
1707
1708         foreach my $src (keys %$pages) {
1709                 my $d=$pages->{$src};
1710                 my $page=pagename($src);
1711                 $pagectime{$page}=$d->{ctime};
1712                 $pagesources{$page}=$src;
1713                 if (! $config{rebuild}) {
1714                         $pagemtime{$page}=$d->{mtime};
1715                         $renderedfiles{$page}=$d->{dest};
1716                         if (exists $d->{links} && ref $d->{links}) {
1717                                 $links{$page}=$d->{links};
1718                                 $oldlinks{$page}=[@{$d->{links}}];
1719                         }
1720                         if (ref $d->{depends_simple} eq 'ARRAY') {
1721                                 # old format
1722                                 $depends_simple{$page}={
1723                                         map { $_ => 1 } @{$d->{depends_simple}}
1724                                 };
1725                         }
1726                         elsif (exists $d->{depends_simple}) {
1727                                 $depends_simple{$page}=$d->{depends_simple};
1728                         }
1729                         if (exists $d->{dependslist}) {
1730                                 # old format
1731                                 $depends{$page}={
1732                                         map { $_ => $DEPEND_CONTENT }
1733                                                 @{$d->{dependslist}}
1734                                 };
1735                         }
1736                         elsif (exists $d->{depends} && ! ref $d->{depends}) {
1737                                 # old format
1738                                 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1739                         }
1740                         elsif (exists $d->{depends}) {
1741                                 $depends{$page}=$d->{depends};
1742                         }
1743                         if (exists $d->{state}) {
1744                                 $pagestate{$page}=$d->{state};
1745                         }
1746                         if (exists $d->{typedlinks}) {
1747                                 $typedlinks{$page}=$d->{typedlinks};
1748
1749                                 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1750                                         next unless %$links;
1751                                         $oldtypedlinks{$page}{$type} = {%$links};
1752                                 }
1753                         }
1754                 }
1755                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1756         }
1757         foreach my $page (keys %pagesources) {
1758                 $pagecase{lc $page}=$page;
1759         }
1760         foreach my $page (keys %renderedfiles) {
1761                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1762         }
1763         return close($in);
1764 }
1765
1766 sub saveindex () {
1767         run_hooks(savestate => sub { shift->() });
1768
1769         my @plugins=keys %loaded_plugins;
1770
1771         if (! -d $config{wikistatedir}) {
1772                 mkdir($config{wikistatedir});
1773         }
1774         my $newfile="$config{wikistatedir}/indexdb.new";
1775         my $cleanup = sub { unlink($newfile) };
1776         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1777
1778         my %index;
1779         foreach my $page (keys %pagemtime) {
1780                 next unless $pagemtime{$page};
1781                 my $src=$pagesources{$page};
1782
1783                 $index{page}{$src}={
1784                         ctime => $pagectime{$page},
1785                         mtime => $pagemtime{$page},
1786                         dest => $renderedfiles{$page},
1787                         links => $links{$page},
1788                 };
1789
1790                 if (exists $depends{$page}) {
1791                         $index{page}{$src}{depends} = $depends{$page};
1792                 }
1793
1794                 if (exists $depends_simple{$page}) {
1795                         $index{page}{$src}{depends_simple} = $depends_simple{$page};
1796                 }
1797
1798                 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1799                         $index{page}{$src}{typedlinks} = $typedlinks{$page};
1800                 }
1801
1802                 if (exists $pagestate{$page}) {
1803                         foreach my $id (@plugins) {
1804                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1805                                         $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1806                                 }
1807                         }
1808                 }
1809         }
1810
1811         $index{state}={};
1812         foreach my $id (@plugins) {
1813                 $index{state}{$id}={}; # used to detect disabled plugins
1814                 foreach my $key (keys %{$wikistate{$id}}) {
1815                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
1816                 }
1817         }
1818         
1819         $index{version}="3";
1820         my $ret=Storable::nstore_fd(\%index, $out);
1821         return if ! defined $ret || ! $ret;
1822         close $out || error("failed saving to $newfile: $!", $cleanup);
1823         rename($newfile, "$config{wikistatedir}/indexdb") ||
1824                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1825         
1826         return 1;
1827 }
1828
1829 sub template_file ($) {
1830         my $name=shift;
1831         
1832         my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1833         my $template;
1834         if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1835                 $template=srcfile($pagesources{$tpage}, 1);
1836                 $name.=".tmpl";
1837         }
1838         else {
1839                 $template=srcfile($tpage, 1);
1840         }
1841
1842         if (defined $template) {
1843                 return $template, $tpage, 1 if wantarray;
1844                 return $template;
1845         }
1846         else {
1847                 $name=~s:/::; # avoid path traversal
1848                 foreach my $dir ($config{templatedir},
1849                                  "$installdir/share/ikiwiki/templates") {
1850                         if (-e "$dir/$name") {
1851                                 $template="$dir/$name";
1852                                 last;
1853                         }
1854                 }
1855                 if (defined $template) {        
1856                         return $template, $tpage if wantarray;
1857                         return $template;
1858                 }
1859         }
1860
1861         return;
1862 }
1863
1864 sub template_depends ($$;@) {
1865         my $name=shift;
1866         my $page=shift;
1867         
1868         my ($filename, $tpage, $untrusted)=template_file($name);
1869         if (! defined $filename) {
1870                 error(sprintf(gettext("template %s not found"), $name))
1871         }
1872
1873         if (defined $page && defined $tpage) {
1874                 add_depends($page, $tpage);
1875         }
1876         
1877         my @opts=(
1878                 filter => sub {
1879                         my $text_ref = shift;
1880                         ${$text_ref} = decode_utf8(${$text_ref});
1881                 },
1882                 loop_context_vars => 1,
1883                 die_on_bad_params => 0,
1884                 filename => $filename,
1885                 @_,
1886                 ($untrusted ? (no_includes => 1) : ()),
1887         );
1888         return @opts if wantarray;
1889
1890         require HTML::Template;
1891         return HTML::Template->new(@opts);
1892 }
1893
1894 sub template ($;@) {
1895         template_depends(shift, undef, @_);
1896 }
1897
1898 sub misctemplate ($$;@) {
1899         my $title=shift;
1900         my $content=shift;
1901         my %params=@_;
1902         
1903         my $template=template("page.tmpl");
1904
1905         my $page="";
1906         if (exists $params{page}) {
1907                 $page=delete $params{page};
1908         }
1909         run_hooks(pagetemplate => sub {
1910                 shift->(
1911                         page => $page,
1912                         destpage => $page,
1913                         template => $template,
1914                 );
1915         });
1916         templateactions($template, "");
1917
1918         $template->param(
1919                 dynamic => 1,
1920                 title => $title,
1921                 wikiname => $config{wikiname},
1922                 content => $content,
1923                 baseurl => baseurl(),
1924                 html5 => $config{html5},
1925                 %params,
1926         );
1927         
1928         return $template->output;
1929 }
1930
1931 sub templateactions ($$) {
1932         my $template=shift;
1933         my $page=shift;
1934
1935         my $have_actions=0;
1936         my @actions;
1937         run_hooks(pageactions => sub {
1938                 push @actions, map { { action => $_ } } 
1939                         grep { defined } shift->(page => $page);
1940         });
1941         $template->param(actions => \@actions);
1942
1943         if ($config{cgiurl} && exists $hooks{auth}) {
1944                 $template->param(prefsurl => cgiurl(do => "prefs"));
1945                 $have_actions=1;
1946         }
1947
1948         if ($have_actions || @actions) {
1949                 $template->param(have_actions => 1);
1950         }
1951 }
1952
1953 sub hook (@) {
1954         my %param=@_;
1955         
1956         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1957                 error 'hook requires type, call, and id parameters';
1958         }
1959
1960         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1961         
1962         $hooks{$param{type}}{$param{id}}=\%param;
1963         return 1;
1964 }
1965
1966 sub run_hooks ($$) {
1967         # Calls the given sub for each hook of the given type,
1968         # passing it the hook function to call.
1969         my $type=shift;
1970         my $sub=shift;
1971
1972         if (exists $hooks{$type}) {
1973                 my (@first, @middle, @last);
1974                 foreach my $id (keys %{$hooks{$type}}) {
1975                         if ($hooks{$type}{$id}{first}) {
1976                                 push @first, $id;
1977                         }
1978                         elsif ($hooks{$type}{$id}{last}) {
1979                                 push @last, $id;
1980                         }
1981                         else {
1982                                 push @middle, $id;
1983                         }
1984                 }
1985                 foreach my $id (@first, @middle, @last) {
1986                         $sub->($hooks{$type}{$id}{call});
1987                 }
1988         }
1989
1990         return 1;
1991 }
1992
1993 sub rcs_update () {
1994         $hooks{rcs}{rcs_update}{call}->(@_);
1995 }
1996
1997 sub rcs_prepedit ($) {
1998         $hooks{rcs}{rcs_prepedit}{call}->(@_);
1999 }
2000
2001 sub rcs_commit (@) {
2002         $hooks{rcs}{rcs_commit}{call}->(@_);
2003 }
2004
2005 sub rcs_commit_staged (@) {
2006         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2007 }
2008
2009 sub rcs_add ($) {
2010         $hooks{rcs}{rcs_add}{call}->(@_);
2011 }
2012
2013 sub rcs_remove ($) {
2014         $hooks{rcs}{rcs_remove}{call}->(@_);
2015 }
2016
2017 sub rcs_rename ($$) {
2018         $hooks{rcs}{rcs_rename}{call}->(@_);
2019 }
2020
2021 sub rcs_recentchanges ($) {
2022         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2023 }
2024
2025 sub rcs_diff ($) {
2026         $hooks{rcs}{rcs_diff}{call}->(@_);
2027 }
2028
2029 sub rcs_getctime ($) {
2030         $hooks{rcs}{rcs_getctime}{call}->(@_);
2031 }
2032
2033 sub rcs_getmtime ($) {
2034         $hooks{rcs}{rcs_getmtime}{call}->(@_);
2035 }
2036
2037 sub rcs_receive () {
2038         $hooks{rcs}{rcs_receive}{call}->();
2039 }
2040
2041 sub add_depends ($$;$) {
2042         my $page=shift;
2043         my $pagespec=shift;
2044         my $deptype=shift || $DEPEND_CONTENT;
2045
2046         # Is the pagespec a simple page name?
2047         if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2048             $pagespec !~ /[\s*?()!]/) {
2049                 $depends_simple{$page}{lc $pagespec} |= $deptype;
2050                 return 1;
2051         }
2052
2053         # Add explicit dependencies for influences.
2054         my $sub=pagespec_translate($pagespec);
2055         return unless defined $sub;
2056         foreach my $p (keys %pagesources) {
2057                 my $r=$sub->($p, location => $page);
2058                 my $i=$r->influences;
2059                 my $static=$r->influences_static;
2060                 foreach my $k (keys %$i) {
2061                         next unless $r || $static || $k eq $page;
2062                         $depends_simple{$page}{lc $k} |= $i->{$k};
2063                 }
2064                 last if $static;
2065         }
2066
2067         $depends{$page}{$pagespec} |= $deptype;
2068         return 1;
2069 }
2070
2071 sub deptype (@) {
2072         my $deptype=0;
2073         foreach my $type (@_) {
2074                 if ($type eq 'presence') {
2075                         $deptype |= $DEPEND_PRESENCE;
2076                 }
2077                 elsif ($type eq 'links') { 
2078                         $deptype |= $DEPEND_LINKS;
2079                 }
2080                 elsif ($type eq 'content') {
2081                         $deptype |= $DEPEND_CONTENT;
2082                 }
2083         }
2084         return $deptype;
2085 }
2086
2087 my $file_prune_regexp;
2088 sub file_pruned ($) {
2089         my $file=shift;
2090
2091         if (defined $config{include} && length $config{include}) {
2092                 return 0 if $file =~ m/$config{include}/;
2093         }
2094
2095         if (! defined $file_prune_regexp) {
2096                 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2097                 $file_prune_regexp=qr/$file_prune_regexp/;
2098         }
2099         return $file =~ m/$file_prune_regexp/;
2100 }
2101
2102 sub define_gettext () {
2103         # If translation is needed, redefine the gettext function to do it.
2104         # Otherwise, it becomes a quick no-op.
2105         my $gettext_obj;
2106         my $getobj;
2107         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2108             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2109             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2110                 $getobj=sub {
2111                         $gettext_obj=eval q{
2112                                 use Locale::gettext q{textdomain};
2113                                 Locale::gettext->domain('ikiwiki')
2114                         };
2115                 };
2116         }
2117
2118         no warnings 'redefine';
2119         *gettext=sub {
2120                 $getobj->() if $getobj;
2121                 if ($gettext_obj) {
2122                         $gettext_obj->get(shift);
2123                 }
2124                 else {
2125                         return shift;
2126                 }
2127         };
2128         *ngettext=sub {
2129                 $getobj->() if $getobj;
2130                 if ($gettext_obj) {
2131                         $gettext_obj->nget(@_);
2132                 }
2133                 else {
2134                         return ($_[2] == 1 ? $_[0] : $_[1])
2135                 }
2136         };
2137 }
2138
2139 sub gettext {
2140         define_gettext();
2141         gettext(@_);
2142 }
2143
2144 sub ngettext {
2145         define_gettext();
2146         ngettext(@_);
2147 }
2148
2149 sub yesno ($) {
2150         my $val=shift;
2151
2152         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2153 }
2154
2155 sub inject {
2156         # Injects a new function into the symbol table to replace an
2157         # exported function.
2158         my %params=@_;
2159
2160         # This is deep ugly perl foo, beware.
2161         no strict;
2162         no warnings;
2163         if (! defined $params{parent}) {
2164                 $params{parent}='::';
2165                 $params{old}=\&{$params{name}};
2166                 $params{name}=~s/.*:://;
2167         }
2168         my $parent=$params{parent};
2169         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2170                 $ns = $params{parent} . $ns;
2171                 inject(%params, parent => $ns) unless $ns eq '::main::';
2172                 *{$ns . $params{name}} = $params{call}
2173                         if exists ${$ns}{$params{name}} &&
2174                            \&{${$ns}{$params{name}}} == $params{old};
2175         }
2176         use strict;
2177         use warnings;
2178 }
2179
2180 sub add_link ($$;$) {
2181         my $page=shift;
2182         my $link=shift;
2183         my $type=shift;
2184
2185         push @{$links{$page}}, $link
2186                 unless grep { $_ eq $link } @{$links{$page}};
2187
2188         if (defined $type) {
2189                 $typedlinks{$page}{$type}{$link} = 1;
2190         }
2191 }
2192
2193 sub add_autofile ($$$) {
2194         my $file=shift;
2195         my $plugin=shift;
2196         my $generator=shift;
2197         
2198         $autofiles{$file}{plugin}=$plugin;
2199         $autofiles{$file}{generator}=$generator;
2200 }
2201
2202 sub sortspec_translate ($$) {
2203         my $spec = shift;
2204         my $reverse = shift;
2205
2206         my $code = "";
2207         my @data;
2208         while ($spec =~ m{
2209                 \s*
2210                 (-?)            # group 1: perhaps negated
2211                 \s*
2212                 (               # group 2: a word
2213                         \w+\([^\)]*\)   # command(params)
2214                         |
2215                         [^\s]+          # or anything else
2216                 )
2217                 \s*
2218         }gx) {
2219                 my $negated = $1;
2220                 my $word = $2;
2221                 my $params = undef;
2222
2223                 if ($word =~ m/^(\w+)\((.*)\)$/) {
2224                         # command with parameters
2225                         $params = $2;
2226                         $word = $1;
2227                 }
2228                 elsif ($word !~ m/^\w+$/) {
2229                         error(sprintf(gettext("invalid sort type %s"), $word));
2230                 }
2231
2232                 if (length $code) {
2233                         $code .= " || ";
2234                 }
2235
2236                 if ($negated) {
2237                         $code .= "-";
2238                 }
2239
2240                 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2241                         if (defined $params) {
2242                                 push @data, $params;
2243                                 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2244                         }
2245                         else {
2246                                 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2247                         }
2248                 }
2249                 else {
2250                         error(sprintf(gettext("unknown sort type %s"), $word));
2251                 }
2252         }
2253
2254         if (! length $code) {
2255                 # undefined sorting method... sort arbitrarily
2256                 return sub { 0 };
2257         }
2258
2259         if ($reverse) {
2260                 $code="-($code)";
2261         }
2262
2263         no warnings;
2264         return eval 'sub { '.$code.' }';
2265 }
2266
2267 sub pagespec_translate ($) {
2268         my $spec=shift;
2269
2270         # Convert spec to perl code.
2271         my $code="";
2272         my @data;
2273         while ($spec=~m{
2274                 \s*             # ignore whitespace
2275                 (               # 1: match a single word
2276                         \!              # !
2277                 |
2278                         \(              # (
2279                 |
2280                         \)              # )
2281                 |
2282                         \w+\([^\)]*\)   # command(params)
2283                 |
2284                         [^\s()]+        # any other text
2285                 )
2286                 \s*             # ignore whitespace
2287         }gx) {
2288                 my $word=$1;
2289                 if (lc $word eq 'and') {
2290                         $code.=' &';
2291                 }
2292                 elsif (lc $word eq 'or') {
2293                         $code.=' |';
2294                 }
2295                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2296                         $code.=' '.$word;
2297                 }
2298                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2299                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2300                                 push @data, $2;
2301                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2302                         }
2303                         else {
2304                                 push @data, qq{unknown function in pagespec "$word"};
2305                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2306                         }
2307                 }
2308                 else {
2309                         push @data, $word;
2310                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2311                 }
2312         }
2313
2314         if (! length $code) {
2315                 $code="IkiWiki::FailReason->new('empty pagespec')";
2316         }
2317
2318         no warnings;
2319         return eval 'sub { my $page=shift; '.$code.' }';
2320 }
2321
2322 sub pagespec_match ($$;@) {
2323         my $page=shift;
2324         my $spec=shift;
2325         my @params=@_;
2326
2327         # Backwards compatability with old calling convention.
2328         if (@params == 1) {
2329                 unshift @params, 'location';
2330         }
2331
2332         my $sub=pagespec_translate($spec);
2333         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2334                 if ! defined $sub;
2335         return $sub->($page, @params);
2336 }
2337
2338 sub pagespec_match_list ($$;@) {
2339         my $page=shift;
2340         my $pagespec=shift;
2341         my %params=@_;
2342
2343         # Backwards compatability with old calling convention.
2344         if (ref $page) {
2345                 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2346                 $params{list}=$page;
2347                 $page=$params{location}; # ugh!
2348         }
2349
2350         my $sub=pagespec_translate($pagespec);
2351         error "syntax error in pagespec \"$pagespec\""
2352                 if ! defined $sub;
2353         my $sort=sortspec_translate($params{sort}, $params{reverse})
2354                 if defined $params{sort};
2355
2356         my @candidates;
2357         if (exists $params{list}) {
2358                 @candidates=exists $params{filter}
2359                         ? grep { ! $params{filter}->($_) } @{$params{list}}
2360                         : @{$params{list}};
2361         }
2362         else {
2363                 @candidates=exists $params{filter}
2364                         ? grep { ! $params{filter}->($_) } keys %pagesources
2365                         : keys %pagesources;
2366         }
2367         
2368         # clear params, remainder is passed to pagespec
2369         $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2370         my $num=$params{num};
2371         delete @params{qw{num deptype reverse sort filter list}};
2372         
2373         # when only the top matches will be returned, it's efficient to
2374         # sort before matching to pagespec,
2375         if (defined $num && defined $sort) {
2376                 @candidates=IkiWiki::SortSpec::sort_pages(
2377                         $sort, @candidates);
2378         }
2379         
2380         my @matches;
2381         my $firstfail;
2382         my $count=0;
2383         my $accum=IkiWiki::SuccessReason->new();
2384         foreach my $p (@candidates) {
2385                 my $r=$sub->($p, %params, location => $page);
2386                 error(sprintf(gettext("cannot match pages: %s"), $r))
2387                         if $r->isa("IkiWiki::ErrorReason");
2388                 unless ($r || $r->influences_static) {
2389                         $r->remove_influence($p);
2390                 }
2391                 $accum |= $r;
2392                 if ($r) {
2393                         push @matches, $p;
2394                         last if defined $num && ++$count == $num;
2395                 }
2396         }
2397
2398         # Add simple dependencies for accumulated influences.
2399         my $i=$accum->influences;
2400         foreach my $k (keys %$i) {
2401                 $depends_simple{$page}{lc $k} |= $i->{$k};
2402         }
2403
2404         # when all matches will be returned, it's efficient to
2405         # sort after matching
2406         if (! defined $num && defined $sort) {
2407                 return IkiWiki::SortSpec::sort_pages(
2408                         $sort, @matches);
2409         }
2410         else {
2411                 return @matches;
2412         }
2413 }
2414
2415 sub pagespec_valid ($) {
2416         my $spec=shift;
2417
2418         return defined pagespec_translate($spec);
2419 }
2420
2421 sub glob2re ($) {
2422         my $re=quotemeta(shift);
2423         $re=~s/\\\*/.*/g;
2424         $re=~s/\\\?/./g;
2425         return qr/^$re$/i;
2426 }
2427
2428 package IkiWiki::FailReason;
2429
2430 use overload (
2431         '""'    => sub { $_[0][0] },
2432         '0+'    => sub { 0 },
2433         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2434         '&'     => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2435         '|'     => sub { $_[1]->merge_influences($_[0]); $_[1] },
2436         fallback => 1,
2437 );
2438
2439 our @ISA = 'IkiWiki::SuccessReason';
2440
2441 package IkiWiki::SuccessReason;
2442
2443 use overload (
2444         '""'    => sub { $_[0][0] },
2445         '0+'    => sub { 1 },
2446         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
2447         '&'     => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2448         '|'     => sub { $_[0]->merge_influences($_[1]); $_[0] },
2449         fallback => 1,
2450 );
2451
2452 sub new {
2453         my $class = shift;
2454         my $value = shift;
2455         return bless [$value, {@_}], $class;
2456 }
2457
2458 sub influences {
2459         my $this=shift;
2460         $this->[1]={@_} if @_;
2461         my %i=%{$this->[1]};
2462         delete $i{""};
2463         return \%i;
2464 }
2465
2466 sub influences_static {
2467         return ! $_[0][1]->{""};
2468 }
2469
2470 sub merge_influences {
2471         my $this=shift;
2472         my $other=shift;
2473         my $anded=shift;
2474
2475         if (! $anded || (($this || %{$this->[1]}) &&
2476                          ($other || %{$other->[1]}))) {
2477                 foreach my $influence (keys %{$other->[1]}) {
2478                         $this->[1]{$influence} |= $other->[1]{$influence};
2479                 }
2480         }
2481         else {
2482                 # influence blocker
2483                 $this->[1]={};
2484         }
2485 }
2486
2487 sub remove_influence {
2488         my $this=shift;
2489         my $torm=shift;
2490
2491         delete $this->[1]{$torm};
2492 }
2493
2494 package IkiWiki::ErrorReason;
2495
2496 our @ISA = 'IkiWiki::FailReason';
2497
2498 package IkiWiki::PageSpec;
2499
2500 sub derel ($$) {
2501         my $path=shift;
2502         my $from=shift;
2503
2504         if ($path =~ m!^\.(/|$)!) {
2505                 if ($1) {
2506                         $from=~s#/?[^/]+$## if defined $from;
2507                         $path=~s#^\./##;
2508                         $path="$from/$path" if defined $from && length $from;
2509                 }
2510                 else {
2511                         $path = $from;
2512                         $path = "" unless defined $path;
2513                 }
2514         }
2515
2516         return $path;
2517 }
2518
2519 my %glob_cache;
2520
2521 sub match_glob ($$;@) {
2522         my $page=shift;
2523         my $glob=shift;
2524         my %params=@_;
2525         
2526         $glob=derel($glob, $params{location});
2527
2528         # Instead of converting the glob to a regex every time,
2529         # cache the compiled regex to save time.
2530         my $re=$glob_cache{$glob};
2531         unless (defined $re) {
2532                 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2533         }
2534         if ($page =~ $re) {
2535                 if (! IkiWiki::isinternal($page) || $params{internal}) {
2536                         return IkiWiki::SuccessReason->new("$glob matches $page");
2537                 }
2538                 else {
2539                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2540                 }
2541         }
2542         else {
2543                 return IkiWiki::FailReason->new("$glob does not match $page");
2544         }
2545 }
2546
2547 sub match_internal ($$;@) {
2548         return match_glob(shift, shift, @_, internal => 1)
2549 }
2550
2551 sub match_page ($$;@) {
2552         my $page=shift;
2553         my $match=match_glob($page, shift, @_);
2554         if ($match) {
2555                 my $source=exists $IkiWiki::pagesources{$page} ?
2556                         $IkiWiki::pagesources{$page} :
2557                         $IkiWiki::delpagesources{$page};
2558                 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2559                 if (! defined $type) {  
2560                         return IkiWiki::FailReason->new("$page is not a page");
2561                 }
2562         }
2563         return $match;
2564 }
2565
2566 sub match_link ($$;@) {
2567         my $page=shift;
2568         my $link=lc(shift);
2569         my %params=@_;
2570
2571         $link=derel($link, $params{location});
2572         my $from=exists $params{location} ? $params{location} : '';
2573         my $linktype=$params{linktype};
2574         my $qualifier='';
2575         if (defined $linktype) {
2576                 $qualifier=" with type $linktype";
2577         }
2578
2579         my $links = $IkiWiki::links{$page};
2580         return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2581                 unless $links && @{$links};
2582         my $bestlink = IkiWiki::bestlink($from, $link);
2583         foreach my $p (@{$links}) {
2584                 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2585
2586                 if (length $bestlink) {
2587                         if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2588                                 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2589                         }
2590                 }
2591                 else {
2592                         if (match_glob($p, $link, %params)) {
2593                                 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2594                         }
2595                         my ($p_rel)=$p=~/^\/?(.*)/;
2596                         $link=~s/^\///;
2597                         if (match_glob($p_rel, $link, %params)) {
2598                                 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2599                         }
2600                 }
2601         }
2602         return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2603 }
2604
2605 sub match_backlink ($$;@) {
2606         my $ret=match_link($_[1], $_[0], @_);
2607         $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2608         return $ret;
2609 }
2610
2611 sub match_created_before ($$;@) {
2612         my $page=shift;
2613         my $testpage=shift;
2614         my %params=@_;
2615         
2616         $testpage=derel($testpage, $params{location});
2617
2618         if (exists $IkiWiki::pagectime{$testpage}) {
2619                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2620                         return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2621                 }
2622                 else {
2623                         return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2624                 }
2625         }
2626         else {
2627                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2628         }
2629 }
2630
2631 sub match_created_after ($$;@) {
2632         my $page=shift;
2633         my $testpage=shift;
2634         my %params=@_;
2635         
2636         $testpage=derel($testpage, $params{location});
2637
2638         if (exists $IkiWiki::pagectime{$testpage}) {
2639                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2640                         return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2641                 }
2642                 else {
2643                         return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2644                 }
2645         }
2646         else {
2647                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2648         }
2649 }
2650
2651 sub match_creation_day ($$;@) {
2652         my $page=shift;
2653         my $d=shift;
2654         if ($d !~ /^\d+$/) {
2655                 return IkiWiki::ErrorReason->new("invalid day $d");
2656         }
2657         if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2658                 return IkiWiki::SuccessReason->new('creation_day matched');
2659         }
2660         else {
2661                 return IkiWiki::FailReason->new('creation_day did not match');
2662         }
2663 }
2664
2665 sub match_creation_month ($$;@) {
2666         my $page=shift;
2667         my $m=shift;
2668         if ($m !~ /^\d+$/) {
2669                 return IkiWiki::ErrorReason->new("invalid month $m");
2670         }
2671         if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2672                 return IkiWiki::SuccessReason->new('creation_month matched');
2673         }
2674         else {
2675                 return IkiWiki::FailReason->new('creation_month did not match');
2676         }
2677 }
2678
2679 sub match_creation_year ($$;@) {
2680         my $page=shift;
2681         my $y=shift;
2682         if ($y !~ /^\d+$/) {
2683                 return IkiWiki::ErrorReason->new("invalid year $y");
2684         }
2685         if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2686                 return IkiWiki::SuccessReason->new('creation_year matched');
2687         }
2688         else {
2689                 return IkiWiki::FailReason->new('creation_year did not match');
2690         }
2691 }
2692
2693 sub match_user ($$;@) {
2694         shift;
2695         my $user=shift;
2696         my %params=@_;
2697         
2698         my $regexp=IkiWiki::glob2re($user);
2699         
2700         if (! exists $params{user}) {
2701                 return IkiWiki::ErrorReason->new("no user specified");
2702         }
2703
2704         if (defined $params{user} && $params{user}=~$regexp) {
2705                 return IkiWiki::SuccessReason->new("user is $user");
2706         }
2707         elsif (! defined $params{user}) {
2708                 return IkiWiki::FailReason->new("not logged in");
2709         }
2710         else {
2711                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2712         }
2713 }
2714
2715 sub match_admin ($$;@) {
2716         shift;
2717         shift;
2718         my %params=@_;
2719         
2720         if (! exists $params{user}) {
2721                 return IkiWiki::ErrorReason->new("no user specified");
2722         }
2723
2724         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2725                 return IkiWiki::SuccessReason->new("user is an admin");
2726         }
2727         elsif (! defined $params{user}) {
2728                 return IkiWiki::FailReason->new("not logged in");
2729         }
2730         else {
2731                 return IkiWiki::FailReason->new("user is not an admin");
2732         }
2733 }
2734
2735 sub match_ip ($$;@) {
2736         shift;
2737         my $ip=shift;
2738         my %params=@_;
2739         
2740         if (! exists $params{ip}) {
2741                 return IkiWiki::ErrorReason->new("no IP specified");
2742         }
2743
2744         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2745                 return IkiWiki::SuccessReason->new("IP is $ip");
2746         }
2747         else {
2748                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2749         }
2750 }
2751
2752 package IkiWiki::SortSpec;
2753
2754 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2755 # are easily available in this namespace, for cmp functions to use them.
2756 sub sort_pages {
2757         my $f=shift;
2758         sort $f @_
2759 }
2760
2761 sub cmp_title {
2762         IkiWiki::pagetitle(IkiWiki::basename($a))
2763         cmp
2764         IkiWiki::pagetitle(IkiWiki::basename($b))
2765 }
2766
2767 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2768 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }
2769
2770 1