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