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