Merge remote branch 'upstream/master' into prv/po
[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 sub checkconfig () {
505         # locale stuff; avoid LC_ALL since it overrides everything
506         if (defined $ENV{LC_ALL}) {
507                 $ENV{LANG} = $ENV{LC_ALL};
508                 delete $ENV{LC_ALL};
509         }
510         if (defined $config{locale}) {
511                 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
512                         $ENV{LANG}=$config{locale};
513                         define_gettext();
514                 }
515         }
516                 
517         if (! defined $config{wiki_file_regexp}) {
518                 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
519         }
520
521         if (ref $config{ENV} eq 'HASH') {
522                 foreach my $val (keys %{$config{ENV}}) {
523                         $ENV{$val}=$config{ENV}{$val};
524                 }
525         }
526
527         if ($config{w3mmode}) {
528                 eval q{use Cwd q{abs_path}};
529                 error($@) if $@;
530                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
531                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
532                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
533                         unless $config{cgiurl} =~ m!file:///!;
534                 $config{url}="file://".$config{destdir};
535         }
536
537         if ($config{cgi} && ! length $config{url}) {
538                 error(gettext("Must specify url to wiki with --url when using --cgi"));
539         }
540         
541         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
542                 unless exists $config{wikistatedir} && defined $config{wikistatedir};
543
544         if (defined $config{umask}) {
545                 umask(possibly_foolish_untaint($config{umask}));
546         }
547
548         run_hooks(checkconfig => sub { shift->() });
549
550         return 1;
551 }
552
553 sub listplugins () {
554         my %ret;
555
556         foreach my $dir (@INC, $config{libdir}) {
557                 next unless defined $dir && length $dir;
558                 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
559                         my ($plugin)=$file=~/.*\/(.*)\.pm$/;
560                         $ret{$plugin}=1;
561                 }
562         }
563         foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
564                 next unless defined $dir && length $dir;
565                 foreach my $file (glob("$dir/plugins/*")) {
566                         $ret{basename($file)}=1 if -x $file;
567                 }
568         }
569
570         return keys %ret;
571 }
572
573 sub loadplugins () {
574         if (defined $config{libdir} && length $config{libdir}) {
575                 unshift @INC, possibly_foolish_untaint($config{libdir});
576         }
577
578         foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
579                 loadplugin($plugin);
580         }
581         
582         if ($config{rcs}) {
583                 if (exists $hooks{rcs}) {
584                         error(gettext("cannot use multiple rcs plugins"));
585                 }
586                 loadplugin($config{rcs});
587         }
588         if (! exists $hooks{rcs}) {
589                 loadplugin("norcs");
590         }
591
592         run_hooks(getopt => sub { shift->() });
593         if (grep /^-/, @ARGV) {
594                 print STDERR "Unknown option (or missing parameter): $_\n"
595                         foreach grep /^-/, @ARGV;
596                 usage();
597         }
598
599         return 1;
600 }
601
602 sub loadplugin ($;$) {
603         my $plugin=shift;
604         my $force=shift;
605
606         return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
607
608         foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
609                          "$installdir/lib/ikiwiki") {
610                 if (defined $dir && -x "$dir/plugins/$plugin") {
611                         eval { require IkiWiki::Plugin::external };
612                         if ($@) {
613                                 my $reason=$@;
614                                 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
615                         }
616                         import IkiWiki::Plugin::external "$dir/plugins/$plugin";
617                         $loaded_plugins{$plugin}=1;
618                         return 1;
619                 }
620         }
621
622         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
623         eval qq{use $mod};
624         if ($@) {
625                 error("Failed to load plugin $mod: $@");
626         }
627         $loaded_plugins{$plugin}=1;
628         return 1;
629 }
630
631 sub error ($;$) {
632         my $message=shift;
633         my $cleaner=shift;
634         log_message('err' => $message) if $config{syslog};
635         if (defined $cleaner) {
636                 $cleaner->();
637         }
638         die $message."\n";
639 }
640
641 sub debug ($) {
642         return unless $config{verbose};
643         return log_message(debug => @_);
644 }
645
646 my $log_open=0;
647 sub log_message ($$) {
648         my $type=shift;
649
650         if ($config{syslog}) {
651                 require Sys::Syslog;
652                 if (! $log_open) {
653                         Sys::Syslog::setlogsock('unix');
654                         Sys::Syslog::openlog('ikiwiki', '', 'user');
655                         $log_open=1;
656                 }
657                 return eval {
658                         Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
659                 };
660         }
661         elsif (! $config{cgi}) {
662                 return print "@_\n";
663         }
664         else {
665                 return print STDERR "@_\n";
666         }
667 }
668
669 sub possibly_foolish_untaint ($) {
670         my $tainted=shift;
671         my ($untainted)=$tainted=~/(.*)/s;
672         return $untainted;
673 }
674
675 sub basename ($) {
676         my $file=shift;
677
678         $file=~s!.*/+!!;
679         return $file;
680 }
681
682 sub dirname ($) {
683         my $file=shift;
684
685         $file=~s!/*[^/]+$!!;
686         return $file;
687 }
688
689 sub isinternal ($) {
690         my $page=shift;
691         return exists $pagesources{$page} &&
692                 $pagesources{$page} =~ /\._([^.]+)$/;
693 }
694
695 sub pagetype ($) {
696         my $file=shift;
697         
698         if ($file =~ /\.([^.]+)$/) {
699                 return $1 if exists $hooks{htmlize}{$1};
700         }
701         my $base=basename($file);
702         if (exists $hooks{htmlize}{$base} &&
703             $hooks{htmlize}{$base}{noextension}) {
704                 return $base;
705         }
706         return;
707 }
708
709 my %pagename_cache;
710
711 sub pagename ($) {
712         my $file=shift;
713
714         if (exists $pagename_cache{$file}) {
715                 return $pagename_cache{$file};
716         }
717
718         my $type=pagetype($file);
719         my $page=$file;
720         $page=~s/\Q.$type\E*$//
721                 if defined $type && !$hooks{htmlize}{$type}{keepextension}
722                         && !$hooks{htmlize}{$type}{noextension};
723         if ($config{indexpages} && $page=~/(.*)\/index$/) {
724                 $page=$1;
725         }
726
727         $pagename_cache{$file} = $page;
728         return $page;
729 }
730
731 sub newpagefile ($$) {
732         my $page=shift;
733         my $type=shift;
734
735         if (! $config{indexpages} || $page eq 'index') {
736                 return $page.".".$type;
737         }
738         else {
739                 return $page."/index.".$type;
740         }
741 }
742
743 sub targetpage ($$;$) {
744         my $page=shift;
745         my $ext=shift;
746         my $filename=shift;
747         
748         if (defined $filename) {
749                 return $page."/".$filename.".".$ext;
750         }
751         elsif (! $config{usedirs} || $page eq 'index') {
752                 return $page.".".$ext;
753         }
754         else {
755                 return $page."/index.".$ext;
756         }
757 }
758
759 sub htmlpage ($) {
760         my $page=shift;
761         
762         return targetpage($page, $config{htmlext});
763 }
764
765 sub srcfile_stat {
766         my $file=shift;
767         my $nothrow=shift;
768
769         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
770         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
771                 return "$dir/$file", stat(_) if -e "$dir/$file";
772         }
773         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
774         return;
775 }
776
777 sub srcfile ($;$) {
778         return (srcfile_stat(@_))[0];
779 }
780
781 sub add_underlay ($) {
782         my $dir=shift;
783
784         if ($dir !~ /^\//) {
785                 $dir="$config{underlaydirbase}/$dir";
786         }
787
788         if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
789                 unshift @{$config{underlaydirs}}, $dir;
790         }
791
792         return 1;
793 }
794
795 sub readfile ($;$$) {
796         my $file=shift;
797         my $binary=shift;
798         my $wantfd=shift;
799
800         if (-l $file) {
801                 error("cannot read a symlink ($file)");
802         }
803         
804         local $/=undef;
805         open (my $in, "<", $file) || error("failed to read $file: $!");
806         binmode($in) if ($binary);
807         return \*$in if $wantfd;
808         my $ret=<$in>;
809         # check for invalid utf-8, and toss it back to avoid crashes
810         if (! utf8::valid($ret)) {
811                 $ret=encode_utf8($ret);
812         }
813         close $in || error("failed to read $file: $!");
814         return $ret;
815 }
816
817 sub prep_writefile ($$) {
818         my $file=shift;
819         my $destdir=shift;
820         
821         my $test=$file;
822         while (length $test) {
823                 if (-l "$destdir/$test") {
824                         error("cannot write to a symlink ($test)");
825                 }
826                 $test=dirname($test);
827         }
828
829         my $dir=dirname("$destdir/$file");
830         if (! -d $dir) {
831                 my $d="";
832                 foreach my $s (split(m!/+!, $dir)) {
833                         $d.="$s/";
834                         if (! -d $d) {
835                                 mkdir($d) || error("failed to create directory $d: $!");
836                         }
837                 }
838         }
839
840         return 1;
841 }
842
843 sub writefile ($$$;$$) {
844         my $file=shift; # can include subdirs
845         my $destdir=shift; # directory to put file in
846         my $content=shift;
847         my $binary=shift;
848         my $writer=shift;
849         
850         prep_writefile($file, $destdir);
851         
852         my $newfile="$destdir/$file.ikiwiki-new";
853         if (-l $newfile) {
854                 error("cannot write to a symlink ($newfile)");
855         }
856         
857         my $cleanup = sub { unlink($newfile) };
858         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
859         binmode($out) if ($binary);
860         if ($writer) {
861                 $writer->(\*$out, $cleanup);
862         }
863         else {
864                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
865         }
866         close $out || error("failed saving $newfile: $!", $cleanup);
867         rename($newfile, "$destdir/$file") || 
868                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
869
870         return 1;
871 }
872
873 my %cleared;
874 sub will_render ($$;$) {
875         my $page=shift;
876         my $dest=shift;
877         my $clear=shift;
878
879         # Important security check.
880         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
881             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
882                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
883         }
884
885         if (! $clear || $cleared{$page}) {
886                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
887         }
888         else {
889                 foreach my $old (@{$renderedfiles{$page}}) {
890                         delete $destsources{$old};
891                 }
892                 $renderedfiles{$page}=[$dest];
893                 $cleared{$page}=1;
894         }
895         $destsources{$dest}=$page;
896
897         return 1;
898 }
899
900 sub bestlink ($$) {
901         my $page=shift;
902         my $link=shift;
903         
904         my $cwd=$page;
905         if ($link=~s/^\/+//) {
906                 # absolute links
907                 $cwd="";
908         }
909         $link=~s/\/$//;
910
911         do {
912                 my $l=$cwd;
913                 $l.="/" if length $l;
914                 $l.=$link;
915
916                 if (exists $pagesources{$l}) {
917                         return $l;
918                 }
919                 elsif (exists $pagecase{lc $l}) {
920                         return $pagecase{lc $l};
921                 }
922         } while $cwd=~s{/?[^/]+$}{};
923
924         if (length $config{userdir}) {
925                 my $l = "$config{userdir}/".lc($link);
926                 if (exists $pagesources{$l}) {
927                         return $l;
928                 }
929                 elsif (exists $pagecase{lc $l}) {
930                         return $pagecase{lc $l};
931                 }
932         }
933
934         #print STDERR "warning: page $page, broken link: $link\n";
935         return "";
936 }
937
938 sub isinlinableimage ($) {
939         my $file=shift;
940         
941         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
942 }
943
944 sub pagetitle ($;$) {
945         my $page=shift;
946         my $unescaped=shift;
947
948         if ($unescaped) {
949                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
950         }
951         else {
952                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
953         }
954
955         return $page;
956 }
957
958 sub titlepage ($) {
959         my $title=shift;
960         # support use w/o %config set
961         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
962         $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
963         return $title;
964 }
965
966 sub linkpage ($) {
967         my $link=shift;
968         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
969         $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
970         return $link;
971 }
972
973 sub cgiurl (@) {
974         my %params=@_;
975
976         my $cgiurl=$config{cgiurl};
977         if (exists $params{cgiurl}) {
978                 $cgiurl=$params{cgiurl};
979                 delete $params{cgiurl};
980         }
981         return $cgiurl."?".
982                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
983 }
984
985 sub baseurl (;$) {
986         my $page=shift;
987
988         return "$config{url}/" if ! defined $page;
989         
990         $page=htmlpage($page);
991         $page=~s/[^\/]+$//;
992         $page=~s/[^\/]+\//..\//g;
993         return $page;
994 }
995
996 sub abs2rel ($$) {
997         # Work around very innefficient behavior in File::Spec if abs2rel
998         # is passed two relative paths. It's much faster if paths are
999         # absolute! (Debian bug #376658; fixed in debian unstable now)
1000         my $path="/".shift;
1001         my $base="/".shift;
1002
1003         require File::Spec;
1004         my $ret=File::Spec->abs2rel($path, $base);
1005         $ret=~s/^// if defined $ret;
1006         return $ret;
1007 }
1008
1009 sub displaytime ($;$$) {
1010         # Plugins can override this function to mark up the time to
1011         # display.
1012         my $time=formattime($_[0], $_[1]);
1013         if ($config{html5}) {
1014                 return '<time datetime="'.date_3339($_[0]).'"'.
1015                         ($_[2] ? ' pubdate="pubdate"' : '').
1016                         '>'.$time.'</time>';
1017         }
1018         else {
1019                 return '<span class="date">'.$time.'</span>';
1020         }
1021 }
1022
1023 sub formattime ($;$) {
1024         # Plugins can override this function to format the time.
1025         my $time=shift;
1026         my $format=shift;
1027         if (! defined $format) {
1028                 $format=$config{timeformat};
1029         }
1030
1031         # strftime doesn't know about encodings, so make sure
1032         # its output is properly treated as utf8
1033         return decode_utf8(POSIX::strftime($format, localtime($time)));
1034 }
1035
1036 sub date_3339 ($) {
1037         my $time=shift;
1038
1039         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1040         POSIX::setlocale(&POSIX::LC_TIME, "C");
1041         my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1042         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1043         return $ret;
1044 }
1045
1046 sub beautify_urlpath ($) {
1047         my $url=shift;
1048
1049         # Ensure url is not an empty link, and if necessary,
1050         # add ./ to avoid colon confusion.
1051         if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1052                 $url="./$url";
1053         }
1054
1055         if ($config{usedirs}) {
1056                 $url =~ s!/index.$config{htmlext}$!/!;
1057         }
1058
1059         return $url;
1060 }
1061
1062 sub urlto ($$;$) {
1063         my $to=shift;
1064         my $from=shift;
1065         my $absolute=shift;
1066         
1067         if (! length $to) {
1068                 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1069         }
1070
1071         if (! $destsources{$to}) {
1072                 $to=htmlpage($to);
1073         }
1074
1075         if ($absolute) {
1076                 return $config{url}.beautify_urlpath("/".$to);
1077         }
1078
1079         my $link = abs2rel($to, dirname(htmlpage($from)));
1080
1081         return beautify_urlpath($link);
1082 }
1083
1084 sub isselflink ($$) {
1085         my $page=shift;
1086         my $link=shift;
1087
1088         return $page eq $link;
1089 }
1090
1091 sub htmllink ($$$;@) {
1092         my $lpage=shift; # the page doing the linking
1093         my $page=shift; # the page that will contain the link (different for inline)
1094         my $link=shift;
1095         my %opts=@_;
1096
1097         $link=~s/\/$//;
1098
1099         my $bestlink;
1100         if (! $opts{forcesubpage}) {
1101                 $bestlink=bestlink($lpage, $link);
1102         }
1103         else {
1104                 $bestlink="$lpage/".lc($link);
1105         }
1106
1107         my $linktext;
1108         if (defined $opts{linktext}) {
1109                 $linktext=$opts{linktext};
1110         }
1111         else {
1112                 $linktext=pagetitle(basename($link));
1113         }
1114         
1115         return "<span class=\"selflink\">$linktext</span>"
1116                 if length $bestlink && isselflink($page, $bestlink) &&
1117                    ! defined $opts{anchor};
1118         
1119         if (! $destsources{$bestlink}) {
1120                 $bestlink=htmlpage($bestlink);
1121
1122                 if (! $destsources{$bestlink}) {
1123                         my $cgilink = "";
1124                         if (length $config{cgiurl}) {
1125                                 $cgilink = "<a href=\"".
1126                                         cgiurl(
1127                                                 do => "create",
1128                                                 page => lc($link),
1129                                                 from => $lpage
1130                                         )."\" rel=\"nofollow\">?</a>";
1131                         }
1132                         return "<span class=\"createlink\">$cgilink$linktext</span>"
1133                 }
1134         }
1135         
1136         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1137         $bestlink=beautify_urlpath($bestlink);
1138         
1139         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1140                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1141         }
1142
1143         if (defined $opts{anchor}) {
1144                 $bestlink.="#".$opts{anchor};
1145         }
1146
1147         my @attrs;
1148         foreach my $attr (qw{rel class title}) {
1149                 if (defined $opts{$attr}) {
1150                         push @attrs, " $attr=\"$opts{$attr}\"";
1151                 }
1152         }
1153
1154         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1155 }
1156
1157 sub userpage ($) {
1158         my $user=shift;
1159         return length $config{userdir} ? "$config{userdir}/$user" : $user;
1160 }
1161
1162 sub openiduser ($) {
1163         my $user=shift;
1164
1165         if ($user =~ m!^https?://! &&
1166             eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1167                 my $display;
1168
1169                 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1170                         $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1171                 }
1172                 else {
1173                         # backcompat with old version
1174                         my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1175                         $display=$oid->display;
1176                 }
1177
1178                 # Convert "user.somehost.com" to "user [somehost.com]"
1179                 # (also "user.somehost.co.uk")
1180                 if ($display !~ /\[/) {
1181                         $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1182                 }
1183                 # Convert "http://somehost.com/user" to "user [somehost.com]".
1184                 # (also "https://somehost.com/user/")
1185                 if ($display !~ /\[/) {
1186                         $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1187                 }
1188                 $display=~s!^https?://!!; # make sure this is removed
1189                 eval q{use CGI 'escapeHTML'};
1190                 error($@) if $@;
1191                 return escapeHTML($display);
1192         }
1193         return;
1194 }
1195
1196 sub htmlize ($$$$) {
1197         my $page=shift;
1198         my $destpage=shift;
1199         my $type=shift;
1200         my $content=shift;
1201         
1202         my $oneline = $content !~ /\n/;
1203         
1204         if (exists $hooks{htmlize}{$type}) {
1205                 $content=$hooks{htmlize}{$type}{call}->(
1206                         page => $page,
1207                         content => $content,
1208                 );
1209         }
1210         else {
1211                 error("htmlization of $type not supported");
1212         }
1213
1214         run_hooks(sanitize => sub {
1215                 $content=shift->(
1216                         page => $page,
1217                         destpage => $destpage,
1218                         content => $content,
1219                 );
1220         });
1221         
1222         if ($oneline) {
1223                 # hack to get rid of enclosing junk added by markdown
1224                 # and other htmlizers/sanitizers
1225                 $content=~s/^<p>//i;
1226                 $content=~s/<\/p>\n*$//i;
1227         }
1228
1229         return $content;
1230 }
1231
1232 sub linkify ($$$) {
1233         my $page=shift;
1234         my $destpage=shift;
1235         my $content=shift;
1236
1237         run_hooks(linkify => sub {
1238                 $content=shift->(
1239                         page => $page,
1240                         destpage => $destpage,
1241                         content => $content,
1242                 );
1243         });
1244         
1245         return $content;
1246 }
1247
1248 our %preprocessing;
1249 our $preprocess_preview=0;
1250 sub preprocess ($$$;$$) {
1251         my $page=shift; # the page the data comes from
1252         my $destpage=shift; # the page the data will appear in (different for inline)
1253         my $content=shift;
1254         my $scan=shift;
1255         my $preview=shift;
1256
1257         # Using local because it needs to be set within any nested calls
1258         # of this function.
1259         local $preprocess_preview=$preview if defined $preview;
1260
1261         my $handle=sub {
1262                 my $escape=shift;
1263                 my $prefix=shift;
1264                 my $command=shift;
1265                 my $params=shift;
1266                 $params="" if ! defined $params;
1267
1268                 if (length $escape) {
1269                         return "[[$prefix$command $params]]";
1270                 }
1271                 elsif (exists $hooks{preprocess}{$command}) {
1272                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1273                         # Note: preserve order of params, some plugins may
1274                         # consider it significant.
1275                         my @params;
1276                         while ($params =~ m{
1277                                 (?:([-\w]+)=)?          # 1: named parameter key?
1278                                 (?:
1279                                         """(.*?)"""     # 2: triple-quoted value
1280                                 |
1281                                         "([^"]*?)"      # 3: single-quoted value
1282                                 |
1283                                         (\S+)           # 4: unquoted value
1284                                 )
1285                                 (?:\s+|$)               # delimiter to next param
1286                         }sgx) {
1287                                 my $key=$1;
1288                                 my $val;
1289                                 if (defined $2) {
1290                                         $val=$2;
1291                                         $val=~s/\r\n/\n/mg;
1292                                         $val=~s/^\n+//g;
1293                                         $val=~s/\n+$//g;
1294                                 }
1295                                 elsif (defined $3) {
1296                                         $val=$3;
1297                                 }
1298                                 elsif (defined $4) {
1299                                         $val=$4;
1300                                 }
1301
1302                                 if (defined $key) {
1303                                         push @params, $key, $val;
1304                                 }
1305                                 else {
1306                                         push @params, $val, '';
1307                                 }
1308                         }
1309                         if ($preprocessing{$page}++ > 3) {
1310                                 # Avoid loops of preprocessed pages preprocessing
1311                                 # other pages that preprocess them, etc.
1312                                 return "[[!$command <span class=\"error\">".
1313                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1314                                                 $page, $preprocessing{$page}).
1315                                         "</span>]]";
1316                         }
1317                         my $ret;
1318                         if (! $scan) {
1319                                 $ret=eval {
1320                                         $hooks{preprocess}{$command}{call}->(
1321                                                 @params,
1322                                                 page => $page,
1323                                                 destpage => $destpage,
1324                                                 preview => $preprocess_preview,
1325                                         );
1326                                 };
1327                                 if ($@) {
1328                                         my $error=$@;
1329                                         chomp $error;
1330                                         $ret="[[!$command <span class=\"error\">".
1331                                                 gettext("Error").": $error"."</span>]]";
1332                                 }
1333                         }
1334                         else {
1335                                 # use void context during scan pass
1336                                 eval {
1337                                         $hooks{preprocess}{$command}{call}->(
1338                                                 @params,
1339                                                 page => $page,
1340                                                 destpage => $destpage,
1341                                                 preview => $preprocess_preview,
1342                                         );
1343                                 };
1344                                 $ret="";
1345                         }
1346                         $preprocessing{$page}--;
1347                         return $ret;
1348                 }
1349                 else {
1350                         return "[[$prefix$command $params]]";
1351                 }
1352         };
1353         
1354         my $regex;
1355         if ($config{prefix_directives}) {
1356                 $regex = qr{
1357                         (\\?)           # 1: escape?
1358                         \[\[(!)         # directive open; 2: prefix
1359                         ([-\w]+)        # 3: command
1360                         (               # 4: the parameters..
1361                                 \s+     # Must have space if parameters present
1362                                 (?:
1363                                         (?:[-\w]+=)?            # named parameter key?
1364                                         (?:
1365                                                 """.*?"""       # triple-quoted value
1366                                                 |
1367                                                 "[^"]*?"        # single-quoted value
1368                                                 |
1369                                                 [^"\s\]]+       # unquoted value
1370                                         )
1371                                         \s*                     # whitespace or end
1372                                                                 # of directive
1373                                 )
1374                         *)?             # 0 or more parameters
1375                         \]\]            # directive closed
1376                 }sx;
1377         }
1378         else {
1379                 $regex = qr{
1380                         (\\?)           # 1: escape?
1381                         \[\[(!?)        # directive open; 2: optional prefix
1382                         ([-\w]+)        # 3: command
1383                         \s+
1384                         (               # 4: the parameters..
1385                                 (?:
1386                                         (?:[-\w]+=)?            # named parameter key?
1387                                         (?:
1388                                                 """.*?"""       # triple-quoted value
1389                                                 |
1390                                                 "[^"]*?"        # single-quoted value
1391                                                 |
1392                                                 [^"\s\]]+       # unquoted value
1393                                         )
1394                                         \s*                     # whitespace or end
1395                                                                 # of directive
1396                                 )
1397                         *)              # 0 or more parameters
1398                         \]\]            # directive closed
1399                 }sx;
1400         }
1401
1402         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1403         return $content;
1404 }
1405
1406 sub filter ($$$;$) {
1407         my $page=shift;
1408         my $destpage=shift;
1409         my $content=shift;
1410         my $fullpage=shift;
1411         $fullpage = 0 unless defined $fullpage;
1412
1413         run_hooks(filter => sub {
1414                 $content=shift->(page => $page, destpage => $destpage, 
1415                         content => $content, fullpage => $fullpage);
1416         });
1417
1418         return $content;
1419 }
1420
1421 sub check_canedit ($$$;$) {
1422         my $page=shift;
1423         my $q=shift;
1424         my $session=shift;
1425         my $nonfatal=shift;
1426         
1427         my $canedit;
1428         run_hooks(canedit => sub {
1429                 return if defined $canedit;
1430                 my $ret=shift->($page, $q, $session);
1431                 if (defined $ret) {
1432                         if ($ret eq "") {
1433                                 $canedit=1;
1434                         }
1435                         elsif (ref $ret eq 'CODE') {
1436                                 $ret->() unless $nonfatal;
1437                                 $canedit=0;
1438                         }
1439                         elsif (defined $ret) {
1440                                 error($ret) unless $nonfatal;
1441                                 $canedit=0;
1442                         }
1443                 }
1444         });
1445         return defined $canedit ? $canedit : 1;
1446 }
1447
1448 sub check_content (@) {
1449         my %params=@_;
1450         
1451         return 1 if ! exists $hooks{checkcontent}; # optimisation
1452
1453         if (exists $pagesources{$params{page}}) {
1454                 my @diff;
1455                 my %old=map { $_ => 1 }
1456                         split("\n", readfile(srcfile($pagesources{$params{page}})));
1457                 foreach my $line (split("\n", $params{content})) {
1458                         push @diff, $line if ! exists $old{$line};
1459                 }
1460                 $params{diff}=join("\n", @diff);
1461         }
1462
1463         my $ok;
1464         run_hooks(checkcontent => sub {
1465                 return if defined $ok;
1466                 my $ret=shift->(%params);
1467                 if (defined $ret) {
1468                         if ($ret eq "") {
1469                                 $ok=1;
1470                         }
1471                         elsif (ref $ret eq 'CODE') {
1472                                 $ret->() unless $params{nonfatal};
1473                                 $ok=0;
1474                         }
1475                         elsif (defined $ret) {
1476                                 error($ret) unless $params{nonfatal};
1477                                 $ok=0;
1478                         }
1479                 }
1480
1481         });
1482         return defined $ok ? $ok : 1;
1483 }
1484
1485 my $wikilock;
1486
1487 sub lockwiki () {
1488         # Take an exclusive lock on the wiki to prevent multiple concurrent
1489         # run issues. The lock will be dropped on program exit.
1490         if (! -d $config{wikistatedir}) {
1491                 mkdir($config{wikistatedir});
1492         }
1493         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1494                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1495         if (! flock($wikilock, 2)) { # LOCK_EX
1496                 error("failed to get lock");
1497         }
1498         return 1;
1499 }
1500
1501 sub unlockwiki () {
1502         POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1503         return close($wikilock) if $wikilock;
1504         return;
1505 }
1506
1507 my $commitlock;
1508
1509 sub commit_hook_enabled () {
1510         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1511                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1512         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1513                 close($commitlock) || error("failed closing commitlock: $!");
1514                 return 0;
1515         }
1516         close($commitlock) || error("failed closing commitlock: $!");
1517         return 1;
1518 }
1519
1520 sub disable_commit_hook () {
1521         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1522                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1523         if (! flock($commitlock, 2)) { # LOCK_EX
1524                 error("failed to get commit lock");
1525         }
1526         return 1;
1527 }
1528
1529 sub enable_commit_hook () {
1530         return close($commitlock) if $commitlock;
1531         return;
1532 }
1533
1534 sub loadindex () {
1535         %oldrenderedfiles=%pagectime=();
1536         if (! $config{rebuild}) {
1537                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1538                 %destsources=%renderedfiles=%pagecase=%pagestate=
1539                 %depends_simple=%typedlinks=%oldtypedlinks=();
1540         }
1541         my $in;
1542         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1543                 if (-e "$config{wikistatedir}/index") {
1544                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1545                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1546                 }
1547                 else {
1548                         $config{gettime}=1; # first build
1549                         return;
1550                 }
1551         }
1552
1553         my $index=Storable::fd_retrieve($in);
1554         if (! defined $index) {
1555                 return 0;
1556         }
1557
1558         my $pages;
1559         if (exists $index->{version} && ! ref $index->{version}) {
1560                 $pages=$index->{page};
1561                 %wikistate=%{$index->{state}};
1562         }
1563         else {
1564                 $pages=$index;
1565                 %wikistate=();
1566         }
1567
1568         foreach my $src (keys %$pages) {
1569                 my $d=$pages->{$src};
1570                 my $page=pagename($src);
1571                 $pagectime{$page}=$d->{ctime};
1572                 $pagesources{$page}=$src;
1573                 if (! $config{rebuild}) {
1574                         $pagemtime{$page}=$d->{mtime};
1575                         $renderedfiles{$page}=$d->{dest};
1576                         if (exists $d->{links} && ref $d->{links}) {
1577                                 $links{$page}=$d->{links};
1578                                 $oldlinks{$page}=[@{$d->{links}}];
1579                         }
1580                         if (ref $d->{depends_simple} eq 'ARRAY') {
1581                                 # old format
1582                                 $depends_simple{$page}={
1583                                         map { $_ => 1 } @{$d->{depends_simple}}
1584                                 };
1585                         }
1586                         elsif (exists $d->{depends_simple}) {
1587                                 $depends_simple{$page}=$d->{depends_simple};
1588                         }
1589                         if (exists $d->{dependslist}) {
1590                                 # old format
1591                                 $depends{$page}={
1592                                         map { $_ => $DEPEND_CONTENT }
1593                                                 @{$d->{dependslist}}
1594                                 };
1595                         }
1596                         elsif (exists $d->{depends} && ! ref $d->{depends}) {
1597                                 # old format
1598                                 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1599                         }
1600                         elsif (exists $d->{depends}) {
1601                                 $depends{$page}=$d->{depends};
1602                         }
1603                         if (exists $d->{state}) {
1604                                 $pagestate{$page}=$d->{state};
1605                         }
1606                         if (exists $d->{typedlinks}) {
1607                                 $typedlinks{$page}=$d->{typedlinks};
1608
1609                                 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1610                                         next unless %$links;
1611                                         $oldtypedlinks{$page}{$type} = {%$links};
1612                                 }
1613                         }
1614                 }
1615                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1616         }
1617         foreach my $page (keys %pagesources) {
1618                 $pagecase{lc $page}=$page;
1619         }
1620         foreach my $page (keys %renderedfiles) {
1621                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1622         }
1623         return close($in);
1624 }
1625
1626 sub saveindex () {
1627         run_hooks(savestate => sub { shift->() });
1628
1629         my %hookids;
1630         foreach my $type (keys %hooks) {
1631                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1632         }
1633         my @hookids=keys %hookids;
1634
1635         if (! -d $config{wikistatedir}) {
1636                 mkdir($config{wikistatedir});
1637         }
1638         my $newfile="$config{wikistatedir}/indexdb.new";
1639         my $cleanup = sub { unlink($newfile) };
1640         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1641
1642         my %index;
1643         foreach my $page (keys %pagemtime) {
1644                 next unless $pagemtime{$page};
1645                 my $src=$pagesources{$page};
1646
1647                 $index{page}{$src}={
1648                         ctime => $pagectime{$page},
1649                         mtime => $pagemtime{$page},
1650                         dest => $renderedfiles{$page},
1651                         links => $links{$page},
1652                 };
1653
1654                 if (exists $depends{$page}) {
1655                         $index{page}{$src}{depends} = $depends{$page};
1656                 }
1657
1658                 if (exists $depends_simple{$page}) {
1659                         $index{page}{$src}{depends_simple} = $depends_simple{$page};
1660                 }
1661
1662                 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1663                         $index{page}{$src}{typedlinks} = $typedlinks{$page};
1664                 }
1665
1666                 if (exists $pagestate{$page}) {
1667                         foreach my $id (@hookids) {
1668                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1669                                         $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1670                                 }
1671                         }
1672                 }
1673         }
1674
1675         $index{state}={};
1676         foreach my $id (@hookids) {
1677                 foreach my $key (keys %{$wikistate{$id}}) {
1678                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
1679                 }
1680         }
1681         
1682         $index{version}="3";
1683         my $ret=Storable::nstore_fd(\%index, $out);
1684         return if ! defined $ret || ! $ret;
1685         close $out || error("failed saving to $newfile: $!", $cleanup);
1686         rename($newfile, "$config{wikistatedir}/indexdb") ||
1687                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1688         
1689         return 1;
1690 }
1691
1692 sub template_file ($) {
1693         my $name=shift;
1694         
1695         my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1696         if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1697                 $tpage=$pagesources{$tpage};
1698                 $name.=".tmpl";
1699         }
1700
1701         my $template=srcfile($tpage, 1);
1702         if (defined $template) {
1703                 return $template, $tpage, 1 if wantarray;
1704                 return $template;
1705         }
1706         else {
1707                 $name=~s:/::; # avoid path traversal
1708                 foreach my $dir ($config{templatedir},
1709                                  "$installdir/share/ikiwiki/templates") {
1710                         if (-e "$dir/$name") {
1711                                 $template="$dir/$name";
1712                                 last;
1713                         }
1714                 }
1715                 if (defined $template) {        
1716                         return $template, $tpage if wantarray;
1717                         return $template;
1718                 }
1719         }
1720
1721         return;
1722 }
1723
1724 sub template_depends ($$;@) {
1725         my $name=shift;
1726         my $page=shift;
1727         
1728         my ($filename, $tpage, $untrusted)=template_file($name);
1729         if (defined $page && defined $tpage) {
1730                 add_depends($page, $tpage);
1731         }
1732
1733         return unless defined $filename;
1734
1735         my @opts=(
1736                 filter => sub {
1737                         my $text_ref = shift;
1738                         ${$text_ref} = decode_utf8(${$text_ref});
1739                 },
1740                 loop_context_vars => 1,
1741                 die_on_bad_params => 0,
1742                 filename => $filename,
1743                 @_,
1744                 ($untrusted ? (no_includes => 1) : ()),
1745         );
1746         return @opts if wantarray;
1747
1748         require HTML::Template;
1749         return HTML::Template->new(@opts);
1750 }
1751
1752 sub template ($;@) {
1753         template_depends(shift, undef, @_);
1754 }
1755
1756 sub misctemplate ($$;@) {
1757         my $title=shift;
1758         my $content=shift;
1759         my %params=@_;
1760         
1761         my $template=template("page.tmpl");
1762
1763         my $page="";
1764         if (exists $params{page}) {
1765                 $page=delete $params{page};
1766         }
1767         run_hooks(pagetemplate => sub {
1768                 shift->(
1769                         page => $page,
1770                         destpage => $page,
1771                         template => $template,
1772                 );
1773         });
1774         templateactions($template, "");
1775
1776         $template->param(
1777                 dynamic => 1,
1778                 title => $title,
1779                 wikiname => $config{wikiname},
1780                 content => $content,
1781                 baseurl => baseurl(),
1782                 html5 => $config{html5},
1783                 %params,
1784         );
1785         
1786         return $template->output;
1787 }
1788
1789 sub templateactions ($$) {
1790         my $template=shift;
1791         my $page=shift;
1792
1793         my $have_actions=0;
1794         my @actions;
1795         run_hooks(pageactions => sub {
1796                 push @actions, map { { action => $_ } } 
1797                         grep { defined } shift->(page => $page);
1798         });
1799         $template->param(actions => \@actions);
1800
1801         if ($config{cgiurl} && exists $hooks{auth}) {
1802                 $template->param(prefsurl => cgiurl(do => "prefs"));
1803                 $have_actions=1;
1804         }
1805
1806         if ($have_actions || @actions) {
1807                 $template->param(have_actions => 1);
1808         }
1809 }
1810
1811 sub hook (@) {
1812         my %param=@_;
1813         
1814         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1815                 error 'hook requires type, call, and id parameters';
1816         }
1817
1818         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1819         
1820         $hooks{$param{type}}{$param{id}}=\%param;
1821         return 1;
1822 }
1823
1824 sub run_hooks ($$) {
1825         # Calls the given sub for each hook of the given type,
1826         # passing it the hook function to call.
1827         my $type=shift;
1828         my $sub=shift;
1829
1830         if (exists $hooks{$type}) {
1831                 my (@first, @middle, @last);
1832                 foreach my $id (keys %{$hooks{$type}}) {
1833                         if ($hooks{$type}{$id}{first}) {
1834                                 push @first, $id;
1835                         }
1836                         elsif ($hooks{$type}{$id}{last}) {
1837                                 push @last, $id;
1838                         }
1839                         else {
1840                                 push @middle, $id;
1841                         }
1842                 }
1843                 foreach my $id (@first, @middle, @last) {
1844                         $sub->($hooks{$type}{$id}{call});
1845                 }
1846         }
1847
1848         return 1;
1849 }
1850
1851 sub rcs_update () {
1852         $hooks{rcs}{rcs_update}{call}->(@_);
1853 }
1854
1855 sub rcs_prepedit ($) {
1856         $hooks{rcs}{rcs_prepedit}{call}->(@_);
1857 }
1858
1859 sub rcs_commit (@) {
1860         $hooks{rcs}{rcs_commit}{call}->(@_);
1861 }
1862
1863 sub rcs_commit_staged (@) {
1864         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1865 }
1866
1867 sub rcs_add ($) {
1868         $hooks{rcs}{rcs_add}{call}->(@_);
1869 }
1870
1871 sub rcs_remove ($) {
1872         $hooks{rcs}{rcs_remove}{call}->(@_);
1873 }
1874
1875 sub rcs_rename ($$) {
1876         $hooks{rcs}{rcs_rename}{call}->(@_);
1877 }
1878
1879 sub rcs_recentchanges ($) {
1880         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1881 }
1882
1883 sub rcs_diff ($) {
1884         $hooks{rcs}{rcs_diff}{call}->(@_);
1885 }
1886
1887 sub rcs_getctime ($) {
1888         $hooks{rcs}{rcs_getctime}{call}->(@_);
1889 }
1890
1891 sub rcs_getmtime ($) {
1892         $hooks{rcs}{rcs_getmtime}{call}->(@_);
1893 }
1894
1895 sub rcs_receive () {
1896         $hooks{rcs}{rcs_receive}{call}->();
1897 }
1898
1899 sub add_depends ($$;$) {
1900         my $page=shift;
1901         my $pagespec=shift;
1902         my $deptype=shift || $DEPEND_CONTENT;
1903
1904         # Is the pagespec a simple page name?
1905         if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1906             $pagespec !~ /[\s*?()!]/) {
1907                 $depends_simple{$page}{lc $pagespec} |= $deptype;
1908                 return 1;
1909         }
1910
1911         # Add explicit dependencies for influences.
1912         my $sub=pagespec_translate($pagespec);
1913         return unless defined $sub;
1914         foreach my $p (keys %pagesources) {
1915                 my $r=$sub->($p, location => $page);
1916                 my $i=$r->influences;
1917                 my $static=$r->influences_static;
1918                 foreach my $k (keys %$i) {
1919                         next unless $r || $static || $k eq $page;
1920                         $depends_simple{$page}{lc $k} |= $i->{$k};
1921                 }
1922                 last if $static;
1923         }
1924
1925         $depends{$page}{$pagespec} |= $deptype;
1926         return 1;
1927 }
1928
1929 sub deptype (@) {
1930         my $deptype=0;
1931         foreach my $type (@_) {
1932                 if ($type eq 'presence') {
1933                         $deptype |= $DEPEND_PRESENCE;
1934                 }
1935                 elsif ($type eq 'links') { 
1936                         $deptype |= $DEPEND_LINKS;
1937                 }
1938                 elsif ($type eq 'content') {
1939                         $deptype |= $DEPEND_CONTENT;
1940                 }
1941         }
1942         return $deptype;
1943 }
1944
1945 my $file_prune_regexp;
1946 sub file_pruned ($) {
1947         my $file=shift;
1948
1949         if (defined $config{include} && length $config{include}) {
1950                 return 0 if $file =~ m/$config{include}/;
1951         }
1952
1953         if (! defined $file_prune_regexp) {
1954                 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1955                 $file_prune_regexp=qr/$file_prune_regexp/;
1956         }
1957         return $file =~ m/$file_prune_regexp/;
1958 }
1959
1960 sub define_gettext () {
1961         # If translation is needed, redefine the gettext function to do it.
1962         # Otherwise, it becomes a quick no-op.
1963         my $gettext_obj;
1964         my $getobj;
1965         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1966             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1967             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1968                 $getobj=sub {
1969                         $gettext_obj=eval q{
1970                                 use Locale::gettext q{textdomain};
1971                                 Locale::gettext->domain('ikiwiki')
1972                         };
1973                 };
1974         }
1975
1976         no warnings 'redefine';
1977         *gettext=sub {
1978                 $getobj->() if $getobj;
1979                 if ($gettext_obj) {
1980                         $gettext_obj->get(shift);
1981                 }
1982                 else {
1983                         return shift;
1984                 }
1985         };
1986         *ngettext=sub {
1987                 $getobj->() if $getobj;
1988                 if ($gettext_obj) {
1989                         $gettext_obj->nget(@_);
1990                 }
1991                 else {
1992                         return ($_[2] == 1 ? $_[0] : $_[1])
1993                 }
1994         };
1995 }
1996
1997 sub gettext {
1998         define_gettext();
1999         gettext(@_);
2000 }
2001
2002 sub ngettext {
2003         define_gettext();
2004         ngettext(@_);
2005 }
2006
2007 sub yesno ($) {
2008         my $val=shift;
2009
2010         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2011 }
2012
2013 sub inject {
2014         # Injects a new function into the symbol table to replace an
2015         # exported function.
2016         my %params=@_;
2017
2018         # This is deep ugly perl foo, beware.
2019         no strict;
2020         no warnings;
2021         if (! defined $params{parent}) {
2022                 $params{parent}='::';
2023                 $params{old}=\&{$params{name}};
2024                 $params{name}=~s/.*:://;
2025         }
2026         my $parent=$params{parent};
2027         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2028                 $ns = $params{parent} . $ns;
2029                 inject(%params, parent => $ns) unless $ns eq '::main::';
2030                 *{$ns . $params{name}} = $params{call}
2031                         if exists ${$ns}{$params{name}} &&
2032                            \&{${$ns}{$params{name}}} == $params{old};
2033         }
2034         use strict;
2035         use warnings;
2036 }
2037
2038 sub add_link ($$;$) {
2039         my $page=shift;
2040         my $link=shift;
2041         my $type=shift;
2042
2043         push @{$links{$page}}, $link
2044                 unless grep { $_ eq $link } @{$links{$page}};
2045
2046         if (defined $type) {
2047                 $typedlinks{$page}{$type}{$link} = 1;
2048         }
2049 }
2050
2051 sub add_autofile ($$$) {
2052         my $file=shift;
2053         my $plugin=shift;
2054         my $generator=shift;
2055         
2056         $autofiles{$file}{plugin}=$plugin;
2057         $autofiles{$file}{generator}=$generator;
2058 }
2059
2060 sub sortspec_translate ($$) {
2061         my $spec = shift;
2062         my $reverse = shift;
2063
2064         my $code = "";
2065         my @data;
2066         while ($spec =~ m{
2067                 \s*
2068                 (-?)            # group 1: perhaps negated
2069                 \s*
2070                 (               # group 2: a word
2071                         \w+\([^\)]*\)   # command(params)
2072                         |
2073                         [^\s]+          # or anything else
2074                 )
2075                 \s*
2076         }gx) {
2077                 my $negated = $1;
2078                 my $word = $2;
2079                 my $params = undef;
2080
2081                 if ($word =~ m/^(\w+)\((.*)\)$/) {
2082                         # command with parameters
2083                         $params = $2;
2084                         $word = $1;
2085                 }
2086                 elsif ($word !~ m/^\w+$/) {
2087                         error(sprintf(gettext("invalid sort type %s"), $word));
2088                 }
2089
2090                 if (length $code) {
2091                         $code .= " || ";
2092                 }
2093
2094                 if ($negated) {
2095                         $code .= "-";
2096                 }
2097
2098                 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2099                         if (defined $params) {
2100                                 push @data, $params;
2101                                 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2102                         }
2103                         else {
2104                                 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2105                         }
2106                 }
2107                 else {
2108                         error(sprintf(gettext("unknown sort type %s"), $word));
2109                 }
2110         }
2111
2112         if (! length $code) {
2113                 # undefined sorting method... sort arbitrarily
2114                 return sub { 0 };
2115         }
2116
2117         if ($reverse) {
2118                 $code="-($code)";
2119         }
2120
2121         no warnings;
2122         return eval 'sub { '.$code.' }';
2123 }
2124
2125 sub pagespec_translate ($) {
2126         my $spec=shift;
2127
2128         # Convert spec to perl code.
2129         my $code="";
2130         my @data;
2131         while ($spec=~m{
2132                 \s*             # ignore whitespace
2133                 (               # 1: match a single word
2134                         \!              # !
2135                 |
2136                         \(              # (
2137                 |
2138                         \)              # )
2139                 |
2140                         \w+\([^\)]*\)   # command(params)
2141                 |
2142                         [^\s()]+        # any other text
2143                 )
2144                 \s*             # ignore whitespace
2145         }gx) {
2146                 my $word=$1;
2147                 if (lc $word eq 'and') {
2148                         $code.=' &';
2149                 }
2150                 elsif (lc $word eq 'or') {
2151                         $code.=' |';
2152                 }
2153                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2154                         $code.=' '.$word;
2155                 }
2156                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2157                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2158                                 push @data, $2;
2159                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2160                         }
2161                         else {
2162                                 push @data, qq{unknown function in pagespec "$word"};
2163                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2164                         }
2165                 }
2166                 else {
2167                         push @data, $word;
2168                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2169                 }
2170         }
2171
2172         if (! length $code) {
2173                 $code="IkiWiki::FailReason->new('empty pagespec')";
2174         }
2175
2176         no warnings;
2177         return eval 'sub { my $page=shift; '.$code.' }';
2178 }
2179
2180 sub pagespec_match ($$;@) {
2181         my $page=shift;
2182         my $spec=shift;
2183         my @params=@_;
2184
2185         # Backwards compatability with old calling convention.
2186         if (@params == 1) {
2187                 unshift @params, 'location';
2188         }
2189
2190         my $sub=pagespec_translate($spec);
2191         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2192                 if ! defined $sub;
2193         return $sub->($page, @params);
2194 }
2195
2196 sub pagespec_match_list ($$;@) {
2197         my $page=shift;
2198         my $pagespec=shift;
2199         my %params=@_;
2200
2201         # Backwards compatability with old calling convention.
2202         if (ref $page) {
2203                 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2204                 $params{list}=$page;
2205                 $page=$params{location}; # ugh!
2206         }
2207
2208         my $sub=pagespec_translate($pagespec);
2209         error "syntax error in pagespec \"$pagespec\""
2210                 if ! defined $sub;
2211         my $sort=sortspec_translate($params{sort}, $params{reverse})
2212                 if defined $params{sort};
2213
2214         my @candidates;
2215         if (exists $params{list}) {
2216                 @candidates=exists $params{filter}
2217                         ? grep { ! $params{filter}->($_) } @{$params{list}}
2218                         : @{$params{list}};
2219         }
2220         else {
2221                 @candidates=exists $params{filter}
2222                         ? grep { ! $params{filter}->($_) } keys %pagesources
2223                         : keys %pagesources;
2224         }
2225         
2226         # clear params, remainder is passed to pagespec
2227         $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2228         my $num=$params{num};
2229         delete @params{qw{num deptype reverse sort filter list}};
2230         
2231         # when only the top matches will be returned, it's efficient to
2232         # sort before matching to pagespec,
2233         if (defined $num && defined $sort) {
2234                 @candidates=IkiWiki::SortSpec::sort_pages(
2235                         $sort, @candidates);
2236         }
2237         
2238         my @matches;
2239         my $firstfail;
2240         my $count=0;
2241         my $accum=IkiWiki::SuccessReason->new();
2242         foreach my $p (@candidates) {
2243                 my $r=$sub->($p, %params, location => $page);
2244                 error(sprintf(gettext("cannot match pages: %s"), $r))
2245                         if $r->isa("IkiWiki::ErrorReason");
2246                 unless ($r || $r->influences_static) {
2247                         $r->remove_influence($p);
2248                 }
2249                 $accum |= $r;
2250                 if ($r) {
2251                         push @matches, $p;
2252                         last if defined $num && ++$count == $num;
2253                 }
2254         }
2255
2256         # Add simple dependencies for accumulated influences.
2257         my $i=$accum->influences;
2258         foreach my $k (keys %$i) {
2259                 $depends_simple{$page}{lc $k} |= $i->{$k};
2260         }
2261
2262         # when all matches will be returned, it's efficient to
2263         # sort after matching
2264         if (! defined $num && defined $sort) {
2265                 return IkiWiki::SortSpec::sort_pages(
2266                         $sort, @matches);
2267         }
2268         else {
2269                 return @matches;
2270         }
2271 }
2272
2273 sub pagespec_valid ($) {
2274         my $spec=shift;
2275
2276         return defined pagespec_translate($spec);
2277 }
2278
2279 sub glob2re ($) {
2280         my $re=quotemeta(shift);
2281         $re=~s/\\\*/.*/g;
2282         $re=~s/\\\?/./g;
2283         return $re;
2284 }
2285
2286 package IkiWiki::FailReason;
2287
2288 use overload (
2289         '""'    => sub { $_[0][0] },
2290         '0+'    => sub { 0 },
2291         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2292         '&'     => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2293         '|'     => sub { $_[1]->merge_influences($_[0]); $_[1] },
2294         fallback => 1,
2295 );
2296
2297 our @ISA = 'IkiWiki::SuccessReason';
2298
2299 package IkiWiki::SuccessReason;
2300
2301 use overload (
2302         '""'    => sub { $_[0][0] },
2303         '0+'    => sub { 1 },
2304         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
2305         '&'     => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2306         '|'     => sub { $_[0]->merge_influences($_[1]); $_[0] },
2307         fallback => 1,
2308 );
2309
2310 sub new {
2311         my $class = shift;
2312         my $value = shift;
2313         return bless [$value, {@_}], $class;
2314 }
2315
2316 sub influences {
2317         my $this=shift;
2318         $this->[1]={@_} if @_;
2319         my %i=%{$this->[1]};
2320         delete $i{""};
2321         return \%i;
2322 }
2323
2324 sub influences_static {
2325         return ! $_[0][1]->{""};
2326 }
2327
2328 sub merge_influences {
2329         my $this=shift;
2330         my $other=shift;
2331         my $anded=shift;
2332
2333         if (! $anded || (($this || %{$this->[1]}) &&
2334                          ($other || %{$other->[1]}))) {
2335                 foreach my $influence (keys %{$other->[1]}) {
2336                         $this->[1]{$influence} |= $other->[1]{$influence};
2337                 }
2338         }
2339         else {
2340                 # influence blocker
2341                 $this->[1]={};
2342         }
2343 }
2344
2345 sub remove_influence {
2346         my $this=shift;
2347         my $torm=shift;
2348
2349         delete $this->[1]{$torm};
2350 }
2351
2352 package IkiWiki::ErrorReason;
2353
2354 our @ISA = 'IkiWiki::FailReason';
2355
2356 package IkiWiki::PageSpec;
2357
2358 sub derel ($$) {
2359         my $path=shift;
2360         my $from=shift;
2361
2362         if ($path =~ m!^\./!) {
2363                 $from=~s#/?[^/]+$## if defined $from;
2364                 $path=~s#^\./##;
2365                 $path="$from/$path" if defined $from && length $from;
2366         }
2367
2368         return $path;
2369 }
2370
2371 sub match_glob ($$;@) {
2372         my $page=shift;
2373         my $glob=shift;
2374         my %params=@_;
2375         
2376         $glob=derel($glob, $params{location});
2377
2378         my $regexp=IkiWiki::glob2re($glob);
2379         if ($page=~/^$regexp$/i) {
2380                 if (! IkiWiki::isinternal($page) || $params{internal}) {
2381                         return IkiWiki::SuccessReason->new("$glob matches $page");
2382                 }
2383                 else {
2384                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2385                 }
2386         }
2387         else {
2388                 return IkiWiki::FailReason->new("$glob does not match $page");
2389         }
2390 }
2391
2392 sub match_internal ($$;@) {
2393         return match_glob(shift, shift, @_, internal => 1)
2394 }
2395
2396 sub match_page ($$;@) {
2397         my $page=shift;
2398         my $match=match_glob($page, shift, @_);
2399         if ($match && ! (exists $IkiWiki::pagesources{$page}
2400             && defined IkiWiki::pagetype($IkiWiki::pagesources{$page}))) {
2401                 return IkiWiki::FailReason->new("$page is not a page");
2402         }
2403         else {
2404                 return $match;
2405         }
2406 }
2407
2408 sub match_link ($$;@) {
2409         my $page=shift;
2410         my $link=lc(shift);
2411         my %params=@_;
2412
2413         $link=derel($link, $params{location});
2414         my $from=exists $params{location} ? $params{location} : '';
2415         my $linktype=$params{linktype};
2416         my $qualifier='';
2417         if (defined $linktype) {
2418                 $qualifier=" with type $linktype";
2419         }
2420
2421         my $links = $IkiWiki::links{$page};
2422         return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2423                 unless $links && @{$links};
2424         my $bestlink = IkiWiki::bestlink($from, $link);
2425         foreach my $p (@{$links}) {
2426                 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2427
2428                 if (length $bestlink) {
2429                         if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2430                                 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2431                         }
2432                 }
2433                 else {
2434                         if (match_glob($p, $link, %params)) {
2435                                 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2436                         }
2437                         my ($p_rel)=$p=~/^\/?(.*)/;
2438                         $link=~s/^\///;
2439                         if (match_glob($p_rel, $link, %params)) {
2440                                 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2441                         }
2442                 }
2443         }
2444         return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2445 }
2446
2447 sub match_backlink ($$;@) {
2448         my $ret=match_link($_[1], $_[0], @_);
2449         $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2450         return $ret;
2451 }
2452
2453 sub match_created_before ($$;@) {
2454         my $page=shift;
2455         my $testpage=shift;
2456         my %params=@_;
2457         
2458         $testpage=derel($testpage, $params{location});
2459
2460         if (exists $IkiWiki::pagectime{$testpage}) {
2461                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2462                         return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2463                 }
2464                 else {
2465                         return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2466                 }
2467         }
2468         else {
2469                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2470         }
2471 }
2472
2473 sub match_created_after ($$;@) {
2474         my $page=shift;
2475         my $testpage=shift;
2476         my %params=@_;
2477         
2478         $testpage=derel($testpage, $params{location});
2479
2480         if (exists $IkiWiki::pagectime{$testpage}) {
2481                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2482                         return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2483                 }
2484                 else {
2485                         return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2486                 }
2487         }
2488         else {
2489                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2490         }
2491 }
2492
2493 sub match_creation_day ($$;@) {
2494         if ((localtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2495                 return IkiWiki::SuccessReason->new('creation_day matched');
2496         }
2497         else {
2498                 return IkiWiki::FailReason->new('creation_day did not match');
2499         }
2500 }
2501
2502 sub match_creation_month ($$;@) {
2503         if ((localtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2504                 return IkiWiki::SuccessReason->new('creation_month matched');
2505         }
2506         else {
2507                 return IkiWiki::FailReason->new('creation_month did not match');
2508         }
2509 }
2510
2511 sub match_creation_year ($$;@) {
2512         if ((localtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2513                 return IkiWiki::SuccessReason->new('creation_year matched');
2514         }
2515         else {
2516                 return IkiWiki::FailReason->new('creation_year did not match');
2517         }
2518 }
2519
2520 sub match_user ($$;@) {
2521         shift;
2522         my $user=shift;
2523         my %params=@_;
2524         
2525         my $regexp=IkiWiki::glob2re($user);
2526         
2527         if (! exists $params{user}) {
2528                 return IkiWiki::ErrorReason->new("no user specified");
2529         }
2530
2531         if (defined $params{user} && $params{user}=~/^$regexp$/i) {
2532                 return IkiWiki::SuccessReason->new("user is $user");
2533         }
2534         elsif (! defined $params{user}) {
2535                 return IkiWiki::FailReason->new("not logged in");
2536         }
2537         else {
2538                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2539         }
2540 }
2541
2542 sub match_admin ($$;@) {
2543         shift;
2544         shift;
2545         my %params=@_;
2546         
2547         if (! exists $params{user}) {
2548                 return IkiWiki::ErrorReason->new("no user specified");
2549         }
2550
2551         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2552                 return IkiWiki::SuccessReason->new("user is an admin");
2553         }
2554         elsif (! defined $params{user}) {
2555                 return IkiWiki::FailReason->new("not logged in");
2556         }
2557         else {
2558                 return IkiWiki::FailReason->new("user is not an admin");
2559         }
2560 }
2561
2562 sub match_ip ($$;@) {
2563         shift;
2564         my $ip=shift;
2565         my %params=@_;
2566         
2567         if (! exists $params{ip}) {
2568                 return IkiWiki::ErrorReason->new("no IP specified");
2569         }
2570
2571         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2572                 return IkiWiki::SuccessReason->new("IP is $ip");
2573         }
2574         else {
2575                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2576         }
2577 }
2578
2579 package IkiWiki::SortSpec;
2580
2581 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2582 # are easily available in this namespace, for cmp functions to use them.
2583 sub sort_pages {
2584         my $f=shift;
2585         sort $f @_
2586 }
2587
2588 sub cmp_title {
2589         IkiWiki::pagetitle(IkiWiki::basename($a))
2590         cmp
2591         IkiWiki::pagetitle(IkiWiki::basename($b))
2592 }
2593
2594 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2595 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }
2596
2597 1