]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki.pm
slight optimisation to file_pruned
[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 ngettext 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         include => {
338                 type => "string",
339                 default => undef,
340                 example => '^\.htaccess$',
341                 description => "regexp of normally ignored source files to include",
342                 advanced => 1,
343                 safe => 0, # regexp
344                 rebuild => 1,
345         },
346         exclude => {
347                 type => "string",
348                 default => undef,
349                 example => '\.wav$',
350                 description => "regexp of source files to ignore",
351                 advanced => 1,
352                 safe => 0, # regexp
353                 rebuild => 1,
354         },
355         wiki_file_prune_regexps => {
356                 type => "internal",
357                 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
358                         qr/\.x?html?$/, qr/\.ikiwiki-new$/,
359                         qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
360                         qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
361                         qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
362                 description => "regexps of source files to ignore",
363                 safe => 0,
364                 rebuild => 1,
365         },
366         wiki_file_chars => {
367                 type => "string",
368                 description => "specifies the characters that are allowed in source filenames",
369                 default => "-[:alnum:]+/.:_",
370                 safe => 0,
371                 rebuild => 1,
372         },
373         wiki_file_regexp => {
374                 type => "internal",
375                 description => "regexp of legal source files",
376                 safe => 0,
377                 rebuild => 1,
378         },
379         web_commit_regexp => {
380                 type => "internal",
381                 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
382                 description => "regexp to parse web commits from logs",
383                 safe => 0,
384                 rebuild => 0,
385         },
386         cgi => {
387                 type => "internal",
388                 default => 0,
389                 description => "run as a cgi",
390                 safe => 0,
391                 rebuild => 0,
392         },
393         cgi_disable_uploads => {
394                 type => "internal",
395                 default => 1,
396                 description => "whether CGI should accept file uploads",
397                 safe => 0,
398                 rebuild => 0,
399         },
400         post_commit => {
401                 type => "internal",
402                 default => 0,
403                 description => "run as a post-commit hook",
404                 safe => 0,
405                 rebuild => 0,
406         },
407         rebuild => {
408                 type => "internal",
409                 default => 0,
410                 description => "running in rebuild mode",
411                 safe => 0,
412                 rebuild => 0,
413         },
414         setup => {
415                 type => "internal",
416                 default => undef,
417                 description => "running in setup mode",
418                 safe => 0,
419                 rebuild => 0,
420         },
421         clean => {
422                 type => "internal",
423                 default => 0,
424                 description => "running in clean mode",
425                 safe => 0,
426                 rebuild => 0,
427         },
428         refresh => {
429                 type => "internal",
430                 default => 0,
431                 description => "running in refresh mode",
432                 safe => 0,
433                 rebuild => 0,
434         },
435         test_receive => {
436                 type => "internal",
437                 default => 0,
438                 description => "running in receive test mode",
439                 safe => 0,
440                 rebuild => 0,
441         },
442         getctime => {
443                 type => "internal",
444                 default => 0,
445                 description => "running in getctime mode",
446                 safe => 0,
447                 rebuild => 0,
448         },
449         w3mmode => {
450                 type => "internal",
451                 default => 0,
452                 description => "running in w3mmode",
453                 safe => 0,
454                 rebuild => 0,
455         },
456         wikistatedir => {
457                 type => "internal",
458                 default => undef,
459                 description => "path to the .ikiwiki directory holding ikiwiki state",
460                 safe => 0,
461                 rebuild => 0,
462         },
463         setupfile => {
464                 type => "internal",
465                 default => undef,
466                 description => "path to setup file",
467                 safe => 0,
468                 rebuild => 0,
469         },
470         allow_symlinks_before_srcdir => {
471                 type => "boolean",
472                 default => 0,
473                 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
474                 safe => 0,
475                 rebuild => 0,
476         },
479 sub defaultconfig () {
480         my %s=getsetup();
481         my @ret;
482         foreach my $key (keys %s) {
483                 push @ret, $key, $s{$key}->{default};
484         }
485         use Data::Dumper;
486         return @ret;
489 sub checkconfig () {
490         # locale stuff; avoid LC_ALL since it overrides everything
491         if (defined $ENV{LC_ALL}) {
492                 $ENV{LANG} = $ENV{LC_ALL};
493                 delete $ENV{LC_ALL};
494         }
495         if (defined $config{locale}) {
496                 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
497                         $ENV{LANG}=$config{locale};
498                         define_gettext();
499                 }
500         }
501                 
502         if (! defined $config{wiki_file_regexp}) {
503                 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
504         }
506         if (ref $config{ENV} eq 'HASH') {
507                 foreach my $val (keys %{$config{ENV}}) {
508                         $ENV{$val}=$config{ENV}{$val};
509                 }
510         }
512         if ($config{w3mmode}) {
513                 eval q{use Cwd q{abs_path}};
514                 error($@) if $@;
515                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
516                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
517                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
518                         unless $config{cgiurl} =~ m!file:///!;
519                 $config{url}="file://".$config{destdir};
520         }
522         if ($config{cgi} && ! length $config{url}) {
523                 error(gettext("Must specify url to wiki with --url when using --cgi"));
524         }
525         
526         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
527                 unless exists $config{wikistatedir} && defined $config{wikistatedir};
529         if (defined $config{umask}) {
530                 umask(possibly_foolish_untaint($config{umask}));
531         }
533         run_hooks(checkconfig => sub { shift->() });
535         return 1;
538 sub listplugins () {
539         my %ret;
541         foreach my $dir (@INC, $config{libdir}) {
542                 next unless defined $dir && length $dir;
543                 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
544                         my ($plugin)=$file=~/.*\/(.*)\.pm$/;
545                         $ret{$plugin}=1;
546                 }
547         }
548         foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
549                 next unless defined $dir && length $dir;
550                 foreach my $file (glob("$dir/plugins/*")) {
551                         $ret{basename($file)}=1 if -x $file;
552                 }
553         }
555         return keys %ret;
558 sub loadplugins () {
559         if (defined $config{libdir} && length $config{libdir}) {
560                 unshift @INC, possibly_foolish_untaint($config{libdir});
561         }
563         foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
564                 loadplugin($plugin);
565         }
566         
567         if ($config{rcs}) {
568                 if (exists $hooks{rcs}) {
569                         error(gettext("cannot use multiple rcs plugins"));
570                 }
571                 loadplugin($config{rcs});
572         }
573         if (! exists $hooks{rcs}) {
574                 loadplugin("norcs");
575         }
577         run_hooks(getopt => sub { shift->() });
578         if (grep /^-/, @ARGV) {
579                 print STDERR "Unknown option (or missing parameter): $_\n"
580                         foreach grep /^-/, @ARGV;
581                 usage();
582         }
584         return 1;
587 sub loadplugin ($) {
588         my $plugin=shift;
590         return if grep { $_ eq $plugin} @{$config{disable_plugins}};
592         foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
593                          "$installdir/lib/ikiwiki") {
594                 if (defined $dir && -x "$dir/plugins/$plugin") {
595                         eval { require IkiWiki::Plugin::external };
596                         if ($@) {
597                                 my $reason=$@;
598                                 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
599                         }
600                         import IkiWiki::Plugin::external "$dir/plugins/$plugin";
601                         $loaded_plugins{$plugin}=1;
602                         return 1;
603                 }
604         }
606         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
607         eval qq{use $mod};
608         if ($@) {
609                 error("Failed to load plugin $mod: $@");
610         }
611         $loaded_plugins{$plugin}=1;
612         return 1;
615 sub error ($;$) {
616         my $message=shift;
617         my $cleaner=shift;
618         log_message('err' => $message) if $config{syslog};
619         if (defined $cleaner) {
620                 $cleaner->();
621         }
622         die $message."\n";
625 sub debug ($) {
626         return unless $config{verbose};
627         return log_message(debug => @_);
630 my $log_open=0;
631 sub log_message ($$) {
632         my $type=shift;
634         if ($config{syslog}) {
635                 require Sys::Syslog;
636                 if (! $log_open) {
637                         Sys::Syslog::setlogsock('unix');
638                         Sys::Syslog::openlog('ikiwiki', '', 'user');
639                         $log_open=1;
640                 }
641                 return eval {
642                         Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
643                 };
644         }
645         elsif (! $config{cgi}) {
646                 return print "@_\n";
647         }
648         else {
649                 return print STDERR "@_\n";
650         }
653 sub possibly_foolish_untaint ($) {
654         my $tainted=shift;
655         my ($untainted)=$tainted=~/(.*)/s;
656         return $untainted;
659 sub basename ($) {
660         my $file=shift;
662         $file=~s!.*/+!!;
663         return $file;
666 sub dirname ($) {
667         my $file=shift;
669         $file=~s!/*[^/]+$!!;
670         return $file;
673 sub isinternal ($) {
674         my $page=shift;
675         return exists $pagesources{$page} &&
676                 $pagesources{$page} =~ /\._([^.]+)$/;
679 sub pagetype ($) {
680         my $file=shift;
681         
682         if ($file =~ /\.([^.]+)$/) {
683                 return $1 if exists $hooks{htmlize}{$1};
684         }
685         my $base=basename($file);
686         if (exists $hooks{htmlize}{$base} &&
687             $hooks{htmlize}{$base}{noextension}) {
688                 return $base;
689         }
690         return;
693 my %pagename_cache;
695 sub pagename ($) {
696         my $file=shift;
698         if (exists $pagename_cache{$file}) {
699                 return $pagename_cache{$file};
700         }
702         my $type=pagetype($file);
703         my $page=$file;
704         $page=~s/\Q.$type\E*$//
705                 if defined $type && !$hooks{htmlize}{$type}{keepextension}
706                         && !$hooks{htmlize}{$type}{noextension};
707         if ($config{indexpages} && $page=~/(.*)\/index$/) {
708                 $page=$1;
709         }
711         $pagename_cache{$file} = $page;
712         return $page;
715 sub newpagefile ($$) {
716         my $page=shift;
717         my $type=shift;
719         if (! $config{indexpages} || $page eq 'index') {
720                 return $page.".".$type;
721         }
722         else {
723                 return $page."/index.".$type;
724         }
727 sub targetpage ($$;$) {
728         my $page=shift;
729         my $ext=shift;
730         my $filename=shift;
731         
732         if (defined $filename) {
733                 return $page."/".$filename.".".$ext;
734         }
735         elsif (! $config{usedirs} || $page eq 'index') {
736                 return $page.".".$ext;
737         }
738         else {
739                 return $page."/index.".$ext;
740         }
743 sub htmlpage ($) {
744         my $page=shift;
745         
746         return targetpage($page, $config{htmlext});
749 sub srcfile_stat {
750         my $file=shift;
751         my $nothrow=shift;
753         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
754         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
755                 return "$dir/$file", stat(_) if -e "$dir/$file";
756         }
757         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
758         return;
761 sub srcfile ($;$) {
762         return (srcfile_stat(@_))[0];
765 sub add_underlay ($) {
766         my $dir=shift;
768         if ($dir !~ /^\//) {
769                 $dir="$config{underlaydirbase}/$dir";
770         }
772         if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
773                 unshift @{$config{underlaydirs}}, $dir;
774         }
776         return 1;
779 sub readfile ($;$$) {
780         my $file=shift;
781         my $binary=shift;
782         my $wantfd=shift;
784         if (-l $file) {
785                 error("cannot read a symlink ($file)");
786         }
787         
788         local $/=undef;
789         open (my $in, "<", $file) || error("failed to read $file: $!");
790         binmode($in) if ($binary);
791         return \*$in if $wantfd;
792         my $ret=<$in>;
793         # check for invalid utf-8, and toss it back to avoid crashes
794         if (! utf8::valid($ret)) {
795                 $ret=encode_utf8($ret);
796         }
797         close $in || error("failed to read $file: $!");
798         return $ret;
801 sub prep_writefile ($$) {
802         my $file=shift;
803         my $destdir=shift;
804         
805         my $test=$file;
806         while (length $test) {
807                 if (-l "$destdir/$test") {
808                         error("cannot write to a symlink ($test)");
809                 }
810                 $test=dirname($test);
811         }
813         my $dir=dirname("$destdir/$file");
814         if (! -d $dir) {
815                 my $d="";
816                 foreach my $s (split(m!/+!, $dir)) {
817                         $d.="$s/";
818                         if (! -d $d) {
819                                 mkdir($d) || error("failed to create directory $d: $!");
820                         }
821                 }
822         }
824         return 1;
827 sub writefile ($$$;$$) {
828         my $file=shift; # can include subdirs
829         my $destdir=shift; # directory to put file in
830         my $content=shift;
831         my $binary=shift;
832         my $writer=shift;
833         
834         prep_writefile($file, $destdir);
835         
836         my $newfile="$destdir/$file.ikiwiki-new";
837         if (-l $newfile) {
838                 error("cannot write to a symlink ($newfile)");
839         }
840         
841         my $cleanup = sub { unlink($newfile) };
842         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
843         binmode($out) if ($binary);
844         if ($writer) {
845                 $writer->(\*$out, $cleanup);
846         }
847         else {
848                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
849         }
850         close $out || error("failed saving $newfile: $!", $cleanup);
851         rename($newfile, "$destdir/$file") || 
852                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
854         return 1;
857 my %cleared;
858 sub will_render ($$;$) {
859         my $page=shift;
860         my $dest=shift;
861         my $clear=shift;
863         # Important security check.
864         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
865             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
866                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
867         }
869         if (! $clear || $cleared{$page}) {
870                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
871         }
872         else {
873                 foreach my $old (@{$renderedfiles{$page}}) {
874                         delete $destsources{$old};
875                 }
876                 $renderedfiles{$page}=[$dest];
877                 $cleared{$page}=1;
878         }
879         $destsources{$dest}=$page;
881         return 1;
884 sub bestlink ($$) {
885         my $page=shift;
886         my $link=shift;
887         
888         my $cwd=$page;
889         if ($link=~s/^\/+//) {
890                 # absolute links
891                 $cwd="";
892         }
893         $link=~s/\/$//;
895         do {
896                 my $l=$cwd;
897                 $l.="/" if length $l;
898                 $l.=$link;
900                 if (exists $pagesources{$l}) {
901                         return $l;
902                 }
903                 elsif (exists $pagecase{lc $l}) {
904                         return $pagecase{lc $l};
905                 }
906         } while $cwd=~s{/?[^/]+$}{};
908         if (length $config{userdir}) {
909                 my $l = "$config{userdir}/".lc($link);
910                 if (exists $pagesources{$l}) {
911                         return $l;
912                 }
913                 elsif (exists $pagecase{lc $l}) {
914                         return $pagecase{lc $l};
915                 }
916         }
918         #print STDERR "warning: page $page, broken link: $link\n";
919         return "";
922 sub isinlinableimage ($) {
923         my $file=shift;
924         
925         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
928 sub pagetitle ($;$) {
929         my $page=shift;
930         my $unescaped=shift;
932         if ($unescaped) {
933                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
934         }
935         else {
936                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
937         }
939         return $page;
942 sub titlepage ($) {
943         my $title=shift;
944         # support use w/o %config set
945         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
946         $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
947         return $title;
950 sub linkpage ($) {
951         my $link=shift;
952         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
953         $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
954         return $link;
957 sub cgiurl (@) {
958         my %params=@_;
960         my $cgiurl=$config{cgiurl};
961         if (exists $params{cgiurl}) {
962                 $cgiurl=$params{cgiurl};
963                 delete $params{cgiurl};
964         }
965         return $cgiurl."?".
966                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
969 sub baseurl (;$) {
970         my $page=shift;
972         return "$config{url}/" if ! defined $page;
973         
974         $page=htmlpage($page);
975         $page=~s/[^\/]+$//;
976         $page=~s/[^\/]+\//..\//g;
977         return $page;
980 sub abs2rel ($$) {
981         # Work around very innefficient behavior in File::Spec if abs2rel
982         # is passed two relative paths. It's much faster if paths are
983         # absolute! (Debian bug #376658; fixed in debian unstable now)
984         my $path="/".shift;
985         my $base="/".shift;
987         require File::Spec;
988         my $ret=File::Spec->abs2rel($path, $base);
989         $ret=~s/^// if defined $ret;
990         return $ret;
993 sub displaytime ($;$) {
994         # Plugins can override this function to mark up the time to
995         # display.
996         return '<span class="date">'.formattime(@_).'</span>';
999 sub formattime ($;$) {
1000         # Plugins can override this function to format the time.
1001         my $time=shift;
1002         my $format=shift;
1003         if (! defined $format) {
1004                 $format=$config{timeformat};
1005         }
1007         # strftime doesn't know about encodings, so make sure
1008         # its output is properly treated as utf8
1009         return decode_utf8(POSIX::strftime($format, localtime($time)));
1012 sub beautify_urlpath ($) {
1013         my $url=shift;
1015         # Ensure url is not an empty link, and if necessary,
1016         # add ./ to avoid colon confusion.
1017         if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1018                 $url="./$url";
1019         }
1021         if ($config{usedirs}) {
1022                 $url =~ s!/index.$config{htmlext}$!/!;
1023         }
1025         return $url;
1028 sub urlto ($$;$) {
1029         my $to=shift;
1030         my $from=shift;
1031         my $absolute=shift;
1032         
1033         if (! length $to) {
1034                 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1035         }
1037         if (! $destsources{$to}) {
1038                 $to=htmlpage($to);
1039         }
1041         if ($absolute) {
1042                 return $config{url}.beautify_urlpath("/".$to);
1043         }
1045         my $link = abs2rel($to, dirname(htmlpage($from)));
1047         return beautify_urlpath($link);
1050 sub htmllink ($$$;@) {
1051         my $lpage=shift; # the page doing the linking
1052         my $page=shift; # the page that will contain the link (different for inline)
1053         my $link=shift;
1054         my %opts=@_;
1056         $link=~s/\/$//;
1058         my $bestlink;
1059         if (! $opts{forcesubpage}) {
1060                 $bestlink=bestlink($lpage, $link);
1061         }
1062         else {
1063                 $bestlink="$lpage/".lc($link);
1064         }
1066         my $linktext;
1067         if (defined $opts{linktext}) {
1068                 $linktext=$opts{linktext};
1069         }
1070         else {
1071                 $linktext=pagetitle(basename($link));
1072         }
1073         
1074         return "<span class=\"selflink\">$linktext</span>"
1075                 if length $bestlink && $page eq $bestlink &&
1076                    ! defined $opts{anchor};
1077         
1078         if (! $destsources{$bestlink}) {
1079                 $bestlink=htmlpage($bestlink);
1081                 if (! $destsources{$bestlink}) {
1082                         return $linktext unless length $config{cgiurl};
1083                         return "<span class=\"createlink\"><a href=\"".
1084                                 cgiurl(
1085                                         do => "create",
1086                                         page => lc($link),
1087                                         from => $lpage
1088                                 ).
1089                                 "\" rel=\"nofollow\">?</a>$linktext</span>"
1090                 }
1091         }
1092         
1093         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1094         $bestlink=beautify_urlpath($bestlink);
1095         
1096         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1097                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1098         }
1100         if (defined $opts{anchor}) {
1101                 $bestlink.="#".$opts{anchor};
1102         }
1104         my @attrs;
1105         foreach my $attr (qw{rel class title}) {
1106                 if (defined $opts{$attr}) {
1107                         push @attrs, " $attr=\"$opts{$attr}\"";
1108                 }
1109         }
1111         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1114 sub userpage ($) {
1115         my $user=shift;
1116         return length $config{userdir} ? "$config{userdir}/$user" : $user;
1119 sub openiduser ($) {
1120         my $user=shift;
1122         if ($user =~ m!^https?://! &&
1123             eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1124                 my $display;
1126                 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1127                         $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1128                 }
1129                 else {
1130                         # backcompat with old version
1131                         my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1132                         $display=$oid->display;
1133                 }
1135                 # Convert "user.somehost.com" to "user [somehost.com]"
1136                 # (also "user.somehost.co.uk")
1137                 if ($display !~ /\[/) {
1138                         $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1139                 }
1140                 # Convert "http://somehost.com/user" to "user [somehost.com]".
1141                 # (also "https://somehost.com/user/")
1142                 if ($display !~ /\[/) {
1143                         $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1144                 }
1145                 $display=~s!^https?://!!; # make sure this is removed
1146                 eval q{use CGI 'escapeHTML'};
1147                 error($@) if $@;
1148                 return escapeHTML($display);
1149         }
1150         return;
1153 sub htmlize ($$$$) {
1154         my $page=shift;
1155         my $destpage=shift;
1156         my $type=shift;
1157         my $content=shift;
1158         
1159         my $oneline = $content !~ /\n/;
1161         if (exists $hooks{htmlize}{$type}) {
1162                 $content=$hooks{htmlize}{$type}{call}->(
1163                         page => $page,
1164                         content => $content,
1165                 );
1166         }
1167         else {
1168                 error("htmlization of $type not supported");
1169         }
1171         run_hooks(sanitize => sub {
1172                 $content=shift->(
1173                         page => $page,
1174                         destpage => $destpage,
1175                         content => $content,
1176                 );
1177         });
1178         
1179         if ($oneline) {
1180                 # hack to get rid of enclosing junk added by markdown
1181                 # and other htmlizers
1182                 $content=~s/^<p>//i;
1183                 $content=~s/<\/p>$//i;
1184                 chomp $content;
1185         }
1187         return $content;
1190 sub linkify ($$$) {
1191         my $page=shift;
1192         my $destpage=shift;
1193         my $content=shift;
1195         run_hooks(linkify => sub {
1196                 $content=shift->(
1197                         page => $page,
1198                         destpage => $destpage,
1199                         content => $content,
1200                 );
1201         });
1202         
1203         return $content;
1206 our %preprocessing;
1207 our $preprocess_preview=0;
1208 sub preprocess ($$$;$$) {
1209         my $page=shift; # the page the data comes from
1210         my $destpage=shift; # the page the data will appear in (different for inline)
1211         my $content=shift;
1212         my $scan=shift;
1213         my $preview=shift;
1215         # Using local because it needs to be set within any nested calls
1216         # of this function.
1217         local $preprocess_preview=$preview if defined $preview;
1219         my $handle=sub {
1220                 my $escape=shift;
1221                 my $prefix=shift;
1222                 my $command=shift;
1223                 my $params=shift;
1224                 $params="" if ! defined $params;
1226                 if (length $escape) {
1227                         return "[[$prefix$command $params]]";
1228                 }
1229                 elsif (exists $hooks{preprocess}{$command}) {
1230                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1231                         # Note: preserve order of params, some plugins may
1232                         # consider it significant.
1233                         my @params;
1234                         while ($params =~ m{
1235                                 (?:([-\w]+)=)?          # 1: named parameter key?
1236                                 (?:
1237                                         """(.*?)"""     # 2: triple-quoted value
1238                                 |
1239                                         "([^"]*?)"      # 3: single-quoted value
1240                                 |
1241                                         (\S+)           # 4: unquoted value
1242                                 )
1243                                 (?:\s+|$)               # delimiter to next param
1244                         }sgx) {
1245                                 my $key=$1;
1246                                 my $val;
1247                                 if (defined $2) {
1248                                         $val=$2;
1249                                         $val=~s/\r\n/\n/mg;
1250                                         $val=~s/^\n+//g;
1251                                         $val=~s/\n+$//g;
1252                                 }
1253                                 elsif (defined $3) {
1254                                         $val=$3;
1255                                 }
1256                                 elsif (defined $4) {
1257                                         $val=$4;
1258                                 }
1260                                 if (defined $key) {
1261                                         push @params, $key, $val;
1262                                 }
1263                                 else {
1264                                         push @params, $val, '';
1265                                 }
1266                         }
1267                         if ($preprocessing{$page}++ > 3) {
1268                                 # Avoid loops of preprocessed pages preprocessing
1269                                 # other pages that preprocess them, etc.
1270                                 return "[[!$command <span class=\"error\">".
1271                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1272                                                 $page, $preprocessing{$page}).
1273                                         "</span>]]";
1274                         }
1275                         my $ret;
1276                         if (! $scan) {
1277                                 $ret=eval {
1278                                         $hooks{preprocess}{$command}{call}->(
1279                                                 @params,
1280                                                 page => $page,
1281                                                 destpage => $destpage,
1282                                                 preview => $preprocess_preview,
1283                                         );
1284                                 };
1285                                 if ($@) {
1286                                         my $error=$@;
1287                                         chomp $error;
1288                                         $ret="[[!$command <span class=\"error\">".
1289                                                 gettext("Error").": $error"."</span>]]";
1290                                 }
1291                         }
1292                         else {
1293                                 # use void context during scan pass
1294                                 eval {
1295                                         $hooks{preprocess}{$command}{call}->(
1296                                                 @params,
1297                                                 page => $page,
1298                                                 destpage => $destpage,
1299                                                 preview => $preprocess_preview,
1300                                         );
1301                                 };
1302                                 $ret="";
1303                         }
1304                         $preprocessing{$page}--;
1305                         return $ret;
1306                 }
1307                 else {
1308                         return "[[$prefix$command $params]]";
1309                 }
1310         };
1311         
1312         my $regex;
1313         if ($config{prefix_directives}) {
1314                 $regex = qr{
1315                         (\\?)           # 1: escape?
1316                         \[\[(!)         # directive open; 2: prefix
1317                         ([-\w]+)        # 3: command
1318                         (               # 4: the parameters..
1319                                 \s+     # Must have space if parameters present
1320                                 (?:
1321                                         (?:[-\w]+=)?            # named parameter key?
1322                                         (?:
1323                                                 """.*?"""       # triple-quoted value
1324                                                 |
1325                                                 "[^"]*?"        # single-quoted value
1326                                                 |
1327                                                 [^"\s\]]+       # unquoted value
1328                                         )
1329                                         \s*                     # whitespace or end
1330                                                                 # of directive
1331                                 )
1332                         *)?             # 0 or more parameters
1333                         \]\]            # directive closed
1334                 }sx;
1335         }
1336         else {
1337                 $regex = qr{
1338                         (\\?)           # 1: escape?
1339                         \[\[(!?)        # directive open; 2: optional prefix
1340                         ([-\w]+)        # 3: command
1341                         \s+
1342                         (               # 4: the parameters..
1343                                 (?:
1344                                         (?:[-\w]+=)?            # named parameter key?
1345                                         (?:
1346                                                 """.*?"""       # triple-quoted value
1347                                                 |
1348                                                 "[^"]*?"        # single-quoted value
1349                                                 |
1350                                                 [^"\s\]]+       # unquoted value
1351                                         )
1352                                         \s*                     # whitespace or end
1353                                                                 # of directive
1354                                 )
1355                         *)              # 0 or more parameters
1356                         \]\]            # directive closed
1357                 }sx;
1358         }
1360         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1361         return $content;
1364 sub filter ($$$) {
1365         my $page=shift;
1366         my $destpage=shift;
1367         my $content=shift;
1369         run_hooks(filter => sub {
1370                 $content=shift->(page => $page, destpage => $destpage, 
1371                         content => $content);
1372         });
1374         return $content;
1377 sub indexlink () {
1378         return "<a href=\"$config{url}\">$config{wikiname}</a>";
1381 sub check_canedit ($$$;$) {
1382         my $page=shift;
1383         my $q=shift;
1384         my $session=shift;
1385         my $nonfatal=shift;
1386         
1387         my $canedit;
1388         run_hooks(canedit => sub {
1389                 return if defined $canedit;
1390                 my $ret=shift->($page, $q, $session);
1391                 if (defined $ret) {
1392                         if ($ret eq "") {
1393                                 $canedit=1;
1394                         }
1395                         elsif (ref $ret eq 'CODE') {
1396                                 $ret->() unless $nonfatal;
1397                                 $canedit=0;
1398                         }
1399                         elsif (defined $ret) {
1400                                 error($ret) unless $nonfatal;
1401                                 $canedit=0;
1402                         }
1403                 }
1404         });
1405         return defined $canedit ? $canedit : 1;
1408 sub check_content (@) {
1409         my %params=@_;
1410         
1411         return 1 if ! exists $hooks{checkcontent}; # optimisation
1413         if (exists $pagesources{$params{page}}) {
1414                 my @diff;
1415                 my %old=map { $_ => 1 }
1416                         split("\n", readfile(srcfile($pagesources{$params{page}})));
1417                 foreach my $line (split("\n", $params{content})) {
1418                         push @diff, $line if ! exists $old{$line};
1419                 }
1420                 $params{diff}=join("\n", @diff);
1421         }
1423         my $ok;
1424         run_hooks(checkcontent => sub {
1425                 return if defined $ok;
1426                 my $ret=shift->(%params);
1427                 if (defined $ret) {
1428                         if ($ret eq "") {
1429                                 $ok=1;
1430                         }
1431                         elsif (ref $ret eq 'CODE') {
1432                                 $ret->() unless $params{nonfatal};
1433                                 $ok=0;
1434                         }
1435                         elsif (defined $ret) {
1436                                 error($ret) unless $params{nonfatal};
1437                                 $ok=0;
1438                         }
1439                 }
1441         });
1442         return defined $ok ? $ok : 1;
1445 my $wikilock;
1447 sub lockwiki () {
1448         # Take an exclusive lock on the wiki to prevent multiple concurrent
1449         # run issues. The lock will be dropped on program exit.
1450         if (! -d $config{wikistatedir}) {
1451                 mkdir($config{wikistatedir});
1452         }
1453         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1454                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1455         if (! flock($wikilock, 2)) { # LOCK_EX
1456                 error("failed to get lock");
1457         }
1458         return 1;
1461 sub unlockwiki () {
1462         POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1463         return close($wikilock) if $wikilock;
1464         return;
1467 my $commitlock;
1469 sub commit_hook_enabled () {
1470         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1471                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1472         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1473                 close($commitlock) || error("failed closing commitlock: $!");
1474                 return 0;
1475         }
1476         close($commitlock) || error("failed closing commitlock: $!");
1477         return 1;
1480 sub disable_commit_hook () {
1481         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1482                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1483         if (! flock($commitlock, 2)) { # LOCK_EX
1484                 error("failed to get commit lock");
1485         }
1486         return 1;
1489 sub enable_commit_hook () {
1490         return close($commitlock) if $commitlock;
1491         return;
1494 sub loadindex () {
1495         %oldrenderedfiles=%pagectime=();
1496         if (! $config{rebuild}) {
1497                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1498                 %destsources=%renderedfiles=%pagecase=%pagestate=
1499                 %depends_simple=();
1500         }
1501         my $in;
1502         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1503                 if (-e "$config{wikistatedir}/index") {
1504                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1505                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1506                 }
1507                 else {
1508                         return;
1509                 }
1510         }
1512         my $index=Storable::fd_retrieve($in);
1513         if (! defined $index) {
1514                 return 0;
1515         }
1517         my $pages;
1518         if (exists $index->{version} && ! ref $index->{version}) {
1519                 $pages=$index->{page};
1520                 %wikistate=%{$index->{state}};
1521         }
1522         else {
1523                 $pages=$index;
1524                 %wikistate=();
1525         }
1527         foreach my $src (keys %$pages) {
1528                 my $d=$pages->{$src};
1529                 my $page=pagename($src);
1530                 $pagectime{$page}=$d->{ctime};
1531                 if (! $config{rebuild}) {
1532                         $pagesources{$page}=$src;
1533                         $pagemtime{$page}=$d->{mtime};
1534                         $renderedfiles{$page}=$d->{dest};
1535                         if (exists $d->{links} && ref $d->{links}) {
1536                                 $links{$page}=$d->{links};
1537                                 $oldlinks{$page}=[@{$d->{links}}];
1538                         }
1539                         if (ref $d->{depends_simple} eq 'ARRAY') {
1540                                 # old format
1541                                 $depends_simple{$page}={
1542                                         map { $_ => 1 } @{$d->{depends_simple}}
1543                                 };
1544                         }
1545                         elsif (exists $d->{depends_simple}) {
1546                                 $depends_simple{$page}=$d->{depends_simple};
1547                         }
1548                         if (exists $d->{dependslist}) {
1549                                 # old format
1550                                 $depends{$page}={
1551                                         map { $_ => $DEPEND_CONTENT }
1552                                                 @{$d->{dependslist}}
1553                                 };
1554                         }
1555                         elsif (exists $d->{depends} && ! ref $d->{depends}) {
1556                                 # old format
1557                                 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1558                         }
1559                         elsif (exists $d->{depends}) {
1560                                 $depends{$page}=$d->{depends};
1561                         }
1562                         if (exists $d->{state}) {
1563                                 $pagestate{$page}=$d->{state};
1564                         }
1565                 }
1566                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1567         }
1568         foreach my $page (keys %pagesources) {
1569                 $pagecase{lc $page}=$page;
1570         }
1571         foreach my $page (keys %renderedfiles) {
1572                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1573         }
1574         return close($in);
1577 sub saveindex () {
1578         run_hooks(savestate => sub { shift->() });
1580         my %hookids;
1581         foreach my $type (keys %hooks) {
1582                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1583         }
1584         my @hookids=keys %hookids;
1586         if (! -d $config{wikistatedir}) {
1587                 mkdir($config{wikistatedir});
1588         }
1589         my $newfile="$config{wikistatedir}/indexdb.new";
1590         my $cleanup = sub { unlink($newfile) };
1591         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1593         my %index;
1594         foreach my $page (keys %pagemtime) {
1595                 next unless $pagemtime{$page};
1596                 my $src=$pagesources{$page};
1598                 $index{page}{$src}={
1599                         ctime => $pagectime{$page},
1600                         mtime => $pagemtime{$page},
1601                         dest => $renderedfiles{$page},
1602                         links => $links{$page},
1603                 };
1605                 if (exists $depends{$page}) {
1606                         $index{page}{$src}{depends} = $depends{$page};
1607                 }
1609                 if (exists $depends_simple{$page}) {
1610                         $index{page}{$src}{depends_simple} = $depends_simple{$page};
1611                 }
1613                 if (exists $pagestate{$page}) {
1614                         foreach my $id (@hookids) {
1615                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1616                                         $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1617                                 }
1618                         }
1619                 }
1620         }
1622         $index{state}={};
1623         foreach my $id (@hookids) {
1624                 foreach my $key (keys %{$wikistate{$id}}) {
1625                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
1626                 }
1627         }
1628         
1629         $index{version}="3";
1630         my $ret=Storable::nstore_fd(\%index, $out);
1631         return if ! defined $ret || ! $ret;
1632         close $out || error("failed saving to $newfile: $!", $cleanup);
1633         rename($newfile, "$config{wikistatedir}/indexdb") ||
1634                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1635         
1636         return 1;
1639 sub template_file ($) {
1640         my $template=shift;
1642         foreach my $dir ($config{templatedir}, @{$config{templatedirs}},
1643                          "$installdir/share/ikiwiki/templates") {
1644                 return "$dir/$template" if -e "$dir/$template";
1645         }
1646         return;
1649 sub template_params (@) {
1650         my $filename=template_file(shift);
1652         if (! defined $filename) {
1653                 return if wantarray;
1654                 return "";
1655         }
1657         my @ret=(
1658                 filter => sub {
1659                         my $text_ref = shift;
1660                         ${$text_ref} = decode_utf8(${$text_ref});
1661                 },
1662                 filename => $filename,
1663                 loop_context_vars => 1,
1664                 die_on_bad_params => 0,
1665                 @_
1666         );
1667         return wantarray ? @ret : {@ret};
1670 sub template ($;@) {
1671         require HTML::Template;
1672         return HTML::Template->new(template_params(@_));
1675 sub misctemplate ($$;@) {
1676         my $title=shift;
1677         my $pagebody=shift;
1678         
1679         my $template=template("misc.tmpl");
1680         $template->param(
1681                 title => $title,
1682                 indexlink => indexlink(),
1683                 wikiname => $config{wikiname},
1684                 pagebody => $pagebody,
1685                 baseurl => baseurl(),
1686                 @_,
1687         );
1688         run_hooks(pagetemplate => sub {
1689                 shift->(page => "", destpage => "", template => $template);
1690         });
1691         return $template->output;
1694 sub hook (@) {
1695         my %param=@_;
1696         
1697         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1698                 error 'hook requires type, call, and id parameters';
1699         }
1701         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1702         
1703         $hooks{$param{type}}{$param{id}}=\%param;
1704         return 1;
1707 sub run_hooks ($$) {
1708         # Calls the given sub for each hook of the given type,
1709         # passing it the hook function to call.
1710         my $type=shift;
1711         my $sub=shift;
1713         if (exists $hooks{$type}) {
1714                 my (@first, @middle, @last);
1715                 foreach my $id (keys %{$hooks{$type}}) {
1716                         if ($hooks{$type}{$id}{first}) {
1717                                 push @first, $id;
1718                         }
1719                         elsif ($hooks{$type}{$id}{last}) {
1720                                 push @last, $id;
1721                         }
1722                         else {
1723                                 push @middle, $id;
1724                         }
1725                 }
1726                 foreach my $id (@first, @middle, @last) {
1727                         $sub->($hooks{$type}{$id}{call});
1728                 }
1729         }
1731         return 1;
1734 sub rcs_update () {
1735         $hooks{rcs}{rcs_update}{call}->(@_);
1738 sub rcs_prepedit ($) {
1739         $hooks{rcs}{rcs_prepedit}{call}->(@_);
1742 sub rcs_commit ($$$;$$) {
1743         $hooks{rcs}{rcs_commit}{call}->(@_);
1746 sub rcs_commit_staged ($$$) {
1747         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1750 sub rcs_add ($) {
1751         $hooks{rcs}{rcs_add}{call}->(@_);
1754 sub rcs_remove ($) {
1755         $hooks{rcs}{rcs_remove}{call}->(@_);
1758 sub rcs_rename ($$) {
1759         $hooks{rcs}{rcs_rename}{call}->(@_);
1762 sub rcs_recentchanges ($) {
1763         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1766 sub rcs_diff ($) {
1767         $hooks{rcs}{rcs_diff}{call}->(@_);
1770 sub rcs_getctime ($) {
1771         $hooks{rcs}{rcs_getctime}{call}->(@_);
1774 sub rcs_receive () {
1775         $hooks{rcs}{rcs_receive}{call}->();
1778 sub add_depends ($$;$) {
1779         my $page=shift;
1780         my $pagespec=shift;
1781         my $deptype=shift || $DEPEND_CONTENT;
1783         # Is the pagespec a simple page name?
1784         if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1785             $pagespec !~ /[\s*?()!]/) {
1786                 $depends_simple{$page}{lc $pagespec} |= $deptype;
1787                 return 1;
1788         }
1790         # Add explicit dependencies for influences.
1791         my $sub=pagespec_translate($pagespec);
1792         return if $@;
1793         foreach my $p (keys %pagesources) {
1794                 my $r=$sub->($p, location => $page);
1795                 my $i=$r->influences;
1796                 foreach my $k (keys %$i) {
1797                         $depends_simple{$page}{lc $k} |= $i->{$k};
1798                 }
1799                 last if $r->influences_static;
1800         }
1802         $depends{$page}{$pagespec} |= $deptype;
1803         return 1;
1806 sub deptype (@) {
1807         my $deptype=0;
1808         foreach my $type (@_) {
1809                 if ($type eq 'presence') {
1810                         $deptype |= $DEPEND_PRESENCE;
1811                 }
1812                 elsif ($type eq 'links') { 
1813                         $deptype |= $DEPEND_LINKS;
1814                 }
1815                 elsif ($type eq 'content') {
1816                         $deptype |= $DEPEND_CONTENT;
1817                 }
1818         }
1819         return $deptype;
1822 my $file_prune_regexp;
1823 sub file_pruned ($;$) {
1824         my $file=shift;
1825         if (@_) {
1826                 require File::Spec;
1827                 $file=File::Spec->canonpath($file);
1828                 my $base=File::Spec->canonpath(shift);
1829                 return if $file eq $base;
1830                 $file =~ s#^\Q$base\E/+##;
1831         }
1833         if (defined $config{include} && length $config{include}) {
1834                 return 0 if $file =~ m/$config{include}/;
1835         }
1837         if (! defined $file_prune_regexp) {
1838                 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1839                 $file_prune_regexp=qr/$file_prune_regexp/;
1840         }
1841         return $file =~ m/$file_prune_regexp/;
1844 sub define_gettext () {
1845         # If translation is needed, redefine the gettext function to do it.
1846         # Otherwise, it becomes a quick no-op.
1847         my $gettext_obj;
1848         my $getobj;
1849         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1850             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1851             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1852                 $getobj=sub {
1853                         $gettext_obj=eval q{
1854                                 use Locale::gettext q{textdomain};
1855                                 Locale::gettext->domain('ikiwiki')
1856                         };
1857                 };
1858         }
1860         no warnings 'redefine';
1861         *gettext=sub {
1862                 $getobj->() if $getobj;
1863                 if ($gettext_obj) {
1864                         $gettext_obj->get(shift);
1865                 }
1866                 else {
1867                         return shift;
1868                 }
1869         };
1870         *ngettext=sub {
1871                 $getobj->() if $getobj;
1872                 if ($gettext_obj) {
1873                         $gettext_obj->nget(@_);
1874                 }
1875                 else {
1876                         return ($_[2] == 1 ? $_[0] : $_[1])
1877                 }
1878         };
1881 sub gettext {
1882         define_gettext();
1883         gettext(@_);
1886 sub ngettext {
1887         define_gettext();
1888         ngettext(@_);
1891 sub yesno ($) {
1892         my $val=shift;
1894         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1897 sub inject {
1898         # Injects a new function into the symbol table to replace an
1899         # exported function.
1900         my %params=@_;
1902         # This is deep ugly perl foo, beware.
1903         no strict;
1904         no warnings;
1905         if (! defined $params{parent}) {
1906                 $params{parent}='::';
1907                 $params{old}=\&{$params{name}};
1908                 $params{name}=~s/.*:://;
1909         }
1910         my $parent=$params{parent};
1911         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1912                 $ns = $params{parent} . $ns;
1913                 inject(%params, parent => $ns) unless $ns eq '::main::';
1914                 *{$ns . $params{name}} = $params{call}
1915                         if exists ${$ns}{$params{name}} &&
1916                            \&{${$ns}{$params{name}}} == $params{old};
1917         }
1918         use strict;
1919         use warnings;
1922 sub add_link ($$) {
1923         my $page=shift;
1924         my $link=shift;
1926         push @{$links{$page}}, $link
1927                 unless grep { $_ eq $link } @{$links{$page}};
1930 sub pagespec_translate ($) {
1931         my $spec=shift;
1933         # Convert spec to perl code.
1934         my $code="";
1935         my @data;
1936         while ($spec=~m{
1937                 \s*             # ignore whitespace
1938                 (               # 1: match a single word
1939                         \!              # !
1940                 |
1941                         \(              # (
1942                 |
1943                         \)              # )
1944                 |
1945                         \w+\([^\)]*\)   # command(params)
1946                 |
1947                         [^\s()]+        # any other text
1948                 )
1949                 \s*             # ignore whitespace
1950         }gx) {
1951                 my $word=$1;
1952                 if (lc $word eq 'and') {
1953                         $code.=' &';
1954                 }
1955                 elsif (lc $word eq 'or') {
1956                         $code.=' |';
1957                 }
1958                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1959                         $code.=' '.$word;
1960                 }
1961                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1962                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1963                                 push @data, $2;
1964                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
1965                         }
1966                         else {
1967                                 push @data, qq{unknown function in pagespec "$word"};
1968                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
1969                         }
1970                 }
1971                 else {
1972                         push @data, $word;
1973                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
1974                 }
1975         }
1977         if (! length $code) {
1978                 $code="IkiWiki::FailReason->new('empty pagespec')";
1979         }
1981         no warnings;
1982         return eval 'sub { my $page=shift; '.$code.' }';
1985 sub pagespec_match ($$;@) {
1986         my $page=shift;
1987         my $spec=shift;
1988         my @params=@_;
1990         # Backwards compatability with old calling convention.
1991         if (@params == 1) {
1992                 unshift @params, 'location';
1993         }
1995         my $sub=pagespec_translate($spec);
1996         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
1997                 if $@ || ! defined $sub;
1998         return $sub->($page, @params);
2001 sub pagespec_match_list ($$;@) {
2002         my $page=shift;
2003         my $pagespec=shift;
2004         my %params=@_;
2006         # Backwards compatability with old calling convention.
2007         if (ref $page) {
2008                 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2009                 $params{list}=$page;
2010                 $page=$params{location}; # ugh!
2011         }
2013         my $sub=pagespec_translate($pagespec);
2014         error "syntax error in pagespec \"$pagespec\""
2015                 if $@ || ! defined $sub;
2017         my @candidates;
2018         if (exists $params{list}) {
2019                 @candidates=exists $params{filter}
2020                         ? grep { ! $params{filter}->($_) } @{$params{list}}
2021                         : @{$params{list}};
2022         }
2023         else {
2024                 @candidates=exists $params{filter}
2025                         ? grep { ! $params{filter}->($_) } keys %pagesources
2026                         : keys %pagesources;
2027         }
2029         if (defined $params{sort}) {
2030                 my $f;
2031                 if ($params{sort} eq 'title') {
2032                         $f=sub { pagetitle(basename($a)) cmp pagetitle(basename($b)) };
2033                 }
2034                 elsif ($params{sort} eq 'title_natural') {
2035                         eval q{use Sort::Naturally};
2036                         if ($@) {
2037                                 error(gettext("Sort::Naturally needed for title_natural sort"));
2038                         }
2039                         $f=sub { Sort::Naturally::ncmp(pagetitle(basename($a)), pagetitle(basename($b))) };
2040                 }
2041                 elsif ($params{sort} eq 'mtime') {
2042                         $f=sub { $pagemtime{$b} <=> $pagemtime{$a} };
2043                 }
2044                 elsif ($params{sort} eq 'age') {
2045                         $f=sub { $pagectime{$b} <=> $pagectime{$a} };
2046                 }
2047                 else {
2048                         error sprintf(gettext("unknown sort type %s"), $params{sort});
2049                 }
2050                 @candidates = sort { &$f } @candidates;
2051         }
2053         @candidates=reverse(@candidates) if $params{reverse};
2054         
2055         $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2056         
2057         # clear params, remainder is passed to pagespec
2058         my $num=$params{num};
2059         delete @params{qw{num deptype reverse sort filter list}};
2060         
2061         my @matches;
2062         my $firstfail;
2063         my $count=0;
2064         my $accum=IkiWiki::SuccessReason->new();
2065         foreach my $p (@candidates) {
2066                 my $r=$sub->($p, %params, location => $page);
2067                 error(sprintf(gettext("cannot match pages: %s"), $r))
2068                         if $r->isa("IkiWiki::ErrorReason");
2069                 $accum |= $r;
2070                 if ($r) {
2071                         push @matches, $p;
2072                         last if defined $num && ++$count == $num;
2073                 }
2074         }
2076         # Add simple dependencies for accumulated influences.
2077         my $i=$accum->influences;
2078         foreach my $k (keys %$i) {
2079                 $depends_simple{$page}{lc $k} |= $i->{$k};
2080         }
2082         return @matches;
2085 sub pagespec_valid ($) {
2086         my $spec=shift;
2088         my $sub=pagespec_translate($spec);
2089         return ! $@;
2092 sub glob2re ($) {
2093         my $re=quotemeta(shift);
2094         $re=~s/\\\*/.*/g;
2095         $re=~s/\\\?/./g;
2096         return $re;
2099 package IkiWiki::FailReason;
2101 use overload (
2102         '""'    => sub { $_[0][0] },
2103         '0+'    => sub { 0 },
2104         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2105         '&'     => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2106         '|'     => sub { $_[1]->merge_influences($_[0]); $_[1] },
2107         fallback => 1,
2108 );
2110 our @ISA = 'IkiWiki::SuccessReason';
2112 package IkiWiki::SuccessReason;
2114 use overload (
2115         '""'    => sub { $_[0][0] },
2116         '0+'    => sub { 1 },
2117         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
2118         '&'     => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2119         '|'     => sub { $_[0]->merge_influences($_[1]); $_[0] },
2120         fallback => 1,
2121 );
2123 sub new {
2124         my $class = shift;
2125         my $value = shift;
2126         return bless [$value, {@_}], $class;
2129 sub influences {
2130         my $this=shift;
2131         $this->[1]={@_} if @_;
2132         my %i=%{$this->[1]};
2133         delete $i{""};
2134         return \%i;
2137 sub influences_static {
2138         return ! $_[0][1]->{""};
2141 sub merge_influences {
2142         my $this=shift;
2143         my $other=shift;
2144         my $anded=shift;
2146         if (! $anded || (($this || %{$this->[1]}) &&
2147                         ($other || %{$other->[1]}))) {
2148                 foreach my $influence (keys %{$other->[1]}) {
2149                         $this->[1]{$influence} |= $other->[1]{$influence};
2150                 }
2151         }
2152         else {
2153                 # influence blocker
2154                 $this->[1]={};
2155         }
2158 package IkiWiki::ErrorReason;
2160 our @ISA = 'IkiWiki::FailReason';
2162 package IkiWiki::PageSpec;
2164 sub derel ($$) {
2165         my $path=shift;
2166         my $from=shift;
2168         if ($path =~ m!^\./!) {
2169                 $from=~s#/?[^/]+$## if defined $from;
2170                 $path=~s#^\./##;
2171                 $path="$from/$path" if length $from;
2172         }
2174         return $path;
2177 sub match_glob ($$;@) {
2178         my $page=shift;
2179         my $glob=shift;
2180         my %params=@_;
2181         
2182         $glob=derel($glob, $params{location});
2184         my $regexp=IkiWiki::glob2re($glob);
2185         if ($page=~/^$regexp$/i) {
2186                 if (! IkiWiki::isinternal($page) || $params{internal}) {
2187                         return IkiWiki::SuccessReason->new("$glob matches $page");
2188                 }
2189                 else {
2190                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2191                 }
2192         }
2193         else {
2194                 return IkiWiki::FailReason->new("$glob does not match $page");
2195         }
2198 sub match_internal ($$;@) {
2199         return match_glob($_[0], $_[1], @_, internal => 1)
2202 sub match_link ($$;@) {
2203         my $page=shift;
2204         my $link=lc(shift);
2205         my %params=@_;
2207         $link=derel($link, $params{location});
2208         my $from=exists $params{location} ? $params{location} : '';
2210         my $links = $IkiWiki::links{$page};
2211         return IkiWiki::FailReason->new("$page has no links", "" => 1)
2212                 unless $links && @{$links};
2213         my $bestlink = IkiWiki::bestlink($from, $link);
2214         foreach my $p (@{$links}) {
2215                 if (length $bestlink) {
2216                         return IkiWiki::SuccessReason->new("$page links to $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2217                                 if $bestlink eq IkiWiki::bestlink($page, $p);
2218                 }
2219                 else {
2220                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2221                                 if match_glob($p, $link, %params);
2222                         my ($p_rel)=$p=~/^\/?(.*)/;
2223                         $link=~s/^\///;
2224                         return IkiWiki::SuccessReason->new("$page links to page $p_rel matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2225                                 if match_glob($p_rel, $link, %params);
2226                 }
2227         }
2228         return IkiWiki::FailReason->new("$page does not link to $link", "" => 1);
2231 sub match_backlink ($$;@) {
2232         my $ret=match_link($_[1], $_[0], @_);
2233         $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2234         return $ret;
2237 sub match_created_before ($$;@) {
2238         my $page=shift;
2239         my $testpage=shift;
2240         my %params=@_;
2241         
2242         $testpage=derel($testpage, $params{location});
2244         if (exists $IkiWiki::pagectime{$testpage}) {
2245                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2246                         return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2247                 }
2248                 else {
2249                         return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2250                 }
2251         }
2252         else {
2253                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2254         }
2257 sub match_created_after ($$;@) {
2258         my $page=shift;
2259         my $testpage=shift;
2260         my %params=@_;
2261         
2262         $testpage=derel($testpage, $params{location});
2264         if (exists $IkiWiki::pagectime{$testpage}) {
2265                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2266                         return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2267                 }
2268                 else {
2269                         return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2270                 }
2271         }
2272         else {
2273                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2274         }
2277 sub match_creation_day ($$;@) {
2278         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2279                 return IkiWiki::SuccessReason->new('creation_day matched');
2280         }
2281         else {
2282                 return IkiWiki::FailReason->new('creation_day did not match');
2283         }
2286 sub match_creation_month ($$;@) {
2287         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2288                 return IkiWiki::SuccessReason->new('creation_month matched');
2289         }
2290         else {
2291                 return IkiWiki::FailReason->new('creation_month did not match');
2292         }
2295 sub match_creation_year ($$;@) {
2296         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2297                 return IkiWiki::SuccessReason->new('creation_year matched');
2298         }
2299         else {
2300                 return IkiWiki::FailReason->new('creation_year did not match');
2301         }
2304 sub match_user ($$;@) {
2305         shift;
2306         my $user=shift;
2307         my %params=@_;
2308         
2309         my $regexp=IkiWiki::glob2re($user);
2310         
2311         if (! exists $params{user}) {
2312                 return IkiWiki::ErrorReason->new("no user specified");
2313         }
2315         if (defined $params{user} && $params{user}=~/^$regexp$/i) {
2316                 return IkiWiki::SuccessReason->new("user is $user");
2317         }
2318         elsif (! defined $params{user}) {
2319                 return IkiWiki::FailReason->new("not logged in");
2320         }
2321         else {
2322                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2323         }
2326 sub match_admin ($$;@) {
2327         shift;
2328         shift;
2329         my %params=@_;
2330         
2331         if (! exists $params{user}) {
2332                 return IkiWiki::ErrorReason->new("no user specified");
2333         }
2335         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2336                 return IkiWiki::SuccessReason->new("user is an admin");
2337         }
2338         elsif (! defined $params{user}) {
2339                 return IkiWiki::FailReason->new("not logged in");
2340         }
2341         else {
2342                 return IkiWiki::FailReason->new("user is not an admin");
2343         }
2346 sub match_ip ($$;@) {
2347         shift;
2348         my $ip=shift;
2349         my %params=@_;
2350         
2351         if (! exists $params{ip}) {
2352                 return IkiWiki::ErrorReason->new("no IP specified");
2353         }
2355         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2356                 return IkiWiki::SuccessReason->new("IP is $ip");
2357         }
2358         else {
2359                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2360         }