load all plugins when generating setup
[ikiwiki.git] / IkiWiki.pm
1 #!/usr/bin/perl
2
3 package IkiWiki;
4
5 use warnings;
6 use strict;
7 use Encode;
8 use HTML::Entities;
9 use URI::Escape q{uri_escape_utf8};
10 use POSIX;
11 use Storable;
12 use open qw{:utf8 :std};
13
14 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
15             %pagestate %renderedfiles %oldrenderedfiles %pagesources
16             %destsources %depends %hooks %forcerebuild $gettext_obj};
17
18 use Exporter q{import};
19 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
20                  bestlink htmllink readfile writefile pagetype srcfile pagename
21                  displaytime will_render gettext urlto targetpage
22                  add_underlay
23                  %config %links %pagestate %renderedfiles
24                  %pagesources %destsources);
25 our $VERSION = 2.00; # plugin interface version, next is ikiwiki version
26 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
27 my $installdir=''; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
28
29 # Optimisation.
30 use Memoize;
31 memoize("abs2rel");
32 memoize("pagespec_translate");
33 memoize("file_pruned");
34
35 sub getsetup () { #{{{
36         wikiname => {
37                 type => "string",
38                 default => "wiki",
39                 description => "name of the wiki",
40                 safe => 1,
41                 rebuild => 1,
42         },
43         srcdir => {
44                 type => "string",
45                 default => undef,
46                 example => "$ENV{HOME}/wiki",
47                 description => "where the source of the wiki is located",
48                 safe => 0, # path
49                 rebuild => 1,
50         },
51         destdir => {
52                 type => "string",
53                 default => undef,
54                 example => "/var/www/wiki",
55                 description => "where to build the wiki",
56                 safe => 0, # path
57                 rebuild => 1,
58         },
59         adminuser => {
60                 type => "string",
61                 default => [],
62                 description => "user names of wiki admins",
63                 safe => 1,
64                 rebuild => 0,
65         },
66         adminemail => {
67                 type => "string",
68                 default => undef,
69                 example => 'me@example.com',
70                 description => "contact email for wiki",
71                 safe => 1,
72                 rebuild => 0,
73         },
74         url => {
75                 type => "string",
76                 default => '',
77                 example => "http://example.com/wiki",
78                 description => "base url to the wiki",
79                 safe => 1,
80                 rebuild => 1,
81         },
82         cgiurl => {
83                 type => "string",
84                 default => '',
85                 examples => "http://example.com/wiki/ikiwiki.cgi",
86                 description => "url to the ikiwiki.cgi",
87                 safe => 1,
88                 rebuild => 1,
89         },
90         rcs => {
91                 type => "string",
92                 default => '',
93                 description => "rcs backend to use",
94                 safe => 0, # don't allow overriding
95                 rebuild => 0,
96         },
97         default_plugins => {
98                 type => "internal",
99                 default => [qw{mdwn link inline htmlscrubber passwordauth
100                                 openid signinedit lockedit conditional
101                                 recentchanges parentlinks}],
102                 description => "plugins to enable by default",
103                 safe => 1,
104                 rebuild => 1,
105         },
106         add_plugins => {
107                 type => "string",
108                 default => [],
109                 description => "plugins to add to the default configuration",
110                 safe => 1,
111                 rebuild => 1,
112         },
113         disable_plugins => {
114                 type => "string",
115                 default => [],
116                 description => "plugins to disable",
117                 safe => 1,
118                 rebuild => 1,
119         },
120         wrappers => {
121                 type => "string",
122                 default => undef,
123                 description => "definitions of wrappers to generate",
124                 safe => 0,
125                 rebuild => 0,
126         },
127         wrapper => {
128                 type => "internal",
129                 default => undef,
130                 description => "wrapper filename",
131                 safe => 0,
132                 rebuild => 0,
133         },
134         wrappermode => {
135                 type => "internal",
136                 default => undef,
137                 description => "mode of wrapper file",
138                 safe => 0,
139                 rebuild => 0,
140         },
141         templatedir => {
142                 type => "string",
143                 default => "$installdir/share/ikiwiki/templates",
144                 description => "location of template files",
145                 safe => 0, # path
146                 rebuild => 1,
147         },
148         underlaydir => {
149                 type => "string",
150                 default => "$installdir/share/ikiwiki/basewiki",
151                 description => "base wiki source location",
152                 safe => 0, # path
153                 rebuild => 0,
154         },
155         underlaydirs => {
156                 type => "internal",
157                 default => [],
158                 description => "additional underlays to use",
159                 safe => 0,
160                 rebuild => 0,
161         },
162         verbose => {
163                 type => "boolean",
164                 default => 0,
165                 description => "display verbose messages when building?",
166                 safe => 1,
167                 rebuild => 0,
168         },
169         syslog => {
170                 type => "boolean",
171                 default => 0,
172                 description => "log to syslog?",
173                 safe => 1,
174                 rebuild => 0,
175         },
176         usedirs => {
177                 type => "boolean",
178                 default => 1,
179                 description => "create output files named page/index.html?",
180                 safe => 0, # changing requires manual transition
181                 rebuild => 1,
182         },
183         prefix_directives => {
184                 type => "boolean",
185                 default => 0,
186                 description => "use '!'-prefixed preprocessor directives?",
187                 safe => 0, # changing requires manual transition
188                 rebuild => 1,
189         },
190         discussion => {
191                 type => "boolean",
192                 default => 1,
193                 description => "enable Discussion pages?",
194                 safe => 1,
195                 rebuild => 1,
196         },
197         default_pageext => {
198                 type => "string",
199                 default => "mdwn",
200                 description => "extension to use for new pages",
201                 safe => 0, # not sanitized
202                 rebuild => 0,
203         },
204         htmlext => {
205                 type => "string",
206                 default => "html",
207                 description => "extension to use for html files",
208                 safe => 0, # not sanitized
209                 rebuild => 1,
210         },
211         timeformat => {
212                 type => "string",
213                 default => '%c',
214                 description => "strftime format string to display date",
215                 safe => 1,
216                 rebuild => 1,
217         },
218         locale => {
219                 type => "string",
220                 default => undef,
221                 example => "en_US.UTF-8",
222                 description => "UTF-8 locale to use",
223                 safe => 0,
224                 rebuild => 1,
225         },
226         sslcookie => {
227                 type => "boolean",
228                 default => 0,
229                 description => "only send cookies over SSL connections?",
230                 safe => 1,
231                 rebuild => 0,
232         },
233         userdir => {
234                 type => "string",
235                 default => "",
236                 example => "users",
237                 description => "put user pages below specified page",
238                 safe => 1,
239                 rebuild => 1,
240         },
241         numbacklinks => {
242                 type => "integer",
243                 default => 10,
244                 description => "how many backlinks to show before hiding excess (0 to show all)",
245                 safe => 1,
246                 rebuild => 1,
247         },
248         hardlink => {
249                 type => "boolean",
250                 default => 0,
251                 description => "attempt to hardlink source files? (optimisation for large files)",
252                 safe => 0, # paranoia
253                 rebuild => 0,
254         },
255
256         exclude => {
257                 type => "string",
258                 default => undef,
259                 example => '\.wav$',
260                 description => "regexp of source files to ignore",
261                 safe => 0, # regexp
262                 rebuild => 1,
263         },
264         wiki_file_prune_regexps => {
265                 type => "internal",
266                 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
267                         qr/\.x?html?$/, qr/\.ikiwiki-new$/,
268                         qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
269                         qr/(^|\/)_MTN\//,
270                         qr/\.dpkg-tmp$/],
271                 description => "regexps of source files to ignore",
272                 safe => 0,
273                 rebuild => 1,
274         },
275         wiki_file_regexp => {
276                 type => "internal",
277                 default => qr/(^[-[:alnum:]_.:\/+]+$)/,
278                 description => "regexp of legal source files",
279                 safe => 0,
280                 rebuild => 1,
281         },
282         web_commit_regexp => {
283                 type => "internal",
284                 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
285                 description => "regexp to parse web commits from logs",
286                 safe => 0,
287                 rebuild => 0,
288         },
289         cgi => {
290                 type => "internal",
291                 default => 0,
292                 description => "run as a cgi",
293                 safe => 0,
294                 rebuild => 0,
295         },
296         cgi_disable_uploads => {
297                 type => "internal",
298                 default => 1,
299                 description => "whether CGI should accept file uploads",
300                 safe => 0,
301                 rebuild => 0,
302         },
303         post_commit => {
304                 type => "internal",
305                 default => 0,
306                 description => "run as a post-commit hook",
307                 safe => 0,
308                 rebuild => 0,
309         },
310         rebuild => {
311                 type => "internal",
312                 default => 0,
313                 description => "running in rebuild mode",
314                 safe => 0,
315                 rebuild => 0,
316         },
317         refresh => {
318                 type => "internal",
319                 default => 0,
320                 description => "running in refresh mode",
321                 safe => 0,
322                 rebuild => 0,
323         },
324         getctime => {
325                 type => "internal",
326                 default => 0,
327                 description => "running in getctime mode",
328                 safe => 0,
329                 rebuild => 0,
330         },
331         w3mmode => {
332                 type => "internal",
333                 default => 0,
334                 description => "running in w3mmode",
335                 safe => 0,
336                 rebuild => 0,
337         },
338         setup => {
339                 type => "internal",
340                 default => undef,
341                 description => "setup file to read",
342                 safe => 0,
343                 rebuild => 0,
344         },
345         libdir => {
346                 type => "internal",
347                 default => undef,
348                 example => "$ENV{HOME}/.ikiwiki/",
349                 description => "extra library and plugin directory",
350                 safe => 0,
351                 rebuild => 0,
352         },
353 } #}}}
354
355 sub defaultconfig () { #{{{
356         my %s=getsetup();
357         my @ret;
358         foreach my $key (keys %s) {
359                 push @ret, $key, $s{$key}->{default};
360         }
361         use Data::Dumper;
362         return @ret;
363 } #}}}
364
365 sub checkconfig () { #{{{
366         # locale stuff; avoid LC_ALL since it overrides everything
367         if (defined $ENV{LC_ALL}) {
368                 $ENV{LANG} = $ENV{LC_ALL};
369                 delete $ENV{LC_ALL};
370         }
371         if (defined $config{locale}) {
372                 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
373                         $ENV{LANG}=$config{locale};
374                         $gettext_obj=undef;
375                 }
376         }
377
378         if (ref $config{ENV} eq 'HASH') {
379                 foreach my $val (keys %{$config{ENV}}) {
380                         $ENV{$val}=$config{ENV}{$val};
381                 }
382         }
383
384         if ($config{w3mmode}) {
385                 eval q{use Cwd q{abs_path}};
386                 error($@) if $@;
387                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
388                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
389                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
390                         unless $config{cgiurl} =~ m!file:///!;
391                 $config{url}="file://".$config{destdir};
392         }
393
394         if ($config{cgi} && ! length $config{url}) {
395                 error(gettext("Must specify url to wiki with --url when using --cgi"));
396         }
397         
398         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
399                 unless exists $config{wikistatedir};
400         
401         if ($config{rcs}) {
402                 eval qq{use IkiWiki::Rcs::$config{rcs}};
403                 if ($@) {
404                         error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
405                 }
406         }
407         else {
408                 require IkiWiki::Rcs::Stub;
409         }
410
411         if (exists $config{umask}) {
412                 umask(possibly_foolish_untaint($config{umask}));
413         }
414
415         run_hooks(checkconfig => sub { shift->() });
416
417         return 1;
418 } #}}}
419
420 sub listplugins () { #{{{
421         my %ret;
422
423         foreach my $dir (@INC, $config{libdir}) {
424                 next unless defined $dir;
425                 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
426                         my ($plugin)=$file=~/.*\/(.*)\.pm$/;
427                         $ret{$plugin}=1;
428                 }
429         }
430         foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
431                 next unless defined $dir;
432                 foreach my $file (glob("$dir/plugins/*")) {
433                         $ret{basename($file)}=1 if -x $file;
434                 }
435         }
436
437         return keys %ret;
438 } #}}}
439
440 sub loadplugins () { #{{{
441         if (defined $config{libdir}) {
442                 unshift @INC, possibly_foolish_untaint($config{libdir});
443         }
444
445         loadplugin($_) foreach @{$config{default_plugins}}, @{$config{add_plugins}};
446
447         run_hooks(getopt => sub { shift->() });
448         if (grep /^-/, @ARGV) {
449                 print STDERR "Unknown option: $_\n"
450                         foreach grep /^-/, @ARGV;
451                 usage();
452         }
453
454         return 1;
455 } #}}}
456
457 sub loadplugin ($) { #{{{
458         my $plugin=shift;
459
460         return if grep { $_ eq $plugin} @{$config{disable_plugins}};
461
462         foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
463                          "$installdir/lib/ikiwiki") {
464                 if (defined $dir && -x "$dir/plugins/$plugin") {
465                         require IkiWiki::Plugin::external;
466                         import IkiWiki::Plugin::external "$dir/plugins/$plugin";
467                         return 1;
468                 }
469         }
470
471         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
472         eval qq{use $mod};
473         if ($@) {
474                 error("Failed to load plugin $mod: $@");
475         }
476         return 1;
477 } #}}}
478
479 sub error ($;$) { #{{{
480         my $message=shift;
481         my $cleaner=shift;
482         log_message('err' => $message) if $config{syslog};
483         if (defined $cleaner) {
484                 $cleaner->();
485         }
486         die $message."\n";
487 } #}}}
488
489 sub debug ($) { #{{{
490         return unless $config{verbose};
491         return log_message(debug => @_);
492 } #}}}
493
494 my $log_open=0;
495 sub log_message ($$) { #{{{
496         my $type=shift;
497
498         if ($config{syslog}) {
499                 require Sys::Syslog;
500                 if (! $log_open) {
501                         Sys::Syslog::setlogsock('unix');
502                         Sys::Syslog::openlog('ikiwiki', '', 'user');
503                         $log_open=1;
504                 }
505                 return eval {
506                         Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
507                 };
508         }
509         elsif (! $config{cgi}) {
510                 return print "@_\n";
511         }
512         else {
513                 return print STDERR "@_\n";
514         }
515 } #}}}
516
517 sub possibly_foolish_untaint ($) { #{{{
518         my $tainted=shift;
519         my ($untainted)=$tainted=~/(.*)/s;
520         return $untainted;
521 } #}}}
522
523 sub basename ($) { #{{{
524         my $file=shift;
525
526         $file=~s!.*/+!!;
527         return $file;
528 } #}}}
529
530 sub dirname ($) { #{{{
531         my $file=shift;
532
533         $file=~s!/*[^/]+$!!;
534         return $file;
535 } #}}}
536
537 sub pagetype ($) { #{{{
538         my $page=shift;
539         
540         if ($page =~ /\.([^.]+)$/) {
541                 return $1 if exists $hooks{htmlize}{$1};
542         }
543         return;
544 } #}}}
545
546 sub isinternal ($) { #{{{
547         my $page=shift;
548         return exists $pagesources{$page} &&
549                 $pagesources{$page} =~ /\._([^.]+)$/;
550 } #}}}
551
552 sub pagename ($) { #{{{
553         my $file=shift;
554
555         my $type=pagetype($file);
556         my $page=$file;
557         $page=~s/\Q.$type\E*$// if defined $type;
558         return $page;
559 } #}}}
560
561 sub targetpage ($$) { #{{{
562         my $page=shift;
563         my $ext=shift;
564         
565         if (! $config{usedirs} || $page =~ /^index$/ ) {
566                 return $page.".".$ext;
567         } else {
568                 return $page."/index.".$ext;
569         }
570 } #}}}
571
572 sub htmlpage ($) { #{{{
573         my $page=shift;
574         
575         return targetpage($page, $config{htmlext});
576 } #}}}
577
578 sub srcfile_stat { #{{{
579         my $file=shift;
580         my $nothrow=shift;
581
582         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
583         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
584                 return "$dir/$file", stat(_) if -e "$dir/$file";
585         }
586         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
587         return;
588 } #}}}
589
590 sub srcfile ($;$) { #{{{
591         return (srcfile_stat(@_))[0];
592 } #}}}
593
594 sub add_underlay ($) { #{{{
595         my $dir=shift;
596
597         if ($dir=~/^\//) {
598                 unshift @{$config{underlaydirs}}, $dir;
599         }
600         else {
601                 unshift @{$config{underlaydirs}}, "$config{underlaydir}/../$dir";
602         }
603
604         return 1;
605 } #}}}
606
607 sub readfile ($;$$) { #{{{
608         my $file=shift;
609         my $binary=shift;
610         my $wantfd=shift;
611
612         if (-l $file) {
613                 error("cannot read a symlink ($file)");
614         }
615         
616         local $/=undef;
617         open (my $in, "<", $file) || error("failed to read $file: $!");
618         binmode($in) if ($binary);
619         return \*$in if $wantfd;
620         my $ret=<$in>;
621         close $in || error("failed to read $file: $!");
622         return $ret;
623 } #}}}
624
625 sub prep_writefile ($$) { #{{{
626         my $file=shift;
627         my $destdir=shift;
628         
629         my $test=$file;
630         while (length $test) {
631                 if (-l "$destdir/$test") {
632                         error("cannot write to a symlink ($test)");
633                 }
634                 $test=dirname($test);
635         }
636
637         my $dir=dirname("$destdir/$file");
638         if (! -d $dir) {
639                 my $d="";
640                 foreach my $s (split(m!/+!, $dir)) {
641                         $d.="$s/";
642                         if (! -d $d) {
643                                 mkdir($d) || error("failed to create directory $d: $!");
644                         }
645                 }
646         }
647
648         return 1;
649 } #}}}
650
651 sub writefile ($$$;$$) { #{{{
652         my $file=shift; # can include subdirs
653         my $destdir=shift; # directory to put file in
654         my $content=shift;
655         my $binary=shift;
656         my $writer=shift;
657         
658         prep_writefile($file, $destdir);
659         
660         my $newfile="$destdir/$file.ikiwiki-new";
661         if (-l $newfile) {
662                 error("cannot write to a symlink ($newfile)");
663         }
664         
665         my $cleanup = sub { unlink($newfile) };
666         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
667         binmode($out) if ($binary);
668         if ($writer) {
669                 $writer->(\*$out, $cleanup);
670         }
671         else {
672                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
673         }
674         close $out || error("failed saving $newfile: $!", $cleanup);
675         rename($newfile, "$destdir/$file") || 
676                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
677
678         return 1;
679 } #}}}
680
681 my %cleared;
682 sub will_render ($$;$) { #{{{
683         my $page=shift;
684         my $dest=shift;
685         my $clear=shift;
686
687         # Important security check.
688         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
689             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}})) {
690                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
691         }
692
693         if (! $clear || $cleared{$page}) {
694                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
695         }
696         else {
697                 foreach my $old (@{$renderedfiles{$page}}) {
698                         delete $destsources{$old};
699                 }
700                 $renderedfiles{$page}=[$dest];
701                 $cleared{$page}=1;
702         }
703         $destsources{$dest}=$page;
704
705         return 1;
706 } #}}}
707
708 sub bestlink ($$) { #{{{
709         my $page=shift;
710         my $link=shift;
711         
712         my $cwd=$page;
713         if ($link=~s/^\/+//) {
714                 # absolute links
715                 $cwd="";
716         }
717         $link=~s/\/$//;
718
719         do {
720                 my $l=$cwd;
721                 $l.="/" if length $l;
722                 $l.=$link;
723
724                 if (exists $links{$l}) {
725                         return $l;
726                 }
727                 elsif (exists $pagecase{lc $l}) {
728                         return $pagecase{lc $l};
729                 }
730         } while $cwd=~s!/?[^/]+$!!;
731
732         if (length $config{userdir}) {
733                 my $l = "$config{userdir}/".lc($link);
734                 if (exists $links{$l}) {
735                         return $l;
736                 }
737                 elsif (exists $pagecase{lc $l}) {
738                         return $pagecase{lc $l};
739                 }
740         }
741
742         #print STDERR "warning: page $page, broken link: $link\n";
743         return "";
744 } #}}}
745
746 sub isinlinableimage ($) { #{{{
747         my $file=shift;
748         
749         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
750 } #}}}
751
752 sub pagetitle ($;$) { #{{{
753         my $page=shift;
754         my $unescaped=shift;
755
756         if ($unescaped) {
757                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
758         }
759         else {
760                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
761         }
762
763         return $page;
764 } #}}}
765
766 sub titlepage ($) { #{{{
767         my $title=shift;
768         $title=~s/([^-[:alnum:]:+\/.])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
769         return $title;
770 } #}}}
771
772 sub linkpage ($) { #{{{
773         my $link=shift;
774         $link=~s/([^-[:alnum:]:+\/._])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
775         return $link;
776 } #}}}
777
778 sub cgiurl (@) { #{{{
779         my %params=@_;
780
781         return $config{cgiurl}."?".
782                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
783 } #}}}
784
785 sub baseurl (;$) { #{{{
786         my $page=shift;
787
788         return "$config{url}/" if ! defined $page;
789         
790         $page=htmlpage($page);
791         $page=~s/[^\/]+$//;
792         $page=~s/[^\/]+\//..\//g;
793         return $page;
794 } #}}}
795
796 sub abs2rel ($$) { #{{{
797         # Work around very innefficient behavior in File::Spec if abs2rel
798         # is passed two relative paths. It's much faster if paths are
799         # absolute! (Debian bug #376658; fixed in debian unstable now)
800         my $path="/".shift;
801         my $base="/".shift;
802
803         require File::Spec;
804         my $ret=File::Spec->abs2rel($path, $base);
805         $ret=~s/^// if defined $ret;
806         return $ret;
807 } #}}}
808
809 sub displaytime ($;$) { #{{{
810         my $time=shift;
811         my $format=shift;
812         if (! defined $format) {
813                 $format=$config{timeformat};
814         }
815
816         # strftime doesn't know about encodings, so make sure
817         # its output is properly treated as utf8
818         return decode_utf8(POSIX::strftime($format, localtime($time)));
819 } #}}}
820
821 sub beautify_urlpath ($) { #{{{
822         my $url=shift;
823
824         if ($config{usedirs}) {
825                 $url =~ s!/index.$config{htmlext}$!/!;
826         }
827
828         # Ensure url is not an empty link, and
829         # if it's relative, make that explicit to avoid colon confusion.
830         if ($url !~ /^\//) {
831                 $url="./$url";
832         }
833
834         return $url;
835 } #}}}
836
837 sub urlto ($$;$) { #{{{
838         my $to=shift;
839         my $from=shift;
840         my $absolute=shift;
841         
842         if (! length $to) {
843                 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
844         }
845
846         if (! $destsources{$to}) {
847                 $to=htmlpage($to);
848         }
849
850         if ($absolute) {
851                 return $config{url}.beautify_urlpath("/".$to);
852         }
853
854         my $link = abs2rel($to, dirname(htmlpage($from)));
855
856         return beautify_urlpath($link);
857 } #}}}
858
859 sub htmllink ($$$;@) { #{{{
860         my $lpage=shift; # the page doing the linking
861         my $page=shift; # the page that will contain the link (different for inline)
862         my $link=shift;
863         my %opts=@_;
864
865         $link=~s/\/$//;
866
867         my $bestlink;
868         if (! $opts{forcesubpage}) {
869                 $bestlink=bestlink($lpage, $link);
870         }
871         else {
872                 $bestlink="$lpage/".lc($link);
873         }
874
875         my $linktext;
876         if (defined $opts{linktext}) {
877                 $linktext=$opts{linktext};
878         }
879         else {
880                 $linktext=pagetitle(basename($link));
881         }
882         
883         return "<span class=\"selflink\">$linktext</span>"
884                 if length $bestlink && $page eq $bestlink &&
885                    ! defined $opts{anchor};
886         
887         if (! $destsources{$bestlink}) {
888                 $bestlink=htmlpage($bestlink);
889
890                 if (! $destsources{$bestlink}) {
891                         return $linktext unless length $config{cgiurl};
892                         return "<span class=\"createlink\"><a href=\"".
893                                 cgiurl(
894                                         do => "create",
895                                         page => lc($link),
896                                         from => $lpage
897                                 ).
898                                 "\" rel=\"nofollow\">?</a>$linktext</span>"
899                 }
900         }
901         
902         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
903         $bestlink=beautify_urlpath($bestlink);
904         
905         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
906                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
907         }
908
909         if (defined $opts{anchor}) {
910                 $bestlink.="#".$opts{anchor};
911         }
912
913         my @attrs;
914         if (defined $opts{rel}) {
915                 push @attrs, ' rel="'.$opts{rel}.'"';
916         }
917         if (defined $opts{class}) {
918                 push @attrs, ' class="'.$opts{class}.'"';
919         }
920
921         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
922 } #}}}
923
924 sub userlink ($) { #{{{
925         my $user=shift;
926
927         my $oiduser=eval { openiduser($user) };
928         if (defined $oiduser) {
929                 return "<a href=\"$user\">$oiduser</a>";
930         }
931         else {
932                 eval q{use CGI 'escapeHTML'};
933                 error($@) if $@;
934
935                 return htmllink("", "", escapeHTML(
936                         length $config{userdir} ? $config{userdir}."/".$user : $user
937                 ), noimageinline => 1);
938         }
939 } #}}}
940
941 sub htmlize ($$$$) { #{{{
942         my $page=shift;
943         my $destpage=shift;
944         my $type=shift;
945         my $content=shift;
946         
947         my $oneline = $content !~ /\n/;
948
949         if (exists $hooks{htmlize}{$type}) {
950                 $content=$hooks{htmlize}{$type}{call}->(
951                         page => $page,
952                         content => $content,
953                 );
954         }
955         else {
956                 error("htmlization of $type not supported");
957         }
958
959         run_hooks(sanitize => sub {
960                 $content=shift->(
961                         page => $page,
962                         destpage => $destpage,
963                         content => $content,
964                 );
965         });
966         
967         if ($oneline) {
968                 # hack to get rid of enclosing junk added by markdown
969                 # and other htmlizers
970                 $content=~s/^<p>//i;
971                 $content=~s/<\/p>$//i;
972                 chomp $content;
973         }
974
975         return $content;
976 } #}}}
977
978 sub linkify ($$$) { #{{{
979         my $page=shift;
980         my $destpage=shift;
981         my $content=shift;
982
983         run_hooks(linkify => sub {
984                 $content=shift->(
985                         page => $page,
986                         destpage => $destpage,
987                         content => $content,
988                 );
989         });
990         
991         return $content;
992 } #}}}
993
994 our %preprocessing;
995 our $preprocess_preview=0;
996 sub preprocess ($$$;$$) { #{{{
997         my $page=shift; # the page the data comes from
998         my $destpage=shift; # the page the data will appear in (different for inline)
999         my $content=shift;
1000         my $scan=shift;
1001         my $preview=shift;
1002
1003         # Using local because it needs to be set within any nested calls
1004         # of this function.
1005         local $preprocess_preview=$preview if defined $preview;
1006
1007         my $handle=sub {
1008                 my $escape=shift;
1009                 my $prefix=shift;
1010                 my $command=shift;
1011                 my $params=shift;
1012                 if (length $escape) {
1013                         return "[[$prefix$command $params]]";
1014                 }
1015                 elsif (exists $hooks{preprocess}{$command}) {
1016                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1017                         # Note: preserve order of params, some plugins may
1018                         # consider it significant.
1019                         my @params;
1020                         while ($params =~ m{
1021                                 (?:([-\w]+)=)?          # 1: named parameter key?
1022                                 (?:
1023                                         """(.*?)"""     # 2: triple-quoted value
1024                                 |
1025                                         "([^"]+)"       # 3: single-quoted value
1026                                 |
1027                                         (\S+)           # 4: unquoted value
1028                                 )
1029                                 (?:\s+|$)               # delimiter to next param
1030                         }sgx) {
1031                                 my $key=$1;
1032                                 my $val;
1033                                 if (defined $2) {
1034                                         $val=$2;
1035                                         $val=~s/\r\n/\n/mg;
1036                                         $val=~s/^\n+//g;
1037                                         $val=~s/\n+$//g;
1038                                 }
1039                                 elsif (defined $3) {
1040                                         $val=$3;
1041                                 }
1042                                 elsif (defined $4) {
1043                                         $val=$4;
1044                                 }
1045
1046                                 if (defined $key) {
1047                                         push @params, $key, $val;
1048                                 }
1049                                 else {
1050                                         push @params, $val, '';
1051                                 }
1052                         }
1053                         if ($preprocessing{$page}++ > 3) {
1054                                 # Avoid loops of preprocessed pages preprocessing
1055                                 # other pages that preprocess them, etc.
1056                                 #translators: The first parameter is a
1057                                 #translators: preprocessor directive name,
1058                                 #translators: the second a page name, the
1059                                 #translators: third a number.
1060                                 return "[[".sprintf(gettext("%s preprocessing loop detected on %s at depth %i"),
1061                                         $command, $page, $preprocessing{$page}).
1062                                 "]]";
1063                         }
1064                         my $ret;
1065                         if (! $scan) {
1066                                 $ret=eval {
1067                                         $hooks{preprocess}{$command}{call}->(
1068                                                 @params,
1069                                                 page => $page,
1070                                                 destpage => $destpage,
1071                                                 preview => $preprocess_preview,
1072                                         );
1073                                 };
1074                                 if ($@) {
1075                                         chomp $@;
1076                                         $ret="[[!$command <span class=\"error\">".
1077                                                 gettext("Error").": $@"."</span>]]";
1078                                 }
1079                         }
1080                         else {
1081                                 # use void context during scan pass
1082                                 eval {
1083                                         $hooks{preprocess}{$command}{call}->(
1084                                                 @params,
1085                                                 page => $page,
1086                                                 destpage => $destpage,
1087                                                 preview => $preprocess_preview,
1088                                         );
1089                                 };
1090                                 $ret="";
1091                         }
1092                         $preprocessing{$page}--;
1093                         return $ret;
1094                 }
1095                 else {
1096                         return "[[$prefix$command $params]]";
1097                 }
1098         };
1099         
1100         my $regex;
1101         if ($config{prefix_directives}) {
1102                 $regex = qr{
1103                         (\\?)           # 1: escape?
1104                         \[\[(!)         # directive open; 2: prefix
1105                         ([-\w]+)        # 3: command
1106                         (               # 4: the parameters..
1107                                 \s+     # Must have space if parameters present
1108                                 (?:
1109                                         (?:[-\w]+=)?            # named parameter key?
1110                                         (?:
1111                                                 """.*?"""       # triple-quoted value
1112                                                 |
1113                                                 "[^"]+"         # single-quoted value
1114                                                 |
1115                                                 [^\s\]]+        # unquoted value
1116                                         )
1117                                         \s*                     # whitespace or end
1118                                                                 # of directive
1119                                 )
1120                         *)?             # 0 or more parameters
1121                         \]\]            # directive closed
1122                 }sx;
1123         }
1124         else {
1125                 $regex = qr{
1126                         (\\?)           # 1: escape?
1127                         \[\[(!?)        # directive open; 2: optional prefix
1128                         ([-\w]+)        # 3: command
1129                         \s+
1130                         (               # 4: the parameters..
1131                                 (?:
1132                                         (?:[-\w]+=)?            # named parameter key?
1133                                         (?:
1134                                                 """.*?"""       # triple-quoted value
1135                                                 |
1136                                                 "[^"]+"         # single-quoted value
1137                                                 |
1138                                                 [^\s\]]+        # unquoted value
1139                                         )
1140                                         \s*                     # whitespace or end
1141                                                                 # of directive
1142                                 )
1143                         *)              # 0 or more parameters
1144                         \]\]            # directive closed
1145                 }sx;
1146         }
1147
1148         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1149         return $content;
1150 } #}}}
1151
1152 sub filter ($$$) { #{{{
1153         my $page=shift;
1154         my $destpage=shift;
1155         my $content=shift;
1156
1157         run_hooks(filter => sub {
1158                 $content=shift->(page => $page, destpage => $destpage, 
1159                         content => $content);
1160         });
1161
1162         return $content;
1163 } #}}}
1164
1165 sub indexlink () { #{{{
1166         return "<a href=\"$config{url}\">$config{wikiname}</a>";
1167 } #}}}
1168
1169 my $wikilock;
1170
1171 sub lockwiki (;$) { #{{{
1172         my $wait=@_ ? shift : 1;
1173         # Take an exclusive lock on the wiki to prevent multiple concurrent
1174         # run issues. The lock will be dropped on program exit.
1175         if (! -d $config{wikistatedir}) {
1176                 mkdir($config{wikistatedir});
1177         }
1178         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1179                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1180         if (! flock($wikilock, 2 | 4)) { # LOCK_EX | LOCK_NB
1181                 if ($wait) {
1182                         debug("wiki seems to be locked, waiting for lock");
1183                         my $wait=600; # arbitrary, but don't hang forever to 
1184                                       # prevent process pileup
1185                         for (1..$wait) {
1186                                 return if flock($wikilock, 2 | 4);
1187                                 sleep 1;
1188                         }
1189                         error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
1190                 }
1191                 else {
1192                         return 0;
1193                 }
1194         }
1195         return 1;
1196 } #}}}
1197
1198 sub unlockwiki () { #{{{
1199         return close($wikilock) if $wikilock;
1200         return;
1201 } #}}}
1202
1203 my $commitlock;
1204
1205 sub commit_hook_enabled () { #{{{
1206         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1207                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1208         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1209                 close($commitlock) || error("failed closing commitlock: $!");
1210                 return 0;
1211         }
1212         close($commitlock) || error("failed closing commitlock: $!");
1213         return 1;
1214 } #}}}
1215
1216 sub disable_commit_hook () { #{{{
1217         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1218                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1219         if (! flock($commitlock, 2)) { # LOCK_EX
1220                 error("failed to get commit lock");
1221         }
1222         return 1;
1223 } #}}}
1224
1225 sub enable_commit_hook () { #{{{
1226         return close($commitlock) if $commitlock;
1227         return;
1228 } #}}}
1229
1230 sub loadindex () { #{{{
1231         %oldrenderedfiles=%pagectime=();
1232         if (! $config{rebuild}) {
1233                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1234                 %destsources=%renderedfiles=%pagecase=%pagestate=();
1235         }
1236         my $in;
1237         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1238                 if (-e "$config{wikistatedir}/index") {
1239                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1240                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1241                 }
1242                 else {
1243                         return;
1244                 }
1245         }
1246         my $ret=Storable::fd_retrieve($in);
1247         if (! defined $ret) {
1248                 return 0;
1249         }
1250         my %index=%$ret;
1251         foreach my $src (keys %index) {
1252                 my %d=%{$index{$src}};
1253                 my $page=pagename($src);
1254                 $pagectime{$page}=$d{ctime};
1255                 if (! $config{rebuild}) {
1256                         $pagesources{$page}=$src;
1257                         $pagemtime{$page}=$d{mtime};
1258                         $renderedfiles{$page}=$d{dest};
1259                         if (exists $d{links} && ref $d{links}) {
1260                                 $links{$page}=$d{links};
1261                                 $oldlinks{$page}=[@{$d{links}}];
1262                         }
1263                         if (exists $d{depends}) {
1264                                 $depends{$page}=$d{depends};
1265                         }
1266                         if (exists $d{state}) {
1267                                 $pagestate{$page}=$d{state};
1268                         }
1269                 }
1270                 $oldrenderedfiles{$page}=[@{$d{dest}}];
1271         }
1272         foreach my $page (keys %pagesources) {
1273                 $pagecase{lc $page}=$page;
1274         }
1275         foreach my $page (keys %renderedfiles) {
1276                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1277         }
1278         return close($in);
1279 } #}}}
1280
1281 sub saveindex () { #{{{
1282         run_hooks(savestate => sub { shift->() });
1283
1284         my %hookids;
1285         foreach my $type (keys %hooks) {
1286                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1287         }
1288         my @hookids=keys %hookids;
1289
1290         if (! -d $config{wikistatedir}) {
1291                 mkdir($config{wikistatedir});
1292         }
1293         my $newfile="$config{wikistatedir}/indexdb.new";
1294         my $cleanup = sub { unlink($newfile) };
1295         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1296         my %index;
1297         foreach my $page (keys %pagemtime) {
1298                 next unless $pagemtime{$page};
1299                 my $src=$pagesources{$page};
1300
1301                 $index{$src}={
1302                         ctime => $pagectime{$page},
1303                         mtime => $pagemtime{$page},
1304                         dest => $renderedfiles{$page},
1305                         links => $links{$page},
1306                 };
1307
1308                 if (exists $depends{$page}) {
1309                         $index{$src}{depends} = $depends{$page};
1310                 }
1311
1312                 if (exists $pagestate{$page}) {
1313                         foreach my $id (@hookids) {
1314                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1315                                         $index{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1316                                 }
1317                         }
1318                 }
1319         }
1320         my $ret=Storable::nstore_fd(\%index, $out);
1321         return if ! defined $ret || ! $ret;
1322         close $out || error("failed saving to $newfile: $!", $cleanup);
1323         rename($newfile, "$config{wikistatedir}/indexdb") ||
1324                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1325         
1326         return 1;
1327 } #}}}
1328
1329 sub template_file ($) { #{{{
1330         my $template=shift;
1331
1332         foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1333                 return "$dir/$template" if -e "$dir/$template";
1334         }
1335         return;
1336 } #}}}
1337
1338 sub template_params (@) { #{{{
1339         my $filename=template_file(shift);
1340
1341         if (! defined $filename) {
1342                 return if wantarray;
1343                 return "";
1344         }
1345
1346         my @ret=(
1347                 filter => sub {
1348                         my $text_ref = shift;
1349                         ${$text_ref} = decode_utf8(${$text_ref});
1350                 },
1351                 filename => $filename,
1352                 loop_context_vars => 1,
1353                 die_on_bad_params => 0,
1354                 @_
1355         );
1356         return wantarray ? @ret : {@ret};
1357 } #}}}
1358
1359 sub template ($;@) { #{{{
1360         require HTML::Template;
1361         return HTML::Template->new(template_params(@_));
1362 } #}}}
1363
1364 sub misctemplate ($$;@) { #{{{
1365         my $title=shift;
1366         my $pagebody=shift;
1367         
1368         my $template=template("misc.tmpl");
1369         $template->param(
1370                 title => $title,
1371                 indexlink => indexlink(),
1372                 wikiname => $config{wikiname},
1373                 pagebody => $pagebody,
1374                 baseurl => baseurl(),
1375                 @_,
1376         );
1377         run_hooks(pagetemplate => sub {
1378                 shift->(page => "", destpage => "", template => $template);
1379         });
1380         return $template->output;
1381 }#}}}
1382
1383 sub hook (@) { # {{{
1384         my %param=@_;
1385         
1386         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1387                 error 'hook requires type, call, and id parameters';
1388         }
1389
1390         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1391         
1392         $hooks{$param{type}}{$param{id}}=\%param;
1393         return 1;
1394 } # }}}
1395
1396 sub run_hooks ($$) { # {{{
1397         # Calls the given sub for each hook of the given type,
1398         # passing it the hook function to call.
1399         my $type=shift;
1400         my $sub=shift;
1401
1402         if (exists $hooks{$type}) {
1403                 my @deferred;
1404                 foreach my $id (keys %{$hooks{$type}}) {
1405                         if ($hooks{$type}{$id}{last}) {
1406                                 push @deferred, $id;
1407                                 next;
1408                         }
1409                         $sub->($hooks{$type}{$id}{call});
1410                 }
1411                 foreach my $id (@deferred) {
1412                         $sub->($hooks{$type}{$id}{call});
1413                 }
1414         }
1415
1416         return 1;
1417 } #}}}
1418
1419 sub globlist_to_pagespec ($) { #{{{
1420         my @globlist=split(' ', shift);
1421
1422         my (@spec, @skip);
1423         foreach my $glob (@globlist) {
1424                 if ($glob=~/^!(.*)/) {
1425                         push @skip, $glob;
1426                 }
1427                 else {
1428                         push @spec, $glob;
1429                 }
1430         }
1431
1432         my $spec=join(' or ', @spec);
1433         if (@skip) {
1434                 my $skip=join(' and ', @skip);
1435                 if (length $spec) {
1436                         $spec="$skip and ($spec)";
1437                 }
1438                 else {
1439                         $spec=$skip;
1440                 }
1441         }
1442         return $spec;
1443 } #}}}
1444
1445 sub is_globlist ($) { #{{{
1446         my $s=shift;
1447         return ( $s =~ /[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or" );
1448 } #}}}
1449
1450 sub safequote ($) { #{{{
1451         my $s=shift;
1452         $s=~s/[{}]//g;
1453         return "q{$s}";
1454 } #}}}
1455
1456 sub add_depends ($$) { #{{{
1457         my $page=shift;
1458         my $pagespec=shift;
1459         
1460         return unless pagespec_valid($pagespec);
1461
1462         if (! exists $depends{$page}) {
1463                 $depends{$page}=$pagespec;
1464         }
1465         else {
1466                 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1467         }
1468
1469         return 1;
1470 } # }}}
1471
1472 sub file_pruned ($$) { #{{{
1473         require File::Spec;
1474         my $file=File::Spec->canonpath(shift);
1475         my $base=File::Spec->canonpath(shift);
1476         $file =~ s#^\Q$base\E/+##;
1477
1478         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1479         return $file =~ m/$regexp/ && $file ne $base;
1480 } #}}}
1481
1482 sub gettext { #{{{
1483         # Only use gettext in the rare cases it's needed.
1484         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1485             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1486             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1487                 if (! $gettext_obj) {
1488                         $gettext_obj=eval q{
1489                                 use Locale::gettext q{textdomain};
1490                                 Locale::gettext->domain('ikiwiki')
1491                         };
1492                         if ($@) {
1493                                 print STDERR "$@";
1494                                 $gettext_obj=undef;
1495                                 return shift;
1496                         }
1497                 }
1498                 return $gettext_obj->get(shift);
1499         }
1500         else {
1501                 return shift;
1502         }
1503 } #}}}
1504
1505 sub yesno ($) { #{{{
1506         my $val=shift;
1507
1508         return (defined $val && lc($val) eq gettext("yes"));
1509 } #}}}
1510
1511 sub pagespec_merge ($$) { #{{{
1512         my $a=shift;
1513         my $b=shift;
1514
1515         return $a if $a eq $b;
1516
1517         # Support for old-style GlobLists.
1518         if (is_globlist($a)) {
1519                 $a=globlist_to_pagespec($a);
1520         }
1521         if (is_globlist($b)) {
1522                 $b=globlist_to_pagespec($b);
1523         }
1524
1525         return "($a) or ($b)";
1526 } #}}}
1527
1528 sub pagespec_translate ($) { #{{{
1529         my $spec=shift;
1530
1531         # Support for old-style GlobLists.
1532         if (is_globlist($spec)) {
1533                 $spec=globlist_to_pagespec($spec);
1534         }
1535
1536         # Convert spec to perl code.
1537         my $code="";
1538         while ($spec=~m{
1539                 \s*             # ignore whitespace
1540                 (               # 1: match a single word
1541                         \!              # !
1542                 |
1543                         \(              # (
1544                 |
1545                         \)              # )
1546                 |
1547                         \w+\([^\)]*\)   # command(params)
1548                 |
1549                         [^\s()]+        # any other text
1550                 )
1551                 \s*             # ignore whitespace
1552         }igx) {
1553                 my $word=$1;
1554                 if (lc $word eq 'and') {
1555                         $code.=' &&';
1556                 }
1557                 elsif (lc $word eq 'or') {
1558                         $code.=' ||';
1559                 }
1560                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1561                         $code.=' '.$word;
1562                 }
1563                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1564                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1565                                 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1566                         }
1567                         else {
1568                                 $code.=' 0';
1569                         }
1570                 }
1571                 else {
1572                         $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1573                 }
1574         }
1575
1576         if (! length $code) {
1577                 $code=0;
1578         }
1579
1580         no warnings;
1581         return eval 'sub { my $page=shift; '.$code.' }';
1582 } #}}}
1583
1584 sub pagespec_match ($$;@) { #{{{
1585         my $page=shift;
1586         my $spec=shift;
1587         my @params=@_;
1588
1589         # Backwards compatability with old calling convention.
1590         if (@params == 1) {
1591                 unshift @params, 'location';
1592         }
1593
1594         my $sub=pagespec_translate($spec);
1595         return IkiWiki::FailReason->new("syntax error in pagespec \"$spec\"") if $@;
1596         return $sub->($page, @params);
1597 } #}}}
1598
1599 sub pagespec_valid ($) { #{{{
1600         my $spec=shift;
1601
1602         my $sub=pagespec_translate($spec);
1603         return ! $@;
1604 } #}}}
1605         
1606 sub glob2re ($) { #{{{
1607         my $re=quotemeta(shift);
1608         $re=~s/\\\*/.*/g;
1609         $re=~s/\\\?/./g;
1610         return $re;
1611 } #}}}
1612
1613 package IkiWiki::FailReason;
1614
1615 use overload ( #{{{
1616         '""'    => sub { ${$_[0]} },
1617         '0+'    => sub { 0 },
1618         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1619         fallback => 1,
1620 ); #}}}
1621
1622 sub new { #{{{
1623         my $class = shift;
1624         my $value = shift;
1625         return bless \$value, $class;
1626 } #}}}
1627
1628 package IkiWiki::SuccessReason;
1629
1630 use overload ( #{{{
1631         '""'    => sub { ${$_[0]} },
1632         '0+'    => sub { 1 },
1633         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
1634         fallback => 1,
1635 ); #}}}
1636
1637 sub new { #{{{
1638         my $class = shift;
1639         my $value = shift;
1640         return bless \$value, $class;
1641 }; #}}}
1642
1643 package IkiWiki::PageSpec;
1644
1645 sub match_glob ($$;@) { #{{{
1646         my $page=shift;
1647         my $glob=shift;
1648         my %params=@_;
1649         
1650         my $from=exists $params{location} ? $params{location} : '';
1651         
1652         # relative matching
1653         if ($glob =~ m!^\./!) {
1654                 $from=~s#/?[^/]+$##;
1655                 $glob=~s#^\./##;
1656                 $glob="$from/$glob" if length $from;
1657         }
1658
1659         my $regexp=IkiWiki::glob2re($glob);
1660         if ($page=~/^$regexp$/i) {
1661                 if (! IkiWiki::isinternal($page) || $params{internal}) {
1662                         return IkiWiki::SuccessReason->new("$glob matches $page");
1663                 }
1664                 else {
1665                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1666                 }
1667         }
1668         else {
1669                 return IkiWiki::FailReason->new("$glob does not match $page");
1670         }
1671 } #}}}
1672
1673 sub match_internal ($$;@) { #{{{
1674         return match_glob($_[0], $_[1], @_, internal => 1)
1675 } #}}}
1676
1677 sub match_link ($$;@) { #{{{
1678         my $page=shift;
1679         my $link=lc(shift);
1680         my %params=@_;
1681
1682         my $from=exists $params{location} ? $params{location} : '';
1683
1684         # relative matching
1685         if ($link =~ m!^\.! && defined $from) {
1686                 $from=~s#/?[^/]+$##;
1687                 $link=~s#^\./##;
1688                 $link="$from/$link" if length $from;
1689         }
1690
1691         my $links = $IkiWiki::links{$page};
1692         return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1693         my $bestlink = IkiWiki::bestlink($from, $link);
1694         foreach my $p (@{$links}) {
1695                 if (length $bestlink) {
1696                         return IkiWiki::SuccessReason->new("$page links to $link")
1697                                 if $bestlink eq IkiWiki::bestlink($page, $p);
1698                 }
1699                 else {
1700                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1701                                 if match_glob($p, $link, %params);
1702                 }
1703         }
1704         return IkiWiki::FailReason->new("$page does not link to $link");
1705 } #}}}
1706
1707 sub match_backlink ($$;@) { #{{{
1708         return match_link($_[1], $_[0], @_);
1709 } #}}}
1710
1711 sub match_created_before ($$;@) { #{{{
1712         my $page=shift;
1713         my $testpage=shift;
1714
1715         if (exists $IkiWiki::pagectime{$testpage}) {
1716                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
1717                         return IkiWiki::SuccessReason->new("$page created before $testpage");
1718                 }
1719                 else {
1720                         return IkiWiki::FailReason->new("$page not created before $testpage");
1721                 }
1722         }
1723         else {
1724                 return IkiWiki::FailReason->new("$testpage has no ctime");
1725         }
1726 } #}}}
1727
1728 sub match_created_after ($$;@) { #{{{
1729         my $page=shift;
1730         my $testpage=shift;
1731
1732         if (exists $IkiWiki::pagectime{$testpage}) {
1733                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
1734                         return IkiWiki::SuccessReason->new("$page created after $testpage");
1735                 }
1736                 else {
1737                         return IkiWiki::FailReason->new("$page not created after $testpage");
1738                 }
1739         }
1740         else {
1741                 return IkiWiki::FailReason->new("$testpage has no ctime");
1742         }
1743 } #}}}
1744
1745 sub match_creation_day ($$;@) { #{{{
1746         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
1747                 return IkiWiki::SuccessReason->new('creation_day matched');
1748         }
1749         else {
1750                 return IkiWiki::FailReason->new('creation_day did not match');
1751         }
1752 } #}}}
1753
1754 sub match_creation_month ($$;@) { #{{{
1755         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
1756                 return IkiWiki::SuccessReason->new('creation_month matched');
1757         }
1758         else {
1759                 return IkiWiki::FailReason->new('creation_month did not match');
1760         }
1761 } #}}}
1762
1763 sub match_creation_year ($$;@) { #{{{
1764         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
1765                 return IkiWiki::SuccessReason->new('creation_year matched');
1766         }
1767         else {
1768                 return IkiWiki::FailReason->new('creation_year did not match');
1769         }
1770 } #}}}
1771
1772 1