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