]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki.pm
update comment re openid library version
[git.ikiwiki.info.git] / IkiWiki.pm
1 #!/usr/bin/perl
3 package IkiWiki;
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};
14 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
15             %pagestate %wikistate %renderedfiles %oldrenderedfiles
16             %pagesources %destsources %depends %depends_simple %hooks
17             %forcerebuild %loaded_plugins};
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error template htmlpage deptype
21                  add_depends pagespec_match pagespec_match_list bestlink
22                  htmllink readfile writefile pagetype srcfile pagename
23                  displaytime will_render gettext urlto targetpage
24                  add_underlay pagetitle titlepage linkpage newpagefile
25                  inject add_link
26                  %config %links %pagestate %wikistate %renderedfiles
27                  %pagesources %destsources);
28 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
29 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
30 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
32 # Page dependency types.
33 our $DEPEND_CONTENT=1;
34 our $DEPEND_PRESENCE=2;
35 our $DEPEND_LINKS=4;
37 # Optimisation.
38 use Memoize;
39 memoize("abs2rel");
40 memoize("pagespec_translate");
41 memoize("template_file");
43 sub getsetup () {
44         wikiname => {
45                 type => "string",
46                 default => "wiki",
47                 description => "name of the wiki",
48                 safe => 1,
49                 rebuild => 1,
50         },
51         adminemail => {
52                 type => "string",
53                 default => undef,
54                 example => 'me@example.com',
55                 description => "contact email for wiki",
56                 safe => 1,
57                 rebuild => 0,
58         },
59         adminuser => {
60                 type => "string",
61                 default => [],
62                 description => "users who are wiki admins",
63                 safe => 1,
64                 rebuild => 0,
65         },
66         banned_users => {
67                 type => "string",
68                 default => [],
69                 description => "users who are banned from the wiki",
70                 safe => 1,
71                 rebuild => 0,
72         },
73         srcdir => {
74                 type => "string",
75                 default => undef,
76                 example => "$ENV{HOME}/wiki",
77                 description => "where the source of the wiki is located",
78                 safe => 0, # path
79                 rebuild => 1,
80         },
81         destdir => {
82                 type => "string",
83                 default => undef,
84                 example => "/var/www/wiki",
85                 description => "where to build the wiki",
86                 safe => 0, # path
87                 rebuild => 1,
88         },
89         url => {
90                 type => "string",
91                 default => '',
92                 example => "http://example.com/wiki",
93                 description => "base url to the wiki",
94                 safe => 1,
95                 rebuild => 1,
96         },
97         cgiurl => {
98                 type => "string",
99                 default => '',
100                 example => "http://example.com/wiki/ikiwiki.cgi",
101                 description => "url to the ikiwiki.cgi",
102                 safe => 1,
103                 rebuild => 1,
104         },
105         cgi_wrapper => {
106                 type => "string",
107                 default => '',
108                 example => "/var/www/wiki/ikiwiki.cgi",
109                 description => "filename of cgi wrapper to generate",
110                 safe => 0, # file
111                 rebuild => 0,
112         },
113         cgi_wrappermode => {
114                 type => "string",
115                 default => '06755',
116                 description => "mode for cgi_wrapper (can safely be made suid)",
117                 safe => 0,
118                 rebuild => 0,
119         },
120         rcs => {
121                 type => "string",
122                 default => '',
123                 description => "rcs backend to use",
124                 safe => 0, # don't allow overriding
125                 rebuild => 0,
126         },
127         default_plugins => {
128                 type => "internal",
129                 default => [qw{mdwn link inline meta htmlscrubber passwordauth
130                                 openid signinedit lockedit conditional
131                                 recentchanges parentlinks editpage}],
132                 description => "plugins to enable by default",
133                 safe => 0,
134                 rebuild => 1,
135         },
136         add_plugins => {
137                 type => "string",
138                 default => [],
139                 description => "plugins to add to the default configuration",
140                 safe => 1,
141                 rebuild => 1,
142         },
143         disable_plugins => {
144                 type => "string",
145                 default => [],
146                 description => "plugins to disable",
147                 safe => 1,
148                 rebuild => 1,
149         },
150         templatedir => {
151                 type => "string",
152                 default => "$installdir/share/ikiwiki/templates",
153                 description => "location of template files",
154                 advanced => 1,
155                 safe => 0, # path
156                 rebuild => 1,
157         },
158         templatedirs => {
159                 type => "internal",
160                 default => [],
161                 description => "additional directories containing template files",
162                 safe => 0,
163                 rebuild => 0,
164         },
165         underlaydir => {
166                 type => "string",
167                 default => "$installdir/share/ikiwiki/basewiki",
168                 description => "base wiki source location",
169                 advanced => 1,
170                 safe => 0, # path
171                 rebuild => 0,
172         },
173         underlaydirbase => {
174                 type => "internal",
175                 default => "$installdir/share/ikiwiki",
176                 description => "parent directory containing additional underlays",
177                 safe => 0,
178                 rebuild => 0,
179         },
180         wrappers => {
181                 type => "internal",
182                 default => [],
183                 description => "wrappers to generate",
184                 safe => 0,
185                 rebuild => 0,
186         },
187         underlaydirs => {
188                 type => "internal",
189                 default => [],
190                 description => "additional underlays to use",
191                 safe => 0,
192                 rebuild => 0,
193         },
194         verbose => {
195                 type => "boolean",
196                 example => 1,
197                 description => "display verbose messages?",
198                 safe => 1,
199                 rebuild => 0,
200         },
201         syslog => {
202                 type => "boolean",
203                 example => 1,
204                 description => "log to syslog?",
205                 safe => 1,
206                 rebuild => 0,
207         },
208         usedirs => {
209                 type => "boolean",
210                 default => 1,
211                 description => "create output files named page/index.html?",
212                 safe => 0, # changing requires manual transition
213                 rebuild => 1,
214         },
215         prefix_directives => {
216                 type => "boolean",
217                 default => 1,
218                 description => "use '!'-prefixed preprocessor directives?",
219                 safe => 0, # changing requires manual transition
220                 rebuild => 1,
221         },
222         indexpages => {
223                 type => "boolean",
224                 default => 0,
225                 description => "use page/index.mdwn source files",
226                 safe => 1,
227                 rebuild => 1,
228         },
229         discussion => {
230                 type => "boolean",
231                 default => 1,
232                 description => "enable Discussion pages?",
233                 safe => 1,
234                 rebuild => 1,
235         },
236         discussionpage => {
237                 type => "string",
238                 default => gettext("Discussion"),
239                 description => "name of Discussion pages",
240                 safe => 1,
241                 rebuild => 1,
242         },
243         sslcookie => {
244                 type => "boolean",
245                 default => 0,
246                 description => "only send cookies over SSL connections?",
247                 advanced => 1,
248                 safe => 1,
249                 rebuild => 0,
250         },
251         default_pageext => {
252                 type => "string",
253                 default => "mdwn",
254                 description => "extension to use for new pages",
255                 safe => 0, # not sanitized
256                 rebuild => 0,
257         },
258         htmlext => {
259                 type => "string",
260                 default => "html",
261                 description => "extension to use for html files",
262                 safe => 0, # not sanitized
263                 rebuild => 1,
264         },
265         timeformat => {
266                 type => "string",
267                 default => '%c',
268                 description => "strftime format string to display date",
269                 advanced => 1,
270                 safe => 1,
271                 rebuild => 1,
272         },
273         locale => {
274                 type => "string",
275                 default => undef,
276                 example => "en_US.UTF-8",
277                 description => "UTF-8 locale to use",
278                 advanced => 1,
279                 safe => 0,
280                 rebuild => 1,
281         },
282         userdir => {
283                 type => "string",
284                 default => "",
285                 example => "users",
286                 description => "put user pages below specified page",
287                 safe => 1,
288                 rebuild => 1,
289         },
290         numbacklinks => {
291                 type => "integer",
292                 default => 10,
293                 description => "how many backlinks to show before hiding excess (0 to show all)",
294                 safe => 1,
295                 rebuild => 1,
296         },
297         hardlink => {
298                 type => "boolean",
299                 default => 0,
300                 description => "attempt to hardlink source files? (optimisation for large files)",
301                 advanced => 1,
302                 safe => 0, # paranoia
303                 rebuild => 0,
304         },
305         umask => {
306                 type => "integer",
307                 example => "022",
308                 description => "force ikiwiki to use a particular umask",
309                 advanced => 1,
310                 safe => 0, # paranoia
311                 rebuild => 0,
312         },
313         wrappergroup => {
314                 type => "string",
315                 example => "ikiwiki",
316                 description => "group for wrappers to run in",
317                 advanced => 1,
318                 safe => 0, # paranoia
319                 rebuild => 0,
320         },
321         libdir => {
322                 type => "string",
323                 default => "",
324                 example => "$ENV{HOME}/.ikiwiki/",
325                 description => "extra library and plugin directory",
326                 advanced => 1,
327                 safe => 0, # directory
328                 rebuild => 0,
329         },
330         ENV => {
331                 type => "string", 
332                 default => {},
333                 description => "environment variables",
334                 safe => 0, # paranoia
335                 rebuild => 0,
336         },
337         exclude => {
338                 type => "string",
339                 default => undef,
340                 example => '\.wav$',
341                 description => "regexp of source files to ignore",
342                 advanced => 1,
343                 safe => 0, # regexp
344                 rebuild => 1,
345         },
346         wiki_file_prune_regexps => {
347                 type => "internal",
348                 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
349                         qr/\.x?html?$/, qr/\.ikiwiki-new$/,
350                         qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
351                         qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
352                         qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
353                 description => "regexps of source files to ignore",
354                 safe => 0,
355                 rebuild => 1,
356         },
357         wiki_file_chars => {
358                 type => "string",
359                 description => "specifies the characters that are allowed in source filenames",
360                 default => "-[:alnum:]+/.:_",
361                 safe => 0,
362                 rebuild => 1,
363         },
364         wiki_file_regexp => {
365                 type => "internal",
366                 description => "regexp of legal source files",
367                 safe => 0,
368                 rebuild => 1,
369         },
370         web_commit_regexp => {
371                 type => "internal",
372                 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
373                 description => "regexp to parse web commits from logs",
374                 safe => 0,
375                 rebuild => 0,
376         },
377         cgi => {
378                 type => "internal",
379                 default => 0,
380                 description => "run as a cgi",
381                 safe => 0,
382                 rebuild => 0,
383         },
384         cgi_disable_uploads => {
385                 type => "internal",
386                 default => 1,
387                 description => "whether CGI should accept file uploads",
388                 safe => 0,
389                 rebuild => 0,
390         },
391         post_commit => {
392                 type => "internal",
393                 default => 0,
394                 description => "run as a post-commit hook",
395                 safe => 0,
396                 rebuild => 0,
397         },
398         rebuild => {
399                 type => "internal",
400                 default => 0,
401                 description => "running in rebuild mode",
402                 safe => 0,
403                 rebuild => 0,
404         },
405         setup => {
406                 type => "internal",
407                 default => undef,
408                 description => "running in setup mode",
409                 safe => 0,
410                 rebuild => 0,
411         },
412         refresh => {
413                 type => "internal",
414                 default => 0,
415                 description => "running in refresh mode",
416                 safe => 0,
417                 rebuild => 0,
418         },
419         test_receive => {
420                 type => "internal",
421                 default => 0,
422                 description => "running in receive test mode",
423                 safe => 0,
424                 rebuild => 0,
425         },
426         getctime => {
427                 type => "internal",
428                 default => 0,
429                 description => "running in getctime mode",
430                 safe => 0,
431                 rebuild => 0,
432         },
433         w3mmode => {
434                 type => "internal",
435                 default => 0,
436                 description => "running in w3mmode",
437                 safe => 0,
438                 rebuild => 0,
439         },
440         wikistatedir => {
441                 type => "internal",
442                 default => undef,
443                 description => "path to the .ikiwiki directory holding ikiwiki state",
444                 safe => 0,
445                 rebuild => 0,
446         },
447         setupfile => {
448                 type => "internal",
449                 default => undef,
450                 description => "path to setup file",
451                 safe => 0,
452                 rebuild => 0,
453         },
454         allow_symlinks_before_srcdir => {
455                 type => "boolean",
456                 default => 0,
457                 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
458                 safe => 0,
459                 rebuild => 0,
460         },
463 sub defaultconfig () {
464         my %s=getsetup();
465         my @ret;
466         foreach my $key (keys %s) {
467                 push @ret, $key, $s{$key}->{default};
468         }
469         use Data::Dumper;
470         return @ret;
473 sub checkconfig () {
474         # locale stuff; avoid LC_ALL since it overrides everything
475         if (defined $ENV{LC_ALL}) {
476                 $ENV{LANG} = $ENV{LC_ALL};
477                 delete $ENV{LC_ALL};
478         }
479         if (defined $config{locale}) {
480                 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
481                         $ENV{LANG}=$config{locale};
482                         define_gettext();
483                 }
484         }
485                 
486         if (! defined $config{wiki_file_regexp}) {
487                 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
488         }
490         if (ref $config{ENV} eq 'HASH') {
491                 foreach my $val (keys %{$config{ENV}}) {
492                         $ENV{$val}=$config{ENV}{$val};
493                 }
494         }
496         if ($config{w3mmode}) {
497                 eval q{use Cwd q{abs_path}};
498                 error($@) if $@;
499                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
500                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
501                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
502                         unless $config{cgiurl} =~ m!file:///!;
503                 $config{url}="file://".$config{destdir};
504         }
506         if ($config{cgi} && ! length $config{url}) {
507                 error(gettext("Must specify url to wiki with --url when using --cgi"));
508         }
509         
510         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
511                 unless exists $config{wikistatedir} && defined $config{wikistatedir};
513         if (defined $config{umask}) {
514                 umask(possibly_foolish_untaint($config{umask}));
515         }
517         run_hooks(checkconfig => sub { shift->() });
519         return 1;
522 sub listplugins () {
523         my %ret;
525         foreach my $dir (@INC, $config{libdir}) {
526                 next unless defined $dir && length $dir;
527                 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
528                         my ($plugin)=$file=~/.*\/(.*)\.pm$/;
529                         $ret{$plugin}=1;
530                 }
531         }
532         foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
533                 next unless defined $dir && length $dir;
534                 foreach my $file (glob("$dir/plugins/*")) {
535                         $ret{basename($file)}=1 if -x $file;
536                 }
537         }
539         return keys %ret;
542 sub loadplugins () {
543         if (defined $config{libdir} && length $config{libdir}) {
544                 unshift @INC, possibly_foolish_untaint($config{libdir});
545         }
547         foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
548                 loadplugin($plugin);
549         }
550         
551         if ($config{rcs}) {
552                 if (exists $hooks{rcs}) {
553                         error(gettext("cannot use multiple rcs plugins"));
554                 }
555                 loadplugin($config{rcs});
556         }
557         if (! exists $hooks{rcs}) {
558                 loadplugin("norcs");
559         }
561         run_hooks(getopt => sub { shift->() });
562         if (grep /^-/, @ARGV) {
563                 print STDERR "Unknown option (or missing parameter): $_\n"
564                         foreach grep /^-/, @ARGV;
565                 usage();
566         }
568         return 1;
571 sub loadplugin ($) {
572         my $plugin=shift;
574         return if grep { $_ eq $plugin} @{$config{disable_plugins}};
576         foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
577                          "$installdir/lib/ikiwiki") {
578                 if (defined $dir && -x "$dir/plugins/$plugin") {
579                         eval { require IkiWiki::Plugin::external };
580                         if ($@) {
581                                 my $reason=$@;
582                                 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
583                         }
584                         import IkiWiki::Plugin::external "$dir/plugins/$plugin";
585                         $loaded_plugins{$plugin}=1;
586                         return 1;
587                 }
588         }
590         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
591         eval qq{use $mod};
592         if ($@) {
593                 error("Failed to load plugin $mod: $@");
594         }
595         $loaded_plugins{$plugin}=1;
596         return 1;
599 sub error ($;$) {
600         my $message=shift;
601         my $cleaner=shift;
602         log_message('err' => $message) if $config{syslog};
603         if (defined $cleaner) {
604                 $cleaner->();
605         }
606         die $message."\n";
609 sub debug ($) {
610         return unless $config{verbose};
611         return log_message(debug => @_);
614 my $log_open=0;
615 sub log_message ($$) {
616         my $type=shift;
618         if ($config{syslog}) {
619                 require Sys::Syslog;
620                 if (! $log_open) {
621                         Sys::Syslog::setlogsock('unix');
622                         Sys::Syslog::openlog('ikiwiki', '', 'user');
623                         $log_open=1;
624                 }
625                 return eval {
626                         Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
627                 };
628         }
629         elsif (! $config{cgi}) {
630                 return print "@_\n";
631         }
632         else {
633                 return print STDERR "@_\n";
634         }
637 sub possibly_foolish_untaint ($) {
638         my $tainted=shift;
639         my ($untainted)=$tainted=~/(.*)/s;
640         return $untainted;
643 sub basename ($) {
644         my $file=shift;
646         $file=~s!.*/+!!;
647         return $file;
650 sub dirname ($) {
651         my $file=shift;
653         $file=~s!/*[^/]+$!!;
654         return $file;
657 sub isinternal ($) {
658         my $page=shift;
659         return exists $pagesources{$page} &&
660                 $pagesources{$page} =~ /\._([^.]+)$/;
663 sub pagetype ($) {
664         my $file=shift;
665         
666         if ($file =~ /\.([^.]+)$/) {
667                 return $1 if exists $hooks{htmlize}{$1};
668         }
669         my $base=basename($file);
670         if (exists $hooks{htmlize}{$base} &&
671             $hooks{htmlize}{$base}{noextension}) {
672                 return $base;
673         }
674         return;
677 my %pagename_cache;
679 sub pagename ($) {
680         my $file=shift;
682         if (exists $pagename_cache{$file}) {
683                 return $pagename_cache{$file};
684         }
686         my $type=pagetype($file);
687         my $page=$file;
688         $page=~s/\Q.$type\E*$//
689                 if defined $type && !$hooks{htmlize}{$type}{keepextension}
690                         && !$hooks{htmlize}{$type}{noextension};
691         if ($config{indexpages} && $page=~/(.*)\/index$/) {
692                 $page=$1;
693         }
695         $pagename_cache{$file} = $page;
696         return $page;
699 sub newpagefile ($$) {
700         my $page=shift;
701         my $type=shift;
703         if (! $config{indexpages} || $page eq 'index') {
704                 return $page.".".$type;
705         }
706         else {
707                 return $page."/index.".$type;
708         }
711 sub targetpage ($$;$) {
712         my $page=shift;
713         my $ext=shift;
714         my $filename=shift;
715         
716         if (defined $filename) {
717                 return $page."/".$filename.".".$ext;
718         }
719         elsif (! $config{usedirs} || $page eq 'index') {
720                 return $page.".".$ext;
721         }
722         else {
723                 return $page."/index.".$ext;
724         }
727 sub htmlpage ($) {
728         my $page=shift;
729         
730         return targetpage($page, $config{htmlext});
733 sub srcfile_stat {
734         my $file=shift;
735         my $nothrow=shift;
737         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
738         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
739                 return "$dir/$file", stat(_) if -e "$dir/$file";
740         }
741         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
742         return;
745 sub srcfile ($;$) {
746         return (srcfile_stat(@_))[0];
749 sub add_underlay ($) {
750         my $dir=shift;
752         if ($dir !~ /^\//) {
753                 $dir="$config{underlaydirbase}/$dir";
754         }
756         if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
757                 unshift @{$config{underlaydirs}}, $dir;
758         }
760         return 1;
763 sub readfile ($;$$) {
764         my $file=shift;
765         my $binary=shift;
766         my $wantfd=shift;
768         if (-l $file) {
769                 error("cannot read a symlink ($file)");
770         }
771         
772         local $/=undef;
773         open (my $in, "<", $file) || error("failed to read $file: $!");
774         binmode($in) if ($binary);
775         return \*$in if $wantfd;
776         my $ret=<$in>;
777         # check for invalid utf-8, and toss it back to avoid crashes
778         if (! utf8::valid($ret)) {
779                 $ret=encode_utf8($ret);
780         }
781         close $in || error("failed to read $file: $!");
782         return $ret;
785 sub prep_writefile ($$) {
786         my $file=shift;
787         my $destdir=shift;
788         
789         my $test=$file;
790         while (length $test) {
791                 if (-l "$destdir/$test") {
792                         error("cannot write to a symlink ($test)");
793                 }
794                 $test=dirname($test);
795         }
797         my $dir=dirname("$destdir/$file");
798         if (! -d $dir) {
799                 my $d="";
800                 foreach my $s (split(m!/+!, $dir)) {
801                         $d.="$s/";
802                         if (! -d $d) {
803                                 mkdir($d) || error("failed to create directory $d: $!");
804                         }
805                 }
806         }
808         return 1;
811 sub writefile ($$$;$$) {
812         my $file=shift; # can include subdirs
813         my $destdir=shift; # directory to put file in
814         my $content=shift;
815         my $binary=shift;
816         my $writer=shift;
817         
818         prep_writefile($file, $destdir);
819         
820         my $newfile="$destdir/$file.ikiwiki-new";
821         if (-l $newfile) {
822                 error("cannot write to a symlink ($newfile)");
823         }
824         
825         my $cleanup = sub { unlink($newfile) };
826         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
827         binmode($out) if ($binary);
828         if ($writer) {
829                 $writer->(\*$out, $cleanup);
830         }
831         else {
832                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
833         }
834         close $out || error("failed saving $newfile: $!", $cleanup);
835         rename($newfile, "$destdir/$file") || 
836                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
838         return 1;
841 my %cleared;
842 sub will_render ($$;$) {
843         my $page=shift;
844         my $dest=shift;
845         my $clear=shift;
847         # Important security check.
848         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
849             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
850                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
851         }
853         if (! $clear || $cleared{$page}) {
854                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
855         }
856         else {
857                 foreach my $old (@{$renderedfiles{$page}}) {
858                         delete $destsources{$old};
859                 }
860                 $renderedfiles{$page}=[$dest];
861                 $cleared{$page}=1;
862         }
863         $destsources{$dest}=$page;
865         return 1;
868 sub bestlink ($$) {
869         my $page=shift;
870         my $link=shift;
871         
872         my $cwd=$page;
873         if ($link=~s/^\/+//) {
874                 # absolute links
875                 $cwd="";
876         }
877         $link=~s/\/$//;
879         do {
880                 my $l=$cwd;
881                 $l.="/" if length $l;
882                 $l.=$link;
884                 if (exists $pagesources{$l}) {
885                         return $l;
886                 }
887                 elsif (exists $pagecase{lc $l}) {
888                         return $pagecase{lc $l};
889                 }
890         } while $cwd=~s{/?[^/]+$}{};
892         if (length $config{userdir}) {
893                 my $l = "$config{userdir}/".lc($link);
894                 if (exists $pagesources{$l}) {
895                         return $l;
896                 }
897                 elsif (exists $pagecase{lc $l}) {
898                         return $pagecase{lc $l};
899                 }
900         }
902         #print STDERR "warning: page $page, broken link: $link\n";
903         return "";
906 sub isinlinableimage ($) {
907         my $file=shift;
908         
909         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
912 sub pagetitle ($;$) {
913         my $page=shift;
914         my $unescaped=shift;
916         if ($unescaped) {
917                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
918         }
919         else {
920                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
921         }
923         return $page;
926 sub titlepage ($) {
927         my $title=shift;
928         # support use w/o %config set
929         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
930         $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
931         return $title;
934 sub linkpage ($) {
935         my $link=shift;
936         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
937         $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
938         return $link;
941 sub cgiurl (@) {
942         my %params=@_;
944         return $config{cgiurl}."?".
945                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
948 sub baseurl (;$) {
949         my $page=shift;
951         return "$config{url}/" if ! defined $page;
952         
953         $page=htmlpage($page);
954         $page=~s/[^\/]+$//;
955         $page=~s/[^\/]+\//..\//g;
956         return $page;
959 sub abs2rel ($$) {
960         # Work around very innefficient behavior in File::Spec if abs2rel
961         # is passed two relative paths. It's much faster if paths are
962         # absolute! (Debian bug #376658; fixed in debian unstable now)
963         my $path="/".shift;
964         my $base="/".shift;
966         require File::Spec;
967         my $ret=File::Spec->abs2rel($path, $base);
968         $ret=~s/^// if defined $ret;
969         return $ret;
972 sub displaytime ($;$) {
973         # Plugins can override this function to mark up the time to
974         # display.
975         return '<span class="date">'.formattime(@_).'</span>';
978 sub formattime ($;$) {
979         # Plugins can override this function to format the time.
980         my $time=shift;
981         my $format=shift;
982         if (! defined $format) {
983                 $format=$config{timeformat};
984         }
986         # strftime doesn't know about encodings, so make sure
987         # its output is properly treated as utf8
988         return decode_utf8(POSIX::strftime($format, localtime($time)));
991 sub beautify_urlpath ($) {
992         my $url=shift;
994         # Ensure url is not an empty link, and if necessary,
995         # add ./ to avoid colon confusion.
996         if ($url !~ /^\// && $url !~ /^\.\.?\//) {
997                 $url="./$url";
998         }
1000         if ($config{usedirs}) {
1001                 $url =~ s!/index.$config{htmlext}$!/!;
1002         }
1004         return $url;
1007 sub urlto ($$;$) {
1008         my $to=shift;
1009         my $from=shift;
1010         my $absolute=shift;
1011         
1012         if (! length $to) {
1013                 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1014         }
1016         if (! $destsources{$to}) {
1017                 $to=htmlpage($to);
1018         }
1020         if ($absolute) {
1021                 return $config{url}.beautify_urlpath("/".$to);
1022         }
1024         my $link = abs2rel($to, dirname(htmlpage($from)));
1026         return beautify_urlpath($link);
1029 sub htmllink ($$$;@) {
1030         my $lpage=shift; # the page doing the linking
1031         my $page=shift; # the page that will contain the link (different for inline)
1032         my $link=shift;
1033         my %opts=@_;
1035         $link=~s/\/$//;
1037         my $bestlink;
1038         if (! $opts{forcesubpage}) {
1039                 $bestlink=bestlink($lpage, $link);
1040         }
1041         else {
1042                 $bestlink="$lpage/".lc($link);
1043         }
1045         my $linktext;
1046         if (defined $opts{linktext}) {
1047                 $linktext=$opts{linktext};
1048         }
1049         else {
1050                 $linktext=pagetitle(basename($link));
1051         }
1052         
1053         return "<span class=\"selflink\">$linktext</span>"
1054                 if length $bestlink && $page eq $bestlink &&
1055                    ! defined $opts{anchor};
1056         
1057         if (! $destsources{$bestlink}) {
1058                 $bestlink=htmlpage($bestlink);
1060                 if (! $destsources{$bestlink}) {
1061                         return $linktext unless length $config{cgiurl};
1062                         return "<span class=\"createlink\"><a href=\"".
1063                                 cgiurl(
1064                                         do => "create",
1065                                         page => lc($link),
1066                                         from => $lpage
1067                                 ).
1068                                 "\" rel=\"nofollow\">?</a>$linktext</span>"
1069                 }
1070         }
1071         
1072         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1073         $bestlink=beautify_urlpath($bestlink);
1074         
1075         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1076                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1077         }
1079         if (defined $opts{anchor}) {
1080                 $bestlink.="#".$opts{anchor};
1081         }
1083         my @attrs;
1084         foreach my $attr (qw{rel class title}) {
1085                 if (defined $opts{$attr}) {
1086                         push @attrs, " $attr=\"$opts{$attr}\"";
1087                 }
1088         }
1090         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1093 sub userpage ($) {
1094         my $user=shift;
1095         return length $config{userdir} ? "$config{userdir}/$user" : $user;
1098 sub openiduser ($) {
1099         my $user=shift;
1101         if ($user =~ m!^https?://! &&
1102             eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1103                 my $display;
1105                 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1106                         $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1107                 }
1108                 else {
1109                         # backcompat with old version
1110                         my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1111                         $display=$oid->display;
1112                 }
1114                 # Convert "user.somehost.com" to "user [somehost.com]"
1115                 # (also "user.somehost.co.uk")
1116                 if ($display !~ /\[/) {
1117                         $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1118                 }
1119                 # Convert "http://somehost.com/user" to "user [somehost.com]".
1120                 # (also "https://somehost.com/user/")
1121                 if ($display !~ /\[/) {
1122                         $display=~s/^https?:\/\/(.+)\/([^\/]+)\/?$/$2 [$1]/;
1123                 }
1124                 $display=~s!^https?://!!; # make sure this is removed
1125                 eval q{use CGI 'escapeHTML'};
1126                 error($@) if $@;
1127                 return escapeHTML($display);
1128         }
1129         return;
1132 sub htmlize ($$$$) {
1133         my $page=shift;
1134         my $destpage=shift;
1135         my $type=shift;
1136         my $content=shift;
1137         
1138         my $oneline = $content !~ /\n/;
1140         if (exists $hooks{htmlize}{$type}) {
1141                 $content=$hooks{htmlize}{$type}{call}->(
1142                         page => $page,
1143                         content => $content,
1144                 );
1145         }
1146         else {
1147                 error("htmlization of $type not supported");
1148         }
1150         run_hooks(sanitize => sub {
1151                 $content=shift->(
1152                         page => $page,
1153                         destpage => $destpage,
1154                         content => $content,
1155                 );
1156         });
1157         
1158         if ($oneline) {
1159                 # hack to get rid of enclosing junk added by markdown
1160                 # and other htmlizers
1161                 $content=~s/^<p>//i;
1162                 $content=~s/<\/p>$//i;
1163                 chomp $content;
1164         }
1166         return $content;
1169 sub linkify ($$$) {
1170         my $page=shift;
1171         my $destpage=shift;
1172         my $content=shift;
1174         run_hooks(linkify => sub {
1175                 $content=shift->(
1176                         page => $page,
1177                         destpage => $destpage,
1178                         content => $content,
1179                 );
1180         });
1181         
1182         return $content;
1185 our %preprocessing;
1186 our $preprocess_preview=0;
1187 sub preprocess ($$$;$$) {
1188         my $page=shift; # the page the data comes from
1189         my $destpage=shift; # the page the data will appear in (different for inline)
1190         my $content=shift;
1191         my $scan=shift;
1192         my $preview=shift;
1194         # Using local because it needs to be set within any nested calls
1195         # of this function.
1196         local $preprocess_preview=$preview if defined $preview;
1198         my $handle=sub {
1199                 my $escape=shift;
1200                 my $prefix=shift;
1201                 my $command=shift;
1202                 my $params=shift;
1203                 $params="" if ! defined $params;
1205                 if (length $escape) {
1206                         return "[[$prefix$command $params]]";
1207                 }
1208                 elsif (exists $hooks{preprocess}{$command}) {
1209                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1210                         # Note: preserve order of params, some plugins may
1211                         # consider it significant.
1212                         my @params;
1213                         while ($params =~ m{
1214                                 (?:([-\w]+)=)?          # 1: named parameter key?
1215                                 (?:
1216                                         """(.*?)"""     # 2: triple-quoted value
1217                                 |
1218                                         "([^"]+)"       # 3: single-quoted value
1219                                 |
1220                                         (\S+)           # 4: unquoted value
1221                                 )
1222                                 (?:\s+|$)               # delimiter to next param
1223                         }sgx) {
1224                                 my $key=$1;
1225                                 my $val;
1226                                 if (defined $2) {
1227                                         $val=$2;
1228                                         $val=~s/\r\n/\n/mg;
1229                                         $val=~s/^\n+//g;
1230                                         $val=~s/\n+$//g;
1231                                 }
1232                                 elsif (defined $3) {
1233                                         $val=$3;
1234                                 }
1235                                 elsif (defined $4) {
1236                                         $val=$4;
1237                                 }
1239                                 if (defined $key) {
1240                                         push @params, $key, $val;
1241                                 }
1242                                 else {
1243                                         push @params, $val, '';
1244                                 }
1245                         }
1246                         if ($preprocessing{$page}++ > 3) {
1247                                 # Avoid loops of preprocessed pages preprocessing
1248                                 # other pages that preprocess them, etc.
1249                                 return "[[!$command <span class=\"error\">".
1250                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1251                                                 $page, $preprocessing{$page}).
1252                                         "</span>]]";
1253                         }
1254                         my $ret;
1255                         if (! $scan) {
1256                                 $ret=eval {
1257                                         $hooks{preprocess}{$command}{call}->(
1258                                                 @params,
1259                                                 page => $page,
1260                                                 destpage => $destpage,
1261                                                 preview => $preprocess_preview,
1262                                         );
1263                                 };
1264                                 if ($@) {
1265                                         my $error=$@;
1266                                         chomp $error;
1267                                         $ret="[[!$command <span class=\"error\">".
1268                                                 gettext("Error").": $error"."</span>]]";
1269                                 }
1270                         }
1271                         else {
1272                                 # use void context during scan pass
1273                                 eval {
1274                                         $hooks{preprocess}{$command}{call}->(
1275                                                 @params,
1276                                                 page => $page,
1277                                                 destpage => $destpage,
1278                                                 preview => $preprocess_preview,
1279                                         );
1280                                 };
1281                                 $ret="";
1282                         }
1283                         $preprocessing{$page}--;
1284                         return $ret;
1285                 }
1286                 else {
1287                         return "[[$prefix$command $params]]";
1288                 }
1289         };
1290         
1291         my $regex;
1292         if ($config{prefix_directives}) {
1293                 $regex = qr{
1294                         (\\?)           # 1: escape?
1295                         \[\[(!)         # directive open; 2: prefix
1296                         ([-\w]+)        # 3: command
1297                         (               # 4: the parameters..
1298                                 \s+     # Must have space if parameters present
1299                                 (?:
1300                                         (?:[-\w]+=)?            # named parameter key?
1301                                         (?:
1302                                                 """.*?"""       # triple-quoted value
1303                                                 |
1304                                                 "[^"]+"         # single-quoted value
1305                                                 |
1306                                                 [^"\s\]]+       # unquoted value
1307                                         )
1308                                         \s*                     # whitespace or end
1309                                                                 # of directive
1310                                 )
1311                         *)?             # 0 or more parameters
1312                         \]\]            # directive closed
1313                 }sx;
1314         }
1315         else {
1316                 $regex = qr{
1317                         (\\?)           # 1: escape?
1318                         \[\[(!?)        # directive open; 2: optional prefix
1319                         ([-\w]+)        # 3: command
1320                         \s+
1321                         (               # 4: the parameters..
1322                                 (?:
1323                                         (?:[-\w]+=)?            # named parameter key?
1324                                         (?:
1325                                                 """.*?"""       # triple-quoted value
1326                                                 |
1327                                                 "[^"]+"         # single-quoted value
1328                                                 |
1329                                                 [^"\s\]]+       # unquoted value
1330                                         )
1331                                         \s*                     # whitespace or end
1332                                                                 # of directive
1333                                 )
1334                         *)              # 0 or more parameters
1335                         \]\]            # directive closed
1336                 }sx;
1337         }
1339         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1340         return $content;
1343 sub filter ($$$) {
1344         my $page=shift;
1345         my $destpage=shift;
1346         my $content=shift;
1348         run_hooks(filter => sub {
1349                 $content=shift->(page => $page, destpage => $destpage, 
1350                         content => $content);
1351         });
1353         return $content;
1356 sub indexlink () {
1357         return "<a href=\"$config{url}\">$config{wikiname}</a>";
1360 sub check_canedit ($$$;$) {
1361         my $page=shift;
1362         my $q=shift;
1363         my $session=shift;
1364         my $nonfatal=shift;
1365         
1366         my $canedit;
1367         run_hooks(canedit => sub {
1368                 return if defined $canedit;
1369                 my $ret=shift->($page, $q, $session);
1370                 if (defined $ret) {
1371                         if ($ret eq "") {
1372                                 $canedit=1;
1373                         }
1374                         elsif (ref $ret eq 'CODE') {
1375                                 $ret->() unless $nonfatal;
1376                                 $canedit=0;
1377                         }
1378                         elsif (defined $ret) {
1379                                 error($ret) unless $nonfatal;
1380                                 $canedit=0;
1381                         }
1382                 }
1383         });
1384         return defined $canedit ? $canedit : 1;
1387 sub check_content (@) {
1388         my %params=@_;
1389         
1390         return 1 if ! exists $hooks{checkcontent}; # optimisation
1392         if (exists $pagesources{$params{page}}) {
1393                 my @diff;
1394                 my %old=map { $_ => 1 }
1395                         split("\n", readfile(srcfile($pagesources{$params{page}})));
1396                 foreach my $line (split("\n", $params{content})) {
1397                         push @diff, $line if ! exists $old{$line};
1398                 }
1399                 $params{diff}=join("\n", @diff);
1400         }
1402         my $ok;
1403         run_hooks(checkcontent => sub {
1404                 return if defined $ok;
1405                 my $ret=shift->(%params);
1406                 if (defined $ret) {
1407                         if ($ret eq "") {
1408                                 $ok=1;
1409                         }
1410                         elsif (ref $ret eq 'CODE') {
1411                                 $ret->() unless $params{nonfatal};
1412                                 $ok=0;
1413                         }
1414                         elsif (defined $ret) {
1415                                 error($ret) unless $params{nonfatal};
1416                                 $ok=0;
1417                         }
1418                 }
1420         });
1421         return defined $ok ? $ok : 1;
1424 my $wikilock;
1426 sub lockwiki () {
1427         # Take an exclusive lock on the wiki to prevent multiple concurrent
1428         # run issues. The lock will be dropped on program exit.
1429         if (! -d $config{wikistatedir}) {
1430                 mkdir($config{wikistatedir});
1431         }
1432         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1433                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1434         if (! flock($wikilock, 2)) { # LOCK_EX
1435                 error("failed to get lock");
1436         }
1437         return 1;
1440 sub unlockwiki () {
1441         POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1442         return close($wikilock) if $wikilock;
1443         return;
1446 my $commitlock;
1448 sub commit_hook_enabled () {
1449         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1450                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1451         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1452                 close($commitlock) || error("failed closing commitlock: $!");
1453                 return 0;
1454         }
1455         close($commitlock) || error("failed closing commitlock: $!");
1456         return 1;
1459 sub disable_commit_hook () {
1460         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1461                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1462         if (! flock($commitlock, 2)) { # LOCK_EX
1463                 error("failed to get commit lock");
1464         }
1465         return 1;
1468 sub enable_commit_hook () {
1469         return close($commitlock) if $commitlock;
1470         return;
1473 sub loadindex () {
1474         %oldrenderedfiles=%pagectime=();
1475         if (! $config{rebuild}) {
1476                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1477                 %destsources=%renderedfiles=%pagecase=%pagestate=
1478                 %depends_simple=();
1479         }
1480         my $in;
1481         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1482                 if (-e "$config{wikistatedir}/index") {
1483                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1484                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1485                 }
1486                 else {
1487                         return;
1488                 }
1489         }
1491         my $index=Storable::fd_retrieve($in);
1492         if (! defined $index) {
1493                 return 0;
1494         }
1496         my $pages;
1497         if (exists $index->{version} && ! ref $index->{version}) {
1498                 $pages=$index->{page};
1499                 %wikistate=%{$index->{state}};
1500         }
1501         else {
1502                 $pages=$index;
1503                 %wikistate=();
1504         }
1506         foreach my $src (keys %$pages) {
1507                 my $d=$pages->{$src};
1508                 my $page=pagename($src);
1509                 $pagectime{$page}=$d->{ctime};
1510                 if (! $config{rebuild}) {
1511                         $pagesources{$page}=$src;
1512                         $pagemtime{$page}=$d->{mtime};
1513                         $renderedfiles{$page}=$d->{dest};
1514                         if (exists $d->{links} && ref $d->{links}) {
1515                                 $links{$page}=$d->{links};
1516                                 $oldlinks{$page}=[@{$d->{links}}];
1517                         }
1518                         if (ref $d->{depends_simple} eq 'ARRAY') {
1519                                 # old format
1520                                 $depends_simple{$page}={
1521                                         map { $_ => 1 } @{$d->{depends_simple}}
1522                                 };
1523                         }
1524                         elsif (exists $d->{depends_simple}) {
1525                                 $depends_simple{$page}=$d->{depends_simple};
1526                         }
1527                         if (exists $d->{dependslist}) {
1528                                 # old format
1529                                 $depends{$page}={
1530                                         map { $_ => $DEPEND_CONTENT }
1531                                                 @{$d->{dependslist}}
1532                                 };
1533                         }
1534                         elsif (exists $d->{depends} && ! ref $d->{depends}) {
1535                                 # old format
1536                                 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1537                         }
1538                         elsif (exists $d->{depends}) {
1539                                 $depends{$page}=$d->{depends};
1540                         }
1541                         if (exists $d->{state}) {
1542                                 $pagestate{$page}=$d->{state};
1543                         }
1544                 }
1545                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1546         }
1547         foreach my $page (keys %pagesources) {
1548                 $pagecase{lc $page}=$page;
1549         }
1550         foreach my $page (keys %renderedfiles) {
1551                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1552         }
1553         return close($in);
1556 sub saveindex () {
1557         run_hooks(savestate => sub { shift->() });
1559         my %hookids;
1560         foreach my $type (keys %hooks) {
1561                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1562         }
1563         my @hookids=keys %hookids;
1565         if (! -d $config{wikistatedir}) {
1566                 mkdir($config{wikistatedir});
1567         }
1568         my $newfile="$config{wikistatedir}/indexdb.new";
1569         my $cleanup = sub { unlink($newfile) };
1570         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1572         my %index;
1573         foreach my $page (keys %pagemtime) {
1574                 next unless $pagemtime{$page};
1575                 my $src=$pagesources{$page};
1577                 $index{page}{$src}={
1578                         ctime => $pagectime{$page},
1579                         mtime => $pagemtime{$page},
1580                         dest => $renderedfiles{$page},
1581                         links => $links{$page},
1582                 };
1584                 if (exists $depends{$page}) {
1585                         $index{page}{$src}{depends} = $depends{$page};
1586                 }
1588                 if (exists $depends_simple{$page}) {
1589                         $index{page}{$src}{depends_simple} = $depends_simple{$page};
1590                 }
1592                 if (exists $pagestate{$page}) {
1593                         foreach my $id (@hookids) {
1594                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1595                                         $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1596                                 }
1597                         }
1598                 }
1599         }
1601         $index{state}={};
1602         foreach my $id (@hookids) {
1603                 foreach my $key (keys %{$wikistate{$id}}) {
1604                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
1605                 }
1606         }
1607         
1608         $index{version}="3";
1609         my $ret=Storable::nstore_fd(\%index, $out);
1610         return if ! defined $ret || ! $ret;
1611         close $out || error("failed saving to $newfile: $!", $cleanup);
1612         rename($newfile, "$config{wikistatedir}/indexdb") ||
1613                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1614         
1615         return 1;
1618 sub template_file ($) {
1619         my $template=shift;
1621         foreach my $dir ($config{templatedir}, @{$config{templatedirs}},
1622                          "$installdir/share/ikiwiki/templates") {
1623                 return "$dir/$template" if -e "$dir/$template";
1624         }
1625         return;
1628 sub template_params (@) {
1629         my $filename=template_file(shift);
1631         if (! defined $filename) {
1632                 return if wantarray;
1633                 return "";
1634         }
1636         my @ret=(
1637                 filter => sub {
1638                         my $text_ref = shift;
1639                         ${$text_ref} = decode_utf8(${$text_ref});
1640                 },
1641                 filename => $filename,
1642                 loop_context_vars => 1,
1643                 die_on_bad_params => 0,
1644                 @_
1645         );
1646         return wantarray ? @ret : {@ret};
1649 sub template ($;@) {
1650         require HTML::Template;
1651         return HTML::Template->new(template_params(@_));
1654 sub misctemplate ($$;@) {
1655         my $title=shift;
1656         my $pagebody=shift;
1657         
1658         my $template=template("misc.tmpl");
1659         $template->param(
1660                 title => $title,
1661                 indexlink => indexlink(),
1662                 wikiname => $config{wikiname},
1663                 pagebody => $pagebody,
1664                 baseurl => baseurl(),
1665                 @_,
1666         );
1667         run_hooks(pagetemplate => sub {
1668                 shift->(page => "", destpage => "", template => $template);
1669         });
1670         return $template->output;
1673 sub hook (@) {
1674         my %param=@_;
1675         
1676         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1677                 error 'hook requires type, call, and id parameters';
1678         }
1680         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1681         
1682         $hooks{$param{type}}{$param{id}}=\%param;
1683         return 1;
1686 sub run_hooks ($$) {
1687         # Calls the given sub for each hook of the given type,
1688         # passing it the hook function to call.
1689         my $type=shift;
1690         my $sub=shift;
1692         if (exists $hooks{$type}) {
1693                 my (@first, @middle, @last);
1694                 foreach my $id (keys %{$hooks{$type}}) {
1695                         if ($hooks{$type}{$id}{first}) {
1696                                 push @first, $id;
1697                         }
1698                         elsif ($hooks{$type}{$id}{last}) {
1699                                 push @last, $id;
1700                         }
1701                         else {
1702                                 push @middle, $id;
1703                         }
1704                 }
1705                 foreach my $id (@first, @middle, @last) {
1706                         $sub->($hooks{$type}{$id}{call});
1707                 }
1708         }
1710         return 1;
1713 sub rcs_update () {
1714         $hooks{rcs}{rcs_update}{call}->(@_);
1717 sub rcs_prepedit ($) {
1718         $hooks{rcs}{rcs_prepedit}{call}->(@_);
1721 sub rcs_commit ($$$;$$) {
1722         $hooks{rcs}{rcs_commit}{call}->(@_);
1725 sub rcs_commit_staged ($$$) {
1726         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1729 sub rcs_add ($) {
1730         $hooks{rcs}{rcs_add}{call}->(@_);
1733 sub rcs_remove ($) {
1734         $hooks{rcs}{rcs_remove}{call}->(@_);
1737 sub rcs_rename ($$) {
1738         $hooks{rcs}{rcs_rename}{call}->(@_);
1741 sub rcs_recentchanges ($) {
1742         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1745 sub rcs_diff ($) {
1746         $hooks{rcs}{rcs_diff}{call}->(@_);
1749 sub rcs_getctime ($) {
1750         $hooks{rcs}{rcs_getctime}{call}->(@_);
1753 sub rcs_receive () {
1754         $hooks{rcs}{rcs_receive}{call}->();
1757 sub add_depends ($$;$) {
1758         my $page=shift;
1759         my $pagespec=shift;
1760         my $deptype=shift || $DEPEND_CONTENT;
1762         # Is the pagespec a simple page name?
1763         if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1764             $pagespec !~ /[\s*?()!]/) {
1765                 $depends_simple{$page}{lc $pagespec} |= $deptype;
1766                 return 1;
1767         }
1769         # Add explicit dependencies for influences.
1770         my $sub=pagespec_translate($pagespec);
1771         return if $@;
1772         foreach my $p (keys %pagesources) {
1773                 my $r=$sub->($p, location => $page);
1774                 my $i=$r->influences;
1775                 foreach my $k (keys %$i) {
1776                         $depends_simple{$page}{lc $k} |= $i->{$k};
1777                 }
1778                 last if $r->influences_static;
1779         }
1781         $depends{$page}{$pagespec} |= $deptype;
1782         return 1;
1785 sub deptype (@) {
1786         my $deptype=0;
1787         foreach my $type (@_) {
1788                 if ($type eq 'presence') {
1789                         $deptype |= $DEPEND_PRESENCE;
1790                 }
1791                 elsif ($type eq 'links') { 
1792                         $deptype |= $DEPEND_LINKS;
1793                 }
1794                 elsif ($type eq 'content') {
1795                         $deptype |= $DEPEND_CONTENT;
1796                 }
1797         }
1798         return $deptype;
1801 sub file_pruned ($;$) {
1802         my $file=shift;
1803         if (@_) {
1804                 require File::Spec;
1805                 $file=File::Spec->canonpath($file);
1806                 my $base=File::Spec->canonpath(shift);
1807                 return if $file eq $base;
1808                 $file =~ s#^\Q$base\E/+##;
1809         }
1811         my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1812         return $file =~ m/$regexp/;
1815 sub define_gettext () {
1816         # If translation is needed, redefine the gettext function to do it.
1817         # Otherwise, it becomes a quick no-op.
1818         no warnings 'redefine';
1819         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1820             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1821             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1822                 *gettext=sub {
1823                         my $gettext_obj=eval q{
1824                                 use Locale::gettext q{textdomain};
1825                                 Locale::gettext->domain('ikiwiki')
1826                         };
1828                         if ($gettext_obj) {
1829                                 $gettext_obj->get(shift);
1830                         }
1831                         else {
1832                                 return shift;
1833                         }
1834                 };
1835         }
1836         else {
1837                 *gettext=sub { return shift };
1838         }
1841 sub gettext {
1842         define_gettext();
1843         gettext(@_);
1846 sub yesno ($) {
1847         my $val=shift;
1849         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1852 sub inject {
1853         # Injects a new function into the symbol table to replace an
1854         # exported function.
1855         my %params=@_;
1857         # This is deep ugly perl foo, beware.
1858         no strict;
1859         no warnings;
1860         if (! defined $params{parent}) {
1861                 $params{parent}='::';
1862                 $params{old}=\&{$params{name}};
1863                 $params{name}=~s/.*:://;
1864         }
1865         my $parent=$params{parent};
1866         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1867                 $ns = $params{parent} . $ns;
1868                 inject(%params, parent => $ns) unless $ns eq '::main::';
1869                 *{$ns . $params{name}} = $params{call}
1870                         if exists ${$ns}{$params{name}} &&
1871                            \&{${$ns}{$params{name}}} == $params{old};
1872         }
1873         use strict;
1874         use warnings;
1877 sub add_link ($$) {
1878         my $page=shift;
1879         my $link=shift;
1881         push @{$links{$page}}, $link
1882                 unless grep { $_ eq $link } @{$links{$page}};
1885 sub pagespec_translate ($) {
1886         my $spec=shift;
1888         # Convert spec to perl code.
1889         my $code="";
1890         my @data;
1891         while ($spec=~m{
1892                 \s*             # ignore whitespace
1893                 (               # 1: match a single word
1894                         \!              # !
1895                 |
1896                         \(              # (
1897                 |
1898                         \)              # )
1899                 |
1900                         \w+\([^\)]*\)   # command(params)
1901                 |
1902                         [^\s()]+        # any other text
1903                 )
1904                 \s*             # ignore whitespace
1905         }gx) {
1906                 my $word=$1;
1907                 if (lc $word eq 'and') {
1908                         $code.=' &';
1909                 }
1910                 elsif (lc $word eq 'or') {
1911                         $code.=' |';
1912                 }
1913                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1914                         $code.=' '.$word;
1915                 }
1916                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1917                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1918                                 push @data, $2;
1919                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
1920                         }
1921                         else {
1922                                 push @data, qq{unknown function in pagespec "$word"};
1923                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
1924                         }
1925                 }
1926                 else {
1927                         push @data, $word;
1928                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
1929                 }
1930         }
1932         if (! length $code) {
1933                 $code="IkiWiki::FailReason->new('empty pagespec')";
1934         }
1936         no warnings;
1937         return eval 'sub { my $page=shift; '.$code.' }';
1940 sub pagespec_match ($$;@) {
1941         my $page=shift;
1942         my $spec=shift;
1943         my @params=@_;
1945         # Backwards compatability with old calling convention.
1946         if (@params == 1) {
1947                 unshift @params, 'location';
1948         }
1950         my $sub=pagespec_translate($spec);
1951         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
1952                 if $@ || ! defined $sub;
1953         return $sub->($page, @params);
1956 sub pagespec_match_list ($$;@) {
1957         my $page=shift;
1958         my $pagespec=shift;
1959         my %params=@_;
1961         # Backwards compatability with old calling convention.
1962         if (ref $page) {
1963                 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
1964                 $params{list}=$page;
1965                 $page=$params{location}; # ugh!
1966         }
1968         my $sub=pagespec_translate($pagespec);
1969         error "syntax error in pagespec \"$pagespec\""
1970                 if $@ || ! defined $sub;
1972         my @candidates;
1973         if (exists $params{list}) {
1974                 @candidates=exists $params{filter}
1975                         ? grep { ! $params{filter}->($_) } @{$params{list}}
1976                         : @{$params{list}};
1977         }
1978         else {
1979                 @candidates=exists $params{filter}
1980                         ? grep { ! $params{filter}->($_) } keys %pagesources
1981                         : keys %pagesources;
1982         }
1984         if (defined $params{sort}) {
1985                 my $f;
1986                 if ($params{sort} eq 'title') {
1987                         $f=sub { pagetitle(basename($a)) cmp pagetitle(basename($b)) };
1988                 }
1989                 elsif ($params{sort} eq 'title_natural') {
1990                         eval q{use Sort::Naturally};
1991                         if ($@) {
1992                                 error(gettext("Sort::Naturally needed for title_natural sort"));
1993                         }
1994                         $f=sub { Sort::Naturally::ncmp(pagetitle(basename($a)), pagetitle(basename($b))) };
1995                 }
1996                 elsif ($params{sort} eq 'mtime') {
1997                         $f=sub { $pagemtime{$b} <=> $pagemtime{$a} };
1998                 }
1999                 elsif ($params{sort} eq 'age') {
2000                         $f=sub { $pagectime{$b} <=> $pagectime{$a} };
2001                 }
2002                 else {
2003                         error sprintf(gettext("unknown sort type %s"), $params{sort});
2004                 }
2005                 @candidates = sort { &$f } @candidates;
2006         }
2008         @candidates=reverse(@candidates) if $params{reverse};
2009         
2010         $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2011         
2012         # clear params, remainder is passed to pagespec
2013         my $num=$params{num};
2014         delete @params{qw{num deptype reverse sort filter list}};
2015         
2016         my @matches;
2017         my $firstfail;
2018         my $count=0;
2019         my $accum=IkiWiki::SuccessReason->new();
2020         foreach my $p (@candidates) {
2021                 my $r=$sub->($p, %params, location => $page);
2022                 error(sprintf(gettext("cannot match pages: %s"), $r))
2023                         if $r->isa("IkiWiki::ErrorReason");
2024                 $accum |= $r;
2025                 if ($r) {
2026                         push @matches, $p;
2027                         last if defined $num && ++$count == $num;
2028                 }
2029         }
2031         # Add simple dependencies for accumulated influences.
2032         my $i=$accum->influences;
2033         foreach my $k (keys %$i) {
2034                 $depends_simple{$page}{lc $k} |= $i->{$k};
2035         }
2037         return @matches;
2040 sub pagespec_valid ($) {
2041         my $spec=shift;
2043         my $sub=pagespec_translate($spec);
2044         return ! $@;
2047 sub glob2re ($) {
2048         my $re=quotemeta(shift);
2049         $re=~s/\\\*/.*/g;
2050         $re=~s/\\\?/./g;
2051         return $re;
2054 package IkiWiki::FailReason;
2056 use overload (
2057         '""'    => sub { $_[0][0] },
2058         '0+'    => sub { 0 },
2059         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2060         '&'     => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2061         '|'     => sub { $_[1]->merge_influences($_[0]); $_[1] },
2062         fallback => 1,
2063 );
2065 our @ISA = 'IkiWiki::SuccessReason';
2067 package IkiWiki::SuccessReason;
2069 use overload (
2070         '""'    => sub { $_[0][0] },
2071         '0+'    => sub { 1 },
2072         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
2073         '&'     => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2074         '|'     => sub { $_[0]->merge_influences($_[1]); $_[0] },
2075         fallback => 1,
2076 );
2078 sub new {
2079         my $class = shift;
2080         my $value = shift;
2081         return bless [$value, {@_}], $class;
2084 sub influences {
2085         my $this=shift;
2086         $this->[1]={@_} if @_;
2087         my %i=%{$this->[1]};
2088         delete $i{""};
2089         return \%i;
2092 sub influences_static {
2093         return ! $_[0][1]->{""};
2096 sub merge_influences {
2097         my $this=shift;
2098         my $other=shift;
2099         my $anded=shift;
2101         if (! $anded || (($this || %{$this->[1]}) &&
2102                         ($other || %{$other->[1]}))) {
2103                 foreach my $influence (keys %{$other->[1]}) {
2104                         $this->[1]{$influence} |= $other->[1]{$influence};
2105                 }
2106         }
2107         else {
2108                 # influence blocker
2109                 $this->[1]={};
2110         }
2113 package IkiWiki::ErrorReason;
2115 our @ISA = 'IkiWiki::FailReason';
2117 package IkiWiki::PageSpec;
2119 sub derel ($$) {
2120         my $path=shift;
2121         my $from=shift;
2123         if ($path =~ m!^\./!) {
2124                 $from=~s#/?[^/]+$## if defined $from;
2125                 $path=~s#^\./##;
2126                 $path="$from/$path" if length $from;
2127         }
2129         return $path;
2132 sub match_glob ($$;@) {
2133         my $page=shift;
2134         my $glob=shift;
2135         my %params=@_;
2136         
2137         $glob=derel($glob, $params{location});
2139         my $regexp=IkiWiki::glob2re($glob);
2140         if ($page=~/^$regexp$/i) {
2141                 if (! IkiWiki::isinternal($page) || $params{internal}) {
2142                         return IkiWiki::SuccessReason->new("$glob matches $page");
2143                 }
2144                 else {
2145                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2146                 }
2147         }
2148         else {
2149                 return IkiWiki::FailReason->new("$glob does not match $page");
2150         }
2153 sub match_internal ($$;@) {
2154         return match_glob($_[0], $_[1], @_, internal => 1)
2157 sub match_link ($$;@) {
2158         my $page=shift;
2159         my $link=lc(shift);
2160         my %params=@_;
2162         $link=derel($link, $params{location});
2163         my $from=exists $params{location} ? $params{location} : '';
2165         my $links = $IkiWiki::links{$page};
2166         return IkiWiki::FailReason->new("$page has no links", "" => 1)
2167                 unless $links && @{$links};
2168         my $bestlink = IkiWiki::bestlink($from, $link);
2169         foreach my $p (@{$links}) {
2170                 if (length $bestlink) {
2171                         return IkiWiki::SuccessReason->new("$page links to $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2172                                 if $bestlink eq IkiWiki::bestlink($page, $p);
2173                 }
2174                 else {
2175                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2176                                 if match_glob($p, $link, %params);
2177                         my ($p_rel)=$p=~/^\/?(.*)/;
2178                         $link=~s/^\///;
2179                         return IkiWiki::SuccessReason->new("$page links to page $p_rel matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2180                                 if match_glob($p_rel, $link, %params);
2181                 }
2182         }
2183         return IkiWiki::FailReason->new("$page does not link to $link", "" => 1);
2186 sub match_backlink ($$;@) {
2187         my $ret=match_link($_[1], $_[0], @_);
2188         $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2189         return $ret;
2192 sub match_created_before ($$;@) {
2193         my $page=shift;
2194         my $testpage=shift;
2195         my %params=@_;
2196         
2197         $testpage=derel($testpage, $params{location});
2199         if (exists $IkiWiki::pagectime{$testpage}) {
2200                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2201                         return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2202                 }
2203                 else {
2204                         return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2205                 }
2206         }
2207         else {
2208                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2209         }
2212 sub match_created_after ($$;@) {
2213         my $page=shift;
2214         my $testpage=shift;
2215         my %params=@_;
2216         
2217         $testpage=derel($testpage, $params{location});
2219         if (exists $IkiWiki::pagectime{$testpage}) {
2220                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2221                         return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2222                 }
2223                 else {
2224                         return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2225                 }
2226         }
2227         else {
2228                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2229         }
2232 sub match_creation_day ($$;@) {
2233         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2234                 return IkiWiki::SuccessReason->new('creation_day matched');
2235         }
2236         else {
2237                 return IkiWiki::FailReason->new('creation_day did not match');
2238         }
2241 sub match_creation_month ($$;@) {
2242         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2243                 return IkiWiki::SuccessReason->new('creation_month matched');
2244         }
2245         else {
2246                 return IkiWiki::FailReason->new('creation_month did not match');
2247         }
2250 sub match_creation_year ($$;@) {
2251         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2252                 return IkiWiki::SuccessReason->new('creation_year matched');
2253         }
2254         else {
2255                 return IkiWiki::FailReason->new('creation_year did not match');
2256         }
2259 sub match_user ($$;@) {
2260         shift;
2261         my $user=shift;
2262         my %params=@_;
2263         
2264         if (! exists $params{user}) {
2265                 return IkiWiki::ErrorReason->new("no user specified");
2266         }
2268         if (defined $params{user} && lc $params{user} eq lc $user) {
2269                 return IkiWiki::SuccessReason->new("user is $user");
2270         }
2271         elsif (! defined $params{user}) {
2272                 return IkiWiki::FailReason->new("not logged in");
2273         }
2274         else {
2275                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2276         }
2279 sub match_admin ($$;@) {
2280         shift;
2281         shift;
2282         my %params=@_;
2283         
2284         if (! exists $params{user}) {
2285                 return IkiWiki::ErrorReason->new("no user specified");
2286         }
2288         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2289                 return IkiWiki::SuccessReason->new("user is an admin");
2290         }
2291         elsif (! defined $params{user}) {
2292                 return IkiWiki::FailReason->new("not logged in");
2293         }
2294         else {
2295                 return IkiWiki::FailReason->new("user is not an admin");
2296         }
2299 sub match_ip ($$;@) {
2300         shift;
2301         my $ip=shift;
2302         my %params=@_;
2303         
2304         if (! exists $params{ip}) {
2305                 return IkiWiki::ErrorReason->new("no IP specified");
2306         }
2308         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2309                 return IkiWiki::SuccessReason->new("IP is $ip");
2310         }
2311         else {
2312                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2313         }