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