]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki.pm
Release to wheezy-security
[git.ikiwiki.info.git] / IkiWiki.pm
1 #!/usr/bin/perl
3 package IkiWiki;
5 use warnings;
6 use strict;
7 use Encode;
8 use URI::Escape q{uri_escape_utf8};
9 use POSIX ();
10 use Storable;
11 use open qw{:utf8 :std};
13 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
14         %pagestate %wikistate %renderedfiles %oldrenderedfiles
15         %pagesources %delpagesources %destsources %depends %depends_simple
16         @mass_depends %hooks %forcerebuild %loaded_plugins %typedlinks
17         %oldtypedlinks %autofiles};
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error htmlpage template template_depends
21         deptype add_depends pagespec_match pagespec_match_list bestlink
22         htmllink readfile writefile pagetype srcfile pagename
23         displaytime strftime_utf8 will_render gettext ngettext urlto targetpage
24         add_underlay pagetitle titlepage linkpage newpagefile
25         inject add_link add_autofile
26         %config %links %pagestate %wikistate %renderedfiles
27         %pagesources %destsources %typedlinks);
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("sortspec_translate");
41 memoize("pagespec_translate");
42 memoize("template_file");
44 sub getsetup () {
45         wikiname => {
46                 type => "string",
47                 default => "wiki",
48                 description => "name of the wiki",
49                 safe => 1,
50                 rebuild => 1,
51         },
52         adminemail => {
53                 type => "string",
54                 default => undef,
55                 example => 'me@example.com',
56                 description => "contact email for wiki",
57                 safe => 1,
58                 rebuild => 0,
59         },
60         adminuser => {
61                 type => "string",
62                 default => [],
63                 description => "users who are wiki admins",
64                 safe => 1,
65                 rebuild => 0,
66         },
67         banned_users => {
68                 type => "string",
69                 default => [],
70                 description => "users who are banned from the wiki",
71                 safe => 1,
72                 rebuild => 0,
73         },
74         srcdir => {
75                 type => "string",
76                 default => undef,
77                 example => "$ENV{HOME}/wiki",
78                 description => "where the source of the wiki is located",
79                 safe => 0, # path
80                 rebuild => 1,
81         },
82         destdir => {
83                 type => "string",
84                 default => undef,
85                 example => "/var/www/wiki",
86                 description => "where to build the wiki",
87                 safe => 0, # path
88                 rebuild => 1,
89         },
90         url => {
91                 type => "string",
92                 default => '',
93                 example => "http://example.com/wiki",
94                 description => "base url to the wiki",
95                 safe => 1,
96                 rebuild => 1,
97         },
98         cgiurl => {
99                 type => "string",
100                 default => '',
101                 example => "http://example.com/wiki/ikiwiki.cgi",
102                 description => "url to the ikiwiki.cgi",
103                 safe => 1,
104                 rebuild => 1,
105         },
106         cgi_wrapper => {
107                 type => "string",
108                 default => '',
109                 example => "/var/www/wiki/ikiwiki.cgi",
110                 description => "filename of cgi wrapper to generate",
111                 safe => 0, # file
112                 rebuild => 0,
113         },
114         cgi_wrappermode => {
115                 type => "string",
116                 default => '06755',
117                 description => "mode for cgi_wrapper (can safely be made suid)",
118                 safe => 0,
119                 rebuild => 0,
120         },
121         rcs => {
122                 type => "string",
123                 default => '',
124                 description => "rcs backend to use",
125                 safe => 0, # don't allow overriding
126                 rebuild => 0,
127         },
128         default_plugins => {
129                 type => "internal",
130                 default => [qw{mdwn link inline meta htmlscrubber passwordauth
131                                 openid signinedit lockedit conditional
132                                 recentchanges parentlinks editpage}],
133                 description => "plugins to enable by default",
134                 safe => 0,
135                 rebuild => 1,
136         },
137         add_plugins => {
138                 type => "string",
139                 default => [],
140                 description => "plugins to add to the default configuration",
141                 safe => 1,
142                 rebuild => 1,
143         },
144         disable_plugins => {
145                 type => "string",
146                 default => [],
147                 description => "plugins to disable",
148                 safe => 1,
149                 rebuild => 1,
150         },
151         templatedir => {
152                 type => "string",
153                 default => "$installdir/share/ikiwiki/templates",
154                 description => "additional directory to search for template files",
155                 advanced => 1,
156                 safe => 0, # path
157                 rebuild => 1,
158         },
159         underlaydir => {
160                 type => "string",
161                 default => "$installdir/share/ikiwiki/basewiki",
162                 description => "base wiki source location",
163                 advanced => 1,
164                 safe => 0, # path
165                 rebuild => 0,
166         },
167         underlaydirbase => {
168                 type => "internal",
169                 default => "$installdir/share/ikiwiki",
170                 description => "parent directory containing additional underlays",
171                 safe => 0,
172                 rebuild => 0,
173         },
174         wrappers => {
175                 type => "internal",
176                 default => [],
177                 description => "wrappers to generate",
178                 safe => 0,
179                 rebuild => 0,
180         },
181         underlaydirs => {
182                 type => "internal",
183                 default => [],
184                 description => "additional underlays to use",
185                 safe => 0,
186                 rebuild => 0,
187         },
188         verbose => {
189                 type => "boolean",
190                 example => 1,
191                 description => "display verbose messages?",
192                 safe => 1,
193                 rebuild => 0,
194         },
195         syslog => {
196                 type => "boolean",
197                 example => 1,
198                 description => "log to syslog?",
199                 safe => 1,
200                 rebuild => 0,
201         },
202         usedirs => {
203                 type => "boolean",
204                 default => 1,
205                 description => "create output files named page/index.html?",
206                 safe => 0, # changing requires manual transition
207                 rebuild => 1,
208         },
209         prefix_directives => {
210                 type => "boolean",
211                 default => 1,
212                 description => "use '!'-prefixed preprocessor directives?",
213                 safe => 0, # changing requires manual transition
214                 rebuild => 1,
215         },
216         indexpages => {
217                 type => "boolean",
218                 default => 0,
219                 description => "use page/index.mdwn source files",
220                 safe => 1,
221                 rebuild => 1,
222         },
223         discussion => {
224                 type => "boolean",
225                 default => 1,
226                 description => "enable Discussion pages?",
227                 safe => 1,
228                 rebuild => 1,
229         },
230         discussionpage => {
231                 type => "string",
232                 default => gettext("Discussion"),
233                 description => "name of Discussion pages",
234                 safe => 1,
235                 rebuild => 1,
236         },
237         html5 => {
238                 type => "boolean",
239                 default => 0,
240                 description => "generate HTML5?",
241                 advanced => 0,
242                 safe => 1,
243                 rebuild => 1,
244         },
245         sslcookie => {
246                 type => "boolean",
247                 default => 0,
248                 description => "only send cookies over SSL connections?",
249                 advanced => 1,
250                 safe => 1,
251                 rebuild => 0,
252         },
253         default_pageext => {
254                 type => "string",
255                 default => "mdwn",
256                 description => "extension to use for new pages",
257                 safe => 0, # not sanitized
258                 rebuild => 0,
259         },
260         htmlext => {
261                 type => "string",
262                 default => "html",
263                 description => "extension to use for html files",
264                 safe => 0, # not sanitized
265                 rebuild => 1,
266         },
267         timeformat => {
268                 type => "string",
269                 default => '%c',
270                 description => "strftime format string to display date",
271                 advanced => 1,
272                 safe => 1,
273                 rebuild => 1,
274         },
275         locale => {
276                 type => "string",
277                 default => undef,
278                 example => "en_US.UTF-8",
279                 description => "UTF-8 locale to use",
280                 advanced => 1,
281                 safe => 0,
282                 rebuild => 1,
283         },
284         userdir => {
285                 type => "string",
286                 default => "",
287                 example => "users",
288                 description => "put user pages below specified page",
289                 safe => 1,
290                 rebuild => 1,
291         },
292         numbacklinks => {
293                 type => "integer",
294                 default => 10,
295                 description => "how many backlinks to show before hiding excess (0 to show all)",
296                 safe => 1,
297                 rebuild => 1,
298         },
299         hardlink => {
300                 type => "boolean",
301                 default => 0,
302                 description => "attempt to hardlink source files? (optimisation for large files)",
303                 advanced => 1,
304                 safe => 0, # paranoia
305                 rebuild => 0,
306         },
307         umask => {
308                 type => "string",
309                 example => "public",
310                 description => "force ikiwiki to use a particular umask (keywords public, group or private, or a number)",
311                 advanced => 1,
312                 safe => 0, # paranoia
313                 rebuild => 0,
314         },
315         wrappergroup => {
316                 type => "string",
317                 example => "ikiwiki",
318                 description => "group for wrappers to run in",
319                 advanced => 1,
320                 safe => 0, # paranoia
321                 rebuild => 0,
322         },
323         libdir => {
324                 type => "string",
325                 default => "",
326                 example => "$ENV{HOME}/.ikiwiki/",
327                 description => "extra library and plugin directory",
328                 advanced => 1,
329                 safe => 0, # directory
330                 rebuild => 0,
331         },
332         ENV => {
333                 type => "string", 
334                 default => {},
335                 description => "environment variables",
336                 safe => 0, # paranoia
337                 rebuild => 0,
338         },
339         timezone => {
340                 type => "string", 
341                 default => "",
342                 example => "US/Eastern",
343                 description => "time zone name",
344                 safe => 1,
345                 rebuild => 1,
346         },
347         include => {
348                 type => "string",
349                 default => undef,
350                 example => '^\.htaccess$',
351                 description => "regexp of normally excluded files to include",
352                 advanced => 1,
353                 safe => 0, # regexp
354                 rebuild => 1,
355         },
356         exclude => {
357                 type => "string",
358                 default => undef,
359                 example => '^(*\.private|Makefile)$',
360                 description => "regexp of files that should be skipped",
361                 advanced => 1,
362                 safe => 0, # regexp
363                 rebuild => 1,
364         },
365         wiki_file_prune_regexps => {
366                 type => "internal",
367                 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
368                         qr/\.x?html?$/, qr/\.ikiwiki-new$/,
369                         qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
370                         qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
371                         qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
372                 description => "regexps of source files to ignore",
373                 safe => 0,
374                 rebuild => 1,
375         },
376         wiki_file_chars => {
377                 type => "string",
378                 description => "specifies the characters that are allowed in source filenames",
379                 default => "-[:alnum:]+/.:_",
380                 safe => 0,
381                 rebuild => 1,
382         },
383         wiki_file_regexp => {
384                 type => "internal",
385                 description => "regexp of legal source files",
386                 safe => 0,
387                 rebuild => 1,
388         },
389         web_commit_regexp => {
390                 type => "internal",
391                 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
392                 description => "regexp to parse web commits from logs",
393                 safe => 0,
394                 rebuild => 0,
395         },
396         cgi => {
397                 type => "internal",
398                 default => 0,
399                 description => "run as a cgi",
400                 safe => 0,
401                 rebuild => 0,
402         },
403         cgi_disable_uploads => {
404                 type => "internal",
405                 default => 1,
406                 description => "whether CGI should accept file uploads",
407                 safe => 0,
408                 rebuild => 0,
409         },
410         post_commit => {
411                 type => "internal",
412                 default => 0,
413                 description => "run as a post-commit hook",
414                 safe => 0,
415                 rebuild => 0,
416         },
417         rebuild => {
418                 type => "internal",
419                 default => 0,
420                 description => "running in rebuild mode",
421                 safe => 0,
422                 rebuild => 0,
423         },
424         setup => {
425                 type => "internal",
426                 default => undef,
427                 description => "running in setup mode",
428                 safe => 0,
429                 rebuild => 0,
430         },
431         clean => {
432                 type => "internal",
433                 default => 0,
434                 description => "running in clean mode",
435                 safe => 0,
436                 rebuild => 0,
437         },
438         refresh => {
439                 type => "internal",
440                 default => 0,
441                 description => "running in refresh mode",
442                 safe => 0,
443                 rebuild => 0,
444         },
445         test_receive => {
446                 type => "internal",
447                 default => 0,
448                 description => "running in receive test mode",
449                 safe => 0,
450                 rebuild => 0,
451         },
452         wrapper_background_command => {
453                 type => "internal",
454                 default => '',
455                 description => "background shell command to run",
456                 safe => 0,
457                 rebuild => 0,
458         },
459         gettime => {
460                 type => "internal",
461                 description => "running in gettime mode",
462                 safe => 0,
463                 rebuild => 0,
464         },
465         w3mmode => {
466                 type => "internal",
467                 default => 0,
468                 description => "running in w3mmode",
469                 safe => 0,
470                 rebuild => 0,
471         },
472         wikistatedir => {
473                 type => "internal",
474                 default => undef,
475                 description => "path to the .ikiwiki directory holding ikiwiki state",
476                 safe => 0,
477                 rebuild => 0,
478         },
479         setupfile => {
480                 type => "internal",
481                 default => undef,
482                 description => "path to setup file",
483                 safe => 0,
484                 rebuild => 0,
485         },
486         setuptype => {
487                 type => "internal",
488                 default => "Yaml",
489                 description => "perl class to use to dump setup file",
490                 safe => 0,
491                 rebuild => 0,
492         },
493         allow_symlinks_before_srcdir => {
494                 type => "boolean",
495                 default => 0,
496                 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
497                 safe => 0,
498                 rebuild => 0,
499         },
502 sub defaultconfig () {
503         my %s=getsetup();
504         my @ret;
505         foreach my $key (keys %s) {
506                 push @ret, $key, $s{$key}->{default};
507         }
508         return @ret;
511 # URL to top of wiki as a path starting with /, valid from any wiki page or
512 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
513 my $local_url;
514 # URL to CGI script, similar to $local_url
515 my $local_cgiurl;
517 sub checkconfig () {
518         # locale stuff; avoid LC_ALL since it overrides everything
519         if (defined $ENV{LC_ALL}) {
520                 $ENV{LANG} = $ENV{LC_ALL};
521                 delete $ENV{LC_ALL};
522         }
523         if (defined $config{locale}) {
524                 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
525                         $ENV{LANG}=$config{locale};
526                         define_gettext();
527                 }
528         }
529                 
530         if (! defined $config{wiki_file_regexp}) {
531                 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
532         }
534         if (ref $config{ENV} eq 'HASH') {
535                 foreach my $val (keys %{$config{ENV}}) {
536                         $ENV{$val}=$config{ENV}{$val};
537                 }
538         }
539         if (defined $config{timezone} && length $config{timezone}) {
540                 $ENV{TZ}=$config{timezone};
541         }
542         else {
543                 $config{timezone}=$ENV{TZ};
544         }
546         if ($config{w3mmode}) {
547                 eval q{use Cwd q{abs_path}};
548                 error($@) if $@;
549                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
550                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
551                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
552                         unless $config{cgiurl} =~ m!file:///!;
553                 $config{url}="file://".$config{destdir};
554         }
556         if ($config{cgi} && ! length $config{url}) {
557                 error(gettext("Must specify url to wiki with --url when using --cgi"));
558         }
560         if (defined $config{url} && length $config{url}) {
561                 eval q{use URI};
562                 my $baseurl = URI->new($config{url});
564                 $local_url = $baseurl->path . "/";
565                 $local_cgiurl = undef;
567                 if (length $config{cgiurl}) {
568                         my $cgiurl = URI->new($config{cgiurl});
570                         $local_cgiurl = $cgiurl->path;
572                         if ($cgiurl->scheme ne $baseurl->scheme or
573                                 $cgiurl->authority ne $baseurl->authority) {
574                                 # too far apart, fall back to absolute URLs
575                                 $local_url = "$config{url}/";
576                                 $local_cgiurl = $config{cgiurl};
577                         }
578                 }
580                 $local_url =~ s{//$}{/};
581         }
582         else {
583                 $local_cgiurl = $config{cgiurl};
584         }
586         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
587                 unless exists $config{wikistatedir} && defined $config{wikistatedir};
589         if (defined $config{umask}) {
590                 my $u = possibly_foolish_untaint($config{umask});
592                 if ($u =~ m/^\d+$/) {
593                         umask($u);
594                 }
595                 elsif ($u eq 'private') {
596                         umask(077);
597                 }
598                 elsif ($u eq 'group') {
599                         umask(027);
600                 }
601                 elsif ($u eq 'public') {
602                         umask(022);
603                 }
604                 else {
605                         error(sprintf(gettext("unsupported umask setting %s"), $u));
606                 }
607         }
609         run_hooks(checkconfig => sub { shift->() });
611         return 1;
614 sub listplugins () {
615         my %ret;
617         foreach my $dir (@INC, $config{libdir}) {
618                 next unless defined $dir && length $dir;
619                 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
620                         my ($plugin)=$file=~/.*\/(.*)\.pm$/;
621                         $ret{$plugin}=1;
622                 }
623         }
624         foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
625                 next unless defined $dir && length $dir;
626                 foreach my $file (glob("$dir/plugins/*")) {
627                         $ret{basename($file)}=1 if -x $file;
628                 }
629         }
631         return keys %ret;
634 sub loadplugins () {
635         if (defined $config{libdir} && length $config{libdir}) {
636                 unshift @INC, possibly_foolish_untaint($config{libdir});
637         }
639         foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
640                 loadplugin($plugin);
641         }
642         
643         if ($config{rcs}) {
644                 if (exists $hooks{rcs}) {
645                         error(gettext("cannot use multiple rcs plugins"));
646                 }
647                 loadplugin($config{rcs});
648         }
649         if (! exists $hooks{rcs}) {
650                 loadplugin("norcs");
651         }
653         run_hooks(getopt => sub { shift->() });
654         if (grep /^-/, @ARGV) {
655                 print STDERR "Unknown option (or missing parameter): $_\n"
656                         foreach grep /^-/, @ARGV;
657                 usage();
658         }
660         return 1;
663 sub loadplugin ($;$) {
664         my $plugin=shift;
665         my $force=shift;
667         return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
669         foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
670                          "$installdir/lib/ikiwiki") {
671                 if (defined $dir && -x "$dir/plugins/$plugin") {
672                         eval { require IkiWiki::Plugin::external };
673                         if ($@) {
674                                 my $reason=$@;
675                                 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
676                         }
677                         import IkiWiki::Plugin::external "$dir/plugins/$plugin";
678                         $loaded_plugins{$plugin}=1;
679                         return 1;
680                 }
681         }
683         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
684         eval qq{use $mod};
685         if ($@) {
686                 error("Failed to load plugin $mod: $@");
687         }
688         $loaded_plugins{$plugin}=1;
689         return 1;
692 sub error ($;$) {
693         my $message=shift;
694         my $cleaner=shift;
695         log_message('err' => $message) if $config{syslog};
696         if (defined $cleaner) {
697                 $cleaner->();
698         }
699         die $message."\n";
702 sub debug ($) {
703         return unless $config{verbose};
704         return log_message(debug => @_);
707 my $log_open=0;
708 sub log_message ($$) {
709         my $type=shift;
711         if ($config{syslog}) {
712                 require Sys::Syslog;
713                 if (! $log_open) {
714                         Sys::Syslog::setlogsock('unix');
715                         Sys::Syslog::openlog('ikiwiki', '', 'user');
716                         $log_open=1;
717                 }
718                 return eval {
719                         Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
720                 };
721         }
722         elsif (! $config{cgi}) {
723                 return print "@_\n";
724         }
725         else {
726                 return print STDERR "@_\n";
727         }
730 sub possibly_foolish_untaint ($) {
731         my $tainted=shift;
732         my ($untainted)=$tainted=~/(.*)/s;
733         return $untainted;
736 sub basename ($) {
737         my $file=shift;
739         $file=~s!.*/+!!;
740         return $file;
743 sub dirname ($) {
744         my $file=shift;
746         $file=~s!/*[^/]+$!!;
747         return $file;
750 sub isinternal ($) {
751         my $page=shift;
752         return exists $pagesources{$page} &&
753                 $pagesources{$page} =~ /\._([^.]+)$/;
756 sub pagetype ($) {
757         my $file=shift;
758         
759         if ($file =~ /\.([^.]+)$/) {
760                 return $1 if exists $hooks{htmlize}{$1};
761         }
762         my $base=basename($file);
763         if (exists $hooks{htmlize}{$base} &&
764             $hooks{htmlize}{$base}{noextension}) {
765                 return $base;
766         }
767         return;
770 my %pagename_cache;
772 sub pagename ($) {
773         my $file=shift;
775         if (exists $pagename_cache{$file}) {
776                 return $pagename_cache{$file};
777         }
779         my $type=pagetype($file);
780         my $page=$file;
781         $page=~s/\Q.$type\E*$//
782                 if defined $type && !$hooks{htmlize}{$type}{keepextension}
783                         && !$hooks{htmlize}{$type}{noextension};
784         if ($config{indexpages} && $page=~/(.*)\/index$/) {
785                 $page=$1;
786         }
788         $pagename_cache{$file} = $page;
789         return $page;
792 sub newpagefile ($$) {
793         my $page=shift;
794         my $type=shift;
796         if (! $config{indexpages} || $page eq 'index') {
797                 return $page.".".$type;
798         }
799         else {
800                 return $page."/index.".$type;
801         }
804 sub targetpage ($$;$) {
805         my $page=shift;
806         my $ext=shift;
807         my $filename=shift;
808         
809         if (defined $filename) {
810                 return $page."/".$filename.".".$ext;
811         }
812         elsif (! $config{usedirs} || $page eq 'index') {
813                 return $page.".".$ext;
814         }
815         else {
816                 return $page."/index.".$ext;
817         }
820 sub htmlpage ($) {
821         my $page=shift;
822         
823         return targetpage($page, $config{htmlext});
826 sub srcfile_stat {
827         my $file=shift;
828         my $nothrow=shift;
830         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
831         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
832                 return "$dir/$file", stat(_) if -e "$dir/$file";
833         }
834         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
835         return;
838 sub srcfile ($;$) {
839         return (srcfile_stat(@_))[0];
842 sub add_literal_underlay ($) {
843         my $dir=shift;
845         if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
846                 unshift @{$config{underlaydirs}}, $dir;
847         }
850 sub add_underlay ($) {
851         my $dir = shift;
853         if ($dir !~ /^\//) {
854                 $dir="$config{underlaydirbase}/$dir";
855         }
857         add_literal_underlay($dir);
858         # why does it return 1? we just don't know
859         return 1;
862 sub readfile ($;$$) {
863         my $file=shift;
864         my $binary=shift;
865         my $wantfd=shift;
867         if (-l $file) {
868                 error("cannot read a symlink ($file)");
869         }
870         
871         local $/=undef;
872         open (my $in, "<", $file) || error("failed to read $file: $!");
873         binmode($in) if ($binary);
874         return \*$in if $wantfd;
875         my $ret=<$in>;
876         # check for invalid utf-8, and toss it back to avoid crashes
877         if (! utf8::valid($ret)) {
878                 $ret=encode_utf8($ret);
879         }
880         close $in || error("failed to read $file: $!");
881         return $ret;
884 sub prep_writefile ($$) {
885         my $file=shift;
886         my $destdir=shift;
887         
888         my $test=$file;
889         while (length $test) {
890                 if (-l "$destdir/$test") {
891                         error("cannot write to a symlink ($test)");
892                 }
893                 if (-f _ && $test ne $file) {
894                         # Remove conflicting file.
895                         foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
896                                 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
897                                         if ($f eq $test) {
898                                                 unlink("$destdir/$test");
899                                                 last;
900                                         }
901                                 }
902                         }
903                 }
904                 $test=dirname($test);
905         }
907         my $dir=dirname("$destdir/$file");
908         if (! -d $dir) {
909                 my $d="";
910                 foreach my $s (split(m!/+!, $dir)) {
911                         $d.="$s/";
912                         if (! -d $d) {
913                                 mkdir($d) || error("failed to create directory $d: $!");
914                         }
915                 }
916         }
918         return 1;
921 sub writefile ($$$;$$) {
922         my $file=shift; # can include subdirs
923         my $destdir=shift; # directory to put file in
924         my $content=shift;
925         my $binary=shift;
926         my $writer=shift;
927         
928         prep_writefile($file, $destdir);
929         
930         my $newfile="$destdir/$file.ikiwiki-new";
931         if (-l $newfile) {
932                 error("cannot write to a symlink ($newfile)");
933         }
934         
935         my $cleanup = sub { unlink($newfile) };
936         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
937         binmode($out) if ($binary);
938         if ($writer) {
939                 $writer->(\*$out, $cleanup);
940         }
941         else {
942                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
943         }
944         close $out || error("failed saving $newfile: $!", $cleanup);
945         rename($newfile, "$destdir/$file") || 
946                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
948         return 1;
951 my %cleared;
952 sub will_render ($$;$) {
953         my $page=shift;
954         my $dest=shift;
955         my $clear=shift;
957         # Important security check for independently created files.
958         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
959             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
960                 my $from_other_page=0;
961                 # Expensive, but rarely runs.
962                 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
963                         if (grep {
964                                 $_ eq $dest ||
965                                 dirname($_) eq $dest
966                             } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
967                                 $from_other_page=1;
968                                 last;
969                         }
970                 }
972                 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
973                         unless $from_other_page;
974         }
976         # If $dest exists as a directory, remove conflicting files in it
977         # rendered from other pages.
978         if (-d _) {
979                 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
980                         foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
981                                 if (dirname($f) eq $dest) {
982                                         unlink("$config{destdir}/$f");
983                                         rmdir(dirname("$config{destdir}/$f"));
984                                 }
985                         }
986                 }
987         }
989         if (! $clear || $cleared{$page}) {
990                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
991         }
992         else {
993                 foreach my $old (@{$renderedfiles{$page}}) {
994                         delete $destsources{$old};
995                 }
996                 $renderedfiles{$page}=[$dest];
997                 $cleared{$page}=1;
998         }
999         $destsources{$dest}=$page;
1001         return 1;
1004 sub bestlink ($$) {
1005         my $page=shift;
1006         my $link=shift;
1007         
1008         my $cwd=$page;
1009         if ($link=~s/^\/+//) {
1010                 # absolute links
1011                 $cwd="";
1012         }
1013         $link=~s/\/$//;
1015         do {
1016                 my $l=$cwd;
1017                 $l.="/" if length $l;
1018                 $l.=$link;
1020                 if (exists $pagesources{$l}) {
1021                         return $l;
1022                 }
1023                 elsif (exists $pagecase{lc $l}) {
1024                         return $pagecase{lc $l};
1025                 }
1026         } while $cwd=~s{/?[^/]+$}{};
1028         if (length $config{userdir}) {
1029                 my $l = "$config{userdir}/".lc($link);
1030                 if (exists $pagesources{$l}) {
1031                         return $l;
1032                 }
1033                 elsif (exists $pagecase{lc $l}) {
1034                         return $pagecase{lc $l};
1035                 }
1036         }
1038         #print STDERR "warning: page $page, broken link: $link\n";
1039         return "";
1042 sub isinlinableimage ($) {
1043         my $file=shift;
1044         
1045         return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1048 sub pagetitle ($;$) {
1049         my $page=shift;
1050         my $unescaped=shift;
1052         if ($unescaped) {
1053                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1054         }
1055         else {
1056                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1057         }
1059         return $page;
1062 sub titlepage ($) {
1063         my $title=shift;
1064         # support use w/o %config set
1065         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1066         $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1067         return $title;
1070 sub linkpage ($) {
1071         my $link=shift;
1072         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1073         $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1074         return $link;
1077 sub cgiurl (@) {
1078         my %params=@_;
1080         my $cgiurl=$local_cgiurl;
1082         if (exists $params{cgiurl}) {
1083                 $cgiurl=$params{cgiurl};
1084                 delete $params{cgiurl};
1085         }
1087         unless (%params) {
1088                 return $cgiurl;
1089         }
1091         return $cgiurl."?".
1092                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1095 sub cgiurl_abs (@) {
1096         eval q{use URI};
1097         URI->new_abs(cgiurl(@_), $config{cgiurl});
1100 sub baseurl (;$) {
1101         my $page=shift;
1103         return $local_url if ! defined $page;
1104         
1105         $page=htmlpage($page);
1106         $page=~s/[^\/]+$//;
1107         $page=~s/[^\/]+\//..\//g;
1108         return $page;
1111 sub urlabs ($$) {
1112         my $url=shift;
1113         my $urlbase=shift;
1115         return $url unless defined $urlbase && length $urlbase;
1117         eval q{use URI};
1118         URI->new_abs($url, $urlbase)->as_string;
1121 sub abs2rel ($$) {
1122         # Work around very innefficient behavior in File::Spec if abs2rel
1123         # is passed two relative paths. It's much faster if paths are
1124         # absolute! (Debian bug #376658; fixed in debian unstable now)
1125         my $path="/".shift;
1126         my $base="/".shift;
1128         require File::Spec;
1129         my $ret=File::Spec->abs2rel($path, $base);
1130         $ret=~s/^// if defined $ret;
1131         return $ret;
1134 sub displaytime ($;$$) {
1135         # Plugins can override this function to mark up the time to
1136         # display.
1137         my $time=formattime($_[0], $_[1]);
1138         if ($config{html5}) {
1139                 return '<time datetime="'.date_3339($_[0]).'"'.
1140                         ($_[2] ? ' pubdate="pubdate"' : '').
1141                         '>'.$time.'</time>';
1142         }
1143         else {
1144                 return '<span class="date">'.$time.'</span>';
1145         }
1148 sub formattime ($;$) {
1149         # Plugins can override this function to format the time.
1150         my $time=shift;
1151         my $format=shift;
1152         if (! defined $format) {
1153                 $format=$config{timeformat};
1154         }
1156         return strftime_utf8($format, localtime($time));
1159 my $strftime_encoding;
1160 sub strftime_utf8 {
1161         # strftime doesn't know about encodings, so make sure
1162         # its output is properly treated as utf8.
1163         # Note that this does not handle utf-8 in the format string.
1164         ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1165                 unless defined $strftime_encoding;
1166         $strftime_encoding
1167                 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1168                 : POSIX::strftime(@_);
1171 sub date_3339 ($) {
1172         my $time=shift;
1174         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1175         POSIX::setlocale(&POSIX::LC_TIME, "C");
1176         my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1177         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1178         return $ret;
1181 sub beautify_urlpath ($) {
1182         my $url=shift;
1184         # Ensure url is not an empty link, and if necessary,
1185         # add ./ to avoid colon confusion.
1186         if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1187                 $url="./$url";
1188         }
1190         if ($config{usedirs}) {
1191                 $url =~ s!/index.$config{htmlext}$!/!;
1192         }
1194         return $url;
1197 sub urlto ($;$$) {
1198         my $to=shift;
1199         my $from=shift;
1200         my $absolute=shift;
1201         
1202         if (! length $to) {
1203                 $to = 'index';
1204         }
1206         if (! $destsources{$to}) {
1207                 $to=htmlpage($to);
1208         }
1210         if ($absolute) {
1211                 return $config{url}.beautify_urlpath("/".$to);
1212         }
1214         if (! defined $from) {
1215                 my $u = $local_url || '';
1216                 $u =~ s{/$}{};
1217                 return $u.beautify_urlpath("/".$to);
1218         }
1220         my $link = abs2rel($to, dirname(htmlpage($from)));
1222         return beautify_urlpath($link);
1225 sub isselflink ($$) {
1226         # Plugins can override this function to support special types
1227         # of selflinks.
1228         my $page=shift;
1229         my $link=shift;
1231         return $page eq $link;
1234 sub htmllink ($$$;@) {
1235         my $lpage=shift; # the page doing the linking
1236         my $page=shift; # the page that will contain the link (different for inline)
1237         my $link=shift;
1238         my %opts=@_;
1240         $link=~s/\/$//;
1242         my $bestlink;
1243         if (! $opts{forcesubpage}) {
1244                 $bestlink=bestlink($lpage, $link);
1245         }
1246         else {
1247                 $bestlink="$lpage/".lc($link);
1248         }
1250         my $linktext;
1251         if (defined $opts{linktext}) {
1252                 $linktext=$opts{linktext};
1253         }
1254         else {
1255                 $linktext=pagetitle(basename($link));
1256         }
1257         
1258         return "<span class=\"selflink\">$linktext</span>"
1259                 if length $bestlink && isselflink($page, $bestlink) &&
1260                    ! defined $opts{anchor};
1261         
1262         if (! $destsources{$bestlink}) {
1263                 $bestlink=htmlpage($bestlink);
1265                 if (! $destsources{$bestlink}) {
1266                         my $cgilink = "";
1267                         if (length $config{cgiurl}) {
1268                                 $cgilink = "<a href=\"".
1269                                         cgiurl(
1270                                                 do => "create",
1271                                                 page => $link,
1272                                                 from => $lpage
1273                                         )."\" rel=\"nofollow\">?</a>";
1274                         }
1275                         return "<span class=\"createlink\">$cgilink$linktext</span>"
1276                 }
1277         }
1278         
1279         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1280         $bestlink=beautify_urlpath($bestlink);
1281         
1282         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1283                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1284         }
1286         if (defined $opts{anchor}) {
1287                 $bestlink.="#".$opts{anchor};
1288         }
1290         my @attrs;
1291         foreach my $attr (qw{rel class title}) {
1292                 if (defined $opts{$attr}) {
1293                         push @attrs, " $attr=\"$opts{$attr}\"";
1294                 }
1295         }
1297         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1300 sub userpage ($) {
1301         my $user=shift;
1302         return length $config{userdir} ? "$config{userdir}/$user" : $user;
1305 sub openiduser ($) {
1306         my $user=shift;
1308         if (defined $user && $user =~ m!^https?://! &&
1309             eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1310                 my $display;
1312                 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1313                         $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1314                 }
1315                 else {
1316                         # backcompat with old version
1317                         my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1318                         $display=$oid->display;
1319                 }
1321                 # Convert "user.somehost.com" to "user [somehost.com]"
1322                 # (also "user.somehost.co.uk")
1323                 if ($display !~ /\[/) {
1324                         $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1325                 }
1326                 # Convert "http://somehost.com/user" to "user [somehost.com]".
1327                 # (also "https://somehost.com/user/")
1328                 if ($display !~ /\[/) {
1329                         $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1330                 }
1331                 $display=~s!^https?://!!; # make sure this is removed
1332                 eval q{use CGI 'escapeHTML'};
1333                 error($@) if $@;
1334                 return escapeHTML($display);
1335         }
1336         return;
1339 sub htmlize ($$$$) {
1340         my $page=shift;
1341         my $destpage=shift;
1342         my $type=shift;
1343         my $content=shift;
1344         
1345         my $oneline = $content !~ /\n/;
1346         
1347         if (exists $hooks{htmlize}{$type}) {
1348                 $content=$hooks{htmlize}{$type}{call}->(
1349                         page => $page,
1350                         content => $content,
1351                 );
1352         }
1353         else {
1354                 error("htmlization of $type not supported");
1355         }
1357         run_hooks(sanitize => sub {
1358                 $content=shift->(
1359                         page => $page,
1360                         destpage => $destpage,
1361                         content => $content,
1362                 );
1363         });
1364         
1365         if ($oneline) {
1366                 # hack to get rid of enclosing junk added by markdown
1367                 # and other htmlizers/sanitizers
1368                 $content=~s/^<p>//i;
1369                 $content=~s/<\/p>\n*$//i;
1370         }
1372         return $content;
1375 sub linkify ($$$) {
1376         my $page=shift;
1377         my $destpage=shift;
1378         my $content=shift;
1380         run_hooks(linkify => sub {
1381                 $content=shift->(
1382                         page => $page,
1383                         destpage => $destpage,
1384                         content => $content,
1385                 );
1386         });
1387         
1388         return $content;
1391 our %preprocessing;
1392 our $preprocess_preview=0;
1393 sub preprocess ($$$;$$) {
1394         my $page=shift; # the page the data comes from
1395         my $destpage=shift; # the page the data will appear in (different for inline)
1396         my $content=shift;
1397         my $scan=shift;
1398         my $preview=shift;
1400         # Using local because it needs to be set within any nested calls
1401         # of this function.
1402         local $preprocess_preview=$preview if defined $preview;
1404         my $handle=sub {
1405                 my $escape=shift;
1406                 my $prefix=shift;
1407                 my $command=shift;
1408                 my $params=shift;
1409                 $params="" if ! defined $params;
1411                 if (length $escape) {
1412                         return "[[$prefix$command $params]]";
1413                 }
1414                 elsif (exists $hooks{preprocess}{$command}) {
1415                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1416                         # Note: preserve order of params, some plugins may
1417                         # consider it significant.
1418                         my @params;
1419                         while ($params =~ m{
1420                                 (?:([-\w]+)=)?          # 1: named parameter key?
1421                                 (?:
1422                                         """(.*?)"""     # 2: triple-quoted value
1423                                 |
1424                                         "([^"]*?)"      # 3: single-quoted value
1425                                 |
1426                                         '''(.*?)'''     # 4: triple-single-quote
1427                                 |
1428                                         <<([a-zA-Z]+)\n # 5: heredoc start
1429                                         (.*?)\n\5       # 6: heredoc value
1430                                 |
1431                                         (\S+)           # 7: unquoted value
1432                                 )
1433                                 (?:\s+|$)               # delimiter to next param
1434                         }msgx) {
1435                                 my $key=$1;
1436                                 my $val;
1437                                 if (defined $2) {
1438                                         $val=$2;
1439                                         $val=~s/\r\n/\n/mg;
1440                                         $val=~s/^\n+//g;
1441                                         $val=~s/\n+$//g;
1442                                 }
1443                                 elsif (defined $3) {
1444                                         $val=$3;
1445                                 }
1446                                 elsif (defined $4) {
1447                                         $val=$4;
1448                                 }
1449                                 elsif (defined $7) {
1450                                         $val=$7;
1451                                 }
1452                                 elsif (defined $6) {
1453                                         $val=$6;
1454                                 }
1456                                 if (defined $key) {
1457                                         push @params, $key, $val;
1458                                 }
1459                                 else {
1460                                         push @params, $val, '';
1461                                 }
1462                         }
1463                         if ($preprocessing{$page}++ > 3) {
1464                                 # Avoid loops of preprocessed pages preprocessing
1465                                 # other pages that preprocess them, etc.
1466                                 return "[[!$command <span class=\"error\">".
1467                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1468                                                 $page, $preprocessing{$page}).
1469                                         "</span>]]";
1470                         }
1471                         my $ret;
1472                         if (! $scan) {
1473                                 $ret=eval {
1474                                         $hooks{preprocess}{$command}{call}->(
1475                                                 @params,
1476                                                 page => $page,
1477                                                 destpage => $destpage,
1478                                                 preview => $preprocess_preview,
1479                                         );
1480                                 };
1481                                 if ($@) {
1482                                         my $error=$@;
1483                                         chomp $error;
1484                                         eval q{use HTML::Entities};
1485                                         $error = encode_entities($error);
1486                                         $ret="[[!$command <span class=\"error\">".
1487                                                 gettext("Error").": $error"."</span>]]";
1488                                 }
1489                         }
1490                         else {
1491                                 # use void context during scan pass
1492                                 eval {
1493                                         $hooks{preprocess}{$command}{call}->(
1494                                                 @params,
1495                                                 page => $page,
1496                                                 destpage => $destpage,
1497                                                 preview => $preprocess_preview,
1498                                         );
1499                                 };
1500                                 $ret="";
1501                         }
1502                         $preprocessing{$page}--;
1503                         return $ret;
1504                 }
1505                 else {
1506                         return "[[$prefix$command $params]]";
1507                 }
1508         };
1509         
1510         my $regex;
1511         if ($config{prefix_directives}) {
1512                 $regex = qr{
1513                         (\\?)           # 1: escape?
1514                         \[\[(!)         # directive open; 2: prefix
1515                         ([-\w]+)        # 3: command
1516                         (               # 4: the parameters..
1517                                 \s+     # Must have space if parameters present
1518                                 (?:
1519                                         (?:[-\w]+=)?            # named parameter key?
1520                                         (?:
1521                                                 """.*?"""       # triple-quoted value
1522                                                 |
1523                                                 "[^"]*?"        # single-quoted value
1524                                                 |
1525                                                 '''.*?'''       # triple-single-quote
1526                                                 |
1527                                                 <<([a-zA-Z]+)\n # 5: heredoc start
1528                                                 (?:.*?)\n\5     # heredoc value
1529                                                 |
1530                                                 [^"\s\]]+       # unquoted value
1531                                         )
1532                                         \s*                     # whitespace or end
1533                                                                 # of directive
1534                                 )
1535                         *)?             # 0 or more parameters
1536                         \]\]            # directive closed
1537                 }sx;
1538         }
1539         else {
1540                 $regex = qr{
1541                         (\\?)           # 1: escape?
1542                         \[\[(!?)        # directive open; 2: optional prefix
1543                         ([-\w]+)        # 3: command
1544                         \s+
1545                         (               # 4: the parameters..
1546                                 (?:
1547                                         (?:[-\w]+=)?            # named parameter key?
1548                                         (?:
1549                                                 """.*?"""       # triple-quoted value
1550                                                 |
1551                                                 "[^"]*?"        # single-quoted value
1552                                                 |
1553                                                 '''.*?'''       # triple-single-quote
1554                                                 |
1555                                                 <<([a-zA-Z]+)\n # 5: heredoc start
1556                                                 (?:.*?)\n\5     # heredoc value
1557                                                 |
1558                                                 [^"\s\]]+       # unquoted value
1559                                         )
1560                                         \s*                     # whitespace or end
1561                                                                 # of directive
1562                                 )
1563                         *)              # 0 or more parameters
1564                         \]\]            # directive closed
1565                 }sx;
1566         }
1568         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1569         return $content;
1572 sub filter ($$$) {
1573         my $page=shift;
1574         my $destpage=shift;
1575         my $content=shift;
1577         run_hooks(filter => sub {
1578                 $content=shift->(page => $page, destpage => $destpage, 
1579                         content => $content);
1580         });
1582         return $content;
1585 sub check_canedit ($$$;$) {
1586         my $page=shift;
1587         my $q=shift;
1588         my $session=shift;
1589         my $nonfatal=shift;
1590         
1591         my $canedit;
1592         run_hooks(canedit => sub {
1593                 return if defined $canedit;
1594                 my $ret=shift->($page, $q, $session);
1595                 if (defined $ret) {
1596                         if ($ret eq "") {
1597                                 $canedit=1;
1598                         }
1599                         elsif (ref $ret eq 'CODE') {
1600                                 $ret->() unless $nonfatal;
1601                                 $canedit=0;
1602                         }
1603                         elsif (defined $ret) {
1604                                 error($ret) unless $nonfatal;
1605                                 $canedit=0;
1606                         }
1607                 }
1608         });
1609         return defined $canedit ? $canedit : 1;
1612 sub check_content (@) {
1613         my %params=@_;
1614         
1615         return 1 if ! exists $hooks{checkcontent}; # optimisation
1617         if (exists $pagesources{$params{page}}) {
1618                 my @diff;
1619                 my %old=map { $_ => 1 }
1620                         split("\n", readfile(srcfile($pagesources{$params{page}})));
1621                 foreach my $line (split("\n", $params{content})) {
1622                         push @diff, $line if ! exists $old{$line};
1623                 }
1624                 $params{diff}=join("\n", @diff);
1625         }
1627         my $ok;
1628         run_hooks(checkcontent => sub {
1629                 return if defined $ok;
1630                 my $ret=shift->(%params);
1631                 if (defined $ret) {
1632                         if ($ret eq "") {
1633                                 $ok=1;
1634                         }
1635                         elsif (ref $ret eq 'CODE') {
1636                                 $ret->() unless $params{nonfatal};
1637                                 $ok=0;
1638                         }
1639                         elsif (defined $ret) {
1640                                 error($ret) unless $params{nonfatal};
1641                                 $ok=0;
1642                         }
1643                 }
1645         });
1646         return defined $ok ? $ok : 1;
1649 sub check_canchange (@) {
1650         my %params = @_;
1651         my $cgi = $params{cgi};
1652         my $session = $params{session};
1653         my @changes = @{$params{changes}};
1655         my %newfiles;
1656         foreach my $change (@changes) {
1657                 # This untaint is safe because we check file_pruned and
1658                 # wiki_file_regexp.
1659                 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1660                 $file=possibly_foolish_untaint($file);
1661                 if (! defined $file || ! length $file ||
1662                     file_pruned($file)) {
1663                         error(gettext("bad file name %s"), $file);
1664                 }
1666                 my $type=pagetype($file);
1667                 my $page=pagename($file) if defined $type;
1669                 if ($change->{action} eq 'add') {
1670                         $newfiles{$file}=1;
1671                 }
1673                 if ($change->{action} eq 'change' ||
1674                     $change->{action} eq 'add') {
1675                         if (defined $page) {
1676                                 check_canedit($page, $cgi, $session);
1677                                 next;
1678                         }
1679                         else {
1680                                 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1681                                         IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1682                                         check_canedit($file, $cgi, $session);
1683                                         next;
1684                                 }
1685                         }
1686                 }
1687                 elsif ($change->{action} eq 'remove') {
1688                         # check_canremove tests to see if the file is present
1689                         # on disk. This will fail when a single commit adds a
1690                         # file and then removes it again. Avoid the problem
1691                         # by not testing the removal in such pairs of changes.
1692                         # (The add is still tested, just to make sure that
1693                         # no data is added to the repo that a web edit
1694                         # could not add.)
1695                         next if $newfiles{$file};
1697                         if (IkiWiki::Plugin::remove->can("check_canremove")) {
1698                                 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1699                                 check_canedit(defined $page ? $page : $file, $cgi, $session);
1700                                 next;
1701                         }
1702                 }
1703                 else {
1704                         error "unknown action ".$change->{action};
1705                 }
1707                 error sprintf(gettext("you are not allowed to change %s"), $file);
1708         }
1712 my $wikilock;
1714 sub lockwiki () {
1715         # Take an exclusive lock on the wiki to prevent multiple concurrent
1716         # run issues. The lock will be dropped on program exit.
1717         if (! -d $config{wikistatedir}) {
1718                 mkdir($config{wikistatedir});
1719         }
1720         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1721                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1722         if (! flock($wikilock, 2)) { # LOCK_EX
1723                 error("failed to get lock");
1724         }
1725         return 1;
1728 sub unlockwiki () {
1729         POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1730         return close($wikilock) if $wikilock;
1731         return;
1734 my $commitlock;
1736 sub commit_hook_enabled () {
1737         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1738                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1739         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1740                 close($commitlock) || error("failed closing commitlock: $!");
1741                 return 0;
1742         }
1743         close($commitlock) || error("failed closing commitlock: $!");
1744         return 1;
1747 sub disable_commit_hook () {
1748         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1749                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1750         if (! flock($commitlock, 2)) { # LOCK_EX
1751                 error("failed to get commit lock");
1752         }
1753         return 1;
1756 sub enable_commit_hook () {
1757         return close($commitlock) if $commitlock;
1758         return;
1761 sub loadindex () {
1762         %oldrenderedfiles=%pagectime=();
1763         if (! $config{rebuild}) {
1764                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1765                 %destsources=%renderedfiles=%pagecase=%pagestate=
1766                 %depends_simple=%typedlinks=%oldtypedlinks=();
1767         }
1768         my $in;
1769         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1770                 if (-e "$config{wikistatedir}/index") {
1771                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1772                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1773                 }
1774                 else {
1775                         $config{gettime}=1; # first build
1776                         return;
1777                 }
1778         }
1780         my $index=Storable::fd_retrieve($in);
1781         if (! defined $index) {
1782                 return 0;
1783         }
1785         my $pages;
1786         if (exists $index->{version} && ! ref $index->{version}) {
1787                 $pages=$index->{page};
1788                 %wikistate=%{$index->{state}};
1789                 # Handle plugins that got disabled by loading a new setup.
1790                 if (exists $config{setupfile}) {
1791                         require IkiWiki::Setup;
1792                         IkiWiki::Setup::disabled_plugins(
1793                                 grep { ! $loaded_plugins{$_} } keys %wikistate);
1794                 }
1795         }
1796         else {
1797                 $pages=$index;
1798                 %wikistate=();
1799         }
1801         foreach my $src (keys %$pages) {
1802                 my $d=$pages->{$src};
1803                 my $page=pagename($src);
1804                 $pagectime{$page}=$d->{ctime};
1805                 $pagesources{$page}=$src;
1806                 if (! $config{rebuild}) {
1807                         $pagemtime{$page}=$d->{mtime};
1808                         $renderedfiles{$page}=$d->{dest};
1809                         if (exists $d->{links} && ref $d->{links}) {
1810                                 $links{$page}=$d->{links};
1811                                 $oldlinks{$page}=[@{$d->{links}}];
1812                         }
1813                         if (ref $d->{depends_simple} eq 'ARRAY') {
1814                                 # old format
1815                                 $depends_simple{$page}={
1816                                         map { $_ => 1 } @{$d->{depends_simple}}
1817                                 };
1818                         }
1819                         elsif (exists $d->{depends_simple}) {
1820                                 $depends_simple{$page}=$d->{depends_simple};
1821                         }
1822                         if (exists $d->{dependslist}) {
1823                                 # old format
1824                                 $depends{$page}={
1825                                         map { $_ => $DEPEND_CONTENT }
1826                                                 @{$d->{dependslist}}
1827                                 };
1828                         }
1829                         elsif (exists $d->{depends} && ! ref $d->{depends}) {
1830                                 # old format
1831                                 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1832                         }
1833                         elsif (exists $d->{depends}) {
1834                                 $depends{$page}=$d->{depends};
1835                         }
1836                         if (exists $d->{state}) {
1837                                 $pagestate{$page}=$d->{state};
1838                         }
1839                         if (exists $d->{typedlinks}) {
1840                                 $typedlinks{$page}=$d->{typedlinks};
1842                                 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1843                                         next unless %$links;
1844                                         $oldtypedlinks{$page}{$type} = {%$links};
1845                                 }
1846                         }
1847                 }
1848                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1849         }
1850         foreach my $page (keys %pagesources) {
1851                 $pagecase{lc $page}=$page;
1852         }
1853         foreach my $page (keys %renderedfiles) {
1854                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1855         }
1856         return close($in);
1859 sub saveindex () {
1860         run_hooks(savestate => sub { shift->() });
1862         my @plugins=keys %loaded_plugins;
1864         if (! -d $config{wikistatedir}) {
1865                 mkdir($config{wikistatedir});
1866         }
1867         my $newfile="$config{wikistatedir}/indexdb.new";
1868         my $cleanup = sub { unlink($newfile) };
1869         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1871         my %index;
1872         foreach my $page (keys %pagemtime) {
1873                 next unless $pagemtime{$page};
1874                 my $src=$pagesources{$page};
1876                 $index{page}{$src}={
1877                         ctime => $pagectime{$page},
1878                         mtime => $pagemtime{$page},
1879                         dest => $renderedfiles{$page},
1880                         links => $links{$page},
1881                 };
1883                 if (exists $depends{$page}) {
1884                         $index{page}{$src}{depends} = $depends{$page};
1885                 }
1887                 if (exists $depends_simple{$page}) {
1888                         $index{page}{$src}{depends_simple} = $depends_simple{$page};
1889                 }
1891                 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1892                         $index{page}{$src}{typedlinks} = $typedlinks{$page};
1893                 }
1895                 if (exists $pagestate{$page}) {
1896                         foreach my $id (@plugins) {
1897                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1898                                         $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1899                                 }
1900                         }
1901                 }
1902         }
1904         $index{state}={};
1905         foreach my $id (@plugins) {
1906                 $index{state}{$id}={}; # used to detect disabled plugins
1907                 foreach my $key (keys %{$wikistate{$id}}) {
1908                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
1909                 }
1910         }
1911         
1912         $index{version}="3";
1913         my $ret=Storable::nstore_fd(\%index, $out);
1914         return if ! defined $ret || ! $ret;
1915         close $out || error("failed saving to $newfile: $!", $cleanup);
1916         rename($newfile, "$config{wikistatedir}/indexdb") ||
1917                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1918         
1919         return 1;
1922 sub template_file ($) {
1923         my $name=shift;
1924         
1925         my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1926         my $template;
1927         if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1928                 $template=srcfile($pagesources{$tpage}, 1);
1929                 $name.=".tmpl";
1930         }
1931         else {
1932                 $template=srcfile($tpage, 1);
1933         }
1935         if (defined $template) {
1936                 return $template, $tpage, 1 if wantarray;
1937                 return $template;
1938         }
1939         else {
1940                 $name=~s:/::; # avoid path traversal
1941                 foreach my $dir ($config{templatedir},
1942                                  "$installdir/share/ikiwiki/templates") {
1943                         if (-e "$dir/$name") {
1944                                 $template="$dir/$name";
1945                                 last;
1946                         }
1947                 }
1948                 if (defined $template) {        
1949                         return $template, $tpage if wantarray;
1950                         return $template;
1951                 }
1952         }
1954         return;
1957 sub template_depends ($$;@) {
1958         my $name=shift;
1959         my $page=shift;
1960         
1961         my ($filename, $tpage, $untrusted)=template_file($name);
1962         if (! defined $filename) {
1963                 error(sprintf(gettext("template %s not found"), $name))
1964         }
1966         if (defined $page && defined $tpage) {
1967                 add_depends($page, $tpage);
1968         }
1969         
1970         my @opts=(
1971                 filter => sub {
1972                         my $text_ref = shift;
1973                         ${$text_ref} = decode_utf8(${$text_ref});
1974                 },
1975                 loop_context_vars => 1,
1976                 die_on_bad_params => 0,
1977                 parent_global_vars => 1,
1978                 filename => $filename,
1979                 @_,
1980                 ($untrusted ? (no_includes => 1) : ()),
1981         );
1982         return @opts if wantarray;
1984         require HTML::Template;
1985         return HTML::Template->new(@opts);
1988 sub template ($;@) {
1989         template_depends(shift, undef, @_);
1992 sub templateactions ($$) {
1993         my $template=shift;
1994         my $page=shift;
1996         my $have_actions=0;
1997         my @actions;
1998         run_hooks(pageactions => sub {
1999                 push @actions, map { { action => $_ } } 
2000                         grep { defined } shift->(page => $page);
2001         });
2002         $template->param(actions => \@actions);
2004         if ($config{cgiurl} && exists $hooks{auth}) {
2005                 $template->param(prefsurl => cgiurl(do => "prefs"));
2006                 $have_actions=1;
2007         }
2009         if ($have_actions || @actions) {
2010                 $template->param(have_actions => 1);
2011         }
2014 sub hook (@) {
2015         my %param=@_;
2016         
2017         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2018                 error 'hook requires type, call, and id parameters';
2019         }
2021         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2022         
2023         $hooks{$param{type}}{$param{id}}=\%param;
2024         return 1;
2027 sub run_hooks ($$) {
2028         # Calls the given sub for each hook of the given type,
2029         # passing it the hook function to call.
2030         my $type=shift;
2031         my $sub=shift;
2033         if (exists $hooks{$type}) {
2034                 my (@first, @middle, @last);
2035                 foreach my $id (keys %{$hooks{$type}}) {
2036                         if ($hooks{$type}{$id}{first}) {
2037                                 push @first, $id;
2038                         }
2039                         elsif ($hooks{$type}{$id}{last}) {
2040                                 push @last, $id;
2041                         }
2042                         else {
2043                                 push @middle, $id;
2044                         }
2045                 }
2046                 foreach my $id (@first, @middle, @last) {
2047                         $sub->($hooks{$type}{$id}{call});
2048                 }
2049         }
2051         return 1;
2054 sub rcs_update () {
2055         $hooks{rcs}{rcs_update}{call}->(@_);
2058 sub rcs_prepedit ($) {
2059         $hooks{rcs}{rcs_prepedit}{call}->(@_);
2062 sub rcs_commit (@) {
2063         $hooks{rcs}{rcs_commit}{call}->(@_);
2066 sub rcs_commit_staged (@) {
2067         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2070 sub rcs_add ($) {
2071         $hooks{rcs}{rcs_add}{call}->(@_);
2074 sub rcs_remove ($) {
2075         $hooks{rcs}{rcs_remove}{call}->(@_);
2078 sub rcs_rename ($$) {
2079         $hooks{rcs}{rcs_rename}{call}->(@_);
2082 sub rcs_recentchanges ($) {
2083         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2086 sub rcs_diff ($;$) {
2087         $hooks{rcs}{rcs_diff}{call}->(@_);
2090 sub rcs_getctime ($) {
2091         $hooks{rcs}{rcs_getctime}{call}->(@_);
2094 sub rcs_getmtime ($) {
2095         $hooks{rcs}{rcs_getmtime}{call}->(@_);
2098 sub rcs_receive () {
2099         $hooks{rcs}{rcs_receive}{call}->();
2102 sub add_depends ($$;$) {
2103         my $page=shift;
2104         my $pagespec=shift;
2105         my $deptype=shift || $DEPEND_CONTENT;
2107         # Is the pagespec a simple page name?
2108         if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2109             $pagespec !~ /[\s*?()!]/) {
2110                 $depends_simple{$page}{lc $pagespec} |= $deptype;
2111                 return 1;
2112         }
2114         # Add explicit dependencies for influences.
2115         my $sub=pagespec_translate($pagespec);
2116         return unless defined $sub;
2117         foreach my $p (keys %pagesources) {
2118                 my $r=$sub->($p, location => $page);
2119                 my $i=$r->influences;
2120                 my $static=$r->influences_static;
2121                 foreach my $k (keys %$i) {
2122                         next unless $r || $static || $k eq $page;
2123                         $depends_simple{$page}{lc $k} |= $i->{$k};
2124                 }
2125                 last if $static;
2126         }
2128         $depends{$page}{$pagespec} |= $deptype;
2129         return 1;
2132 sub deptype (@) {
2133         my $deptype=0;
2134         foreach my $type (@_) {
2135                 if ($type eq 'presence') {
2136                         $deptype |= $DEPEND_PRESENCE;
2137                 }
2138                 elsif ($type eq 'links') { 
2139                         $deptype |= $DEPEND_LINKS;
2140                 }
2141                 elsif ($type eq 'content') {
2142                         $deptype |= $DEPEND_CONTENT;
2143                 }
2144         }
2145         return $deptype;
2148 my $file_prune_regexp;
2149 sub file_pruned ($) {
2150         my $file=shift;
2152         if (defined $config{include} && length $config{include}) {
2153                 return 0 if $file =~ m/$config{include}/;
2154         }
2156         if (! defined $file_prune_regexp) {
2157                 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2158                 $file_prune_regexp=qr/$file_prune_regexp/;
2159         }
2160         return $file =~ m/$file_prune_regexp/;
2163 sub define_gettext () {
2164         # If translation is needed, redefine the gettext function to do it.
2165         # Otherwise, it becomes a quick no-op.
2166         my $gettext_obj;
2167         my $getobj;
2168         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2169             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2170             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2171                 $getobj=sub {
2172                         $gettext_obj=eval q{
2173                                 use Locale::gettext q{textdomain};
2174                                 Locale::gettext->domain('ikiwiki')
2175                         };
2176                 };
2177         }
2179         no warnings 'redefine';
2180         *gettext=sub {
2181                 $getobj->() if $getobj;
2182                 if ($gettext_obj) {
2183                         $gettext_obj->get(shift);
2184                 }
2185                 else {
2186                         return shift;
2187                 }
2188         };
2189         *ngettext=sub {
2190                 $getobj->() if $getobj;
2191                 if ($gettext_obj) {
2192                         $gettext_obj->nget(@_);
2193                 }
2194                 else {
2195                         return ($_[2] == 1 ? $_[0] : $_[1])
2196                 }
2197         };
2200 sub gettext {
2201         define_gettext();
2202         gettext(@_);
2205 sub ngettext {
2206         define_gettext();
2207         ngettext(@_);
2210 sub yesno ($) {
2211         my $val=shift;
2213         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2216 sub inject {
2217         # Injects a new function into the symbol table to replace an
2218         # exported function.
2219         my %params=@_;
2221         # This is deep ugly perl foo, beware.
2222         no strict;
2223         no warnings;
2224         if (! defined $params{parent}) {
2225                 $params{parent}='::';
2226                 $params{old}=\&{$params{name}};
2227                 $params{name}=~s/.*:://;
2228         }
2229         my $parent=$params{parent};
2230         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2231                 $ns = $params{parent} . $ns;
2232                 inject(%params, parent => $ns) unless $ns eq '::main::';
2233                 *{$ns . $params{name}} = $params{call}
2234                         if exists ${$ns}{$params{name}} &&
2235                            \&{${$ns}{$params{name}}} == $params{old};
2236         }
2237         use strict;
2238         use warnings;
2241 sub add_link ($$;$) {
2242         my $page=shift;
2243         my $link=shift;
2244         my $type=shift;
2246         push @{$links{$page}}, $link
2247                 unless grep { $_ eq $link } @{$links{$page}};
2249         if (defined $type) {
2250                 $typedlinks{$page}{$type}{$link} = 1;
2251         }
2254 sub add_autofile ($$$) {
2255         my $file=shift;
2256         my $plugin=shift;
2257         my $generator=shift;
2258         
2259         $autofiles{$file}{plugin}=$plugin;
2260         $autofiles{$file}{generator}=$generator;
2263 sub sortspec_translate ($$) {
2264         my $spec = shift;
2265         my $reverse = shift;
2267         my $code = "";
2268         my @data;
2269         while ($spec =~ m{
2270                 \s*
2271                 (-?)            # group 1: perhaps negated
2272                 \s*
2273                 (               # group 2: a word
2274                         \w+\([^\)]*\)   # command(params)
2275                         |
2276                         [^\s]+          # or anything else
2277                 )
2278                 \s*
2279         }gx) {
2280                 my $negated = $1;
2281                 my $word = $2;
2282                 my $params = undef;
2284                 if ($word =~ m/^(\w+)\((.*)\)$/) {
2285                         # command with parameters
2286                         $params = $2;
2287                         $word = $1;
2288                 }
2289                 elsif ($word !~ m/^\w+$/) {
2290                         error(sprintf(gettext("invalid sort type %s"), $word));
2291                 }
2293                 if (length $code) {
2294                         $code .= " || ";
2295                 }
2297                 if ($negated) {
2298                         $code .= "-";
2299                 }
2301                 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2302                         if (defined $params) {
2303                                 push @data, $params;
2304                                 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2305                         }
2306                         else {
2307                                 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2308                         }
2309                 }
2310                 else {
2311                         error(sprintf(gettext("unknown sort type %s"), $word));
2312                 }
2313         }
2315         if (! length $code) {
2316                 # undefined sorting method... sort arbitrarily
2317                 return sub { 0 };
2318         }
2320         if ($reverse) {
2321                 $code="-($code)";
2322         }
2324         no warnings;
2325         return eval 'sub { '.$code.' }';
2328 sub pagespec_translate ($) {
2329         my $spec=shift;
2331         # Convert spec to perl code.
2332         my $code="";
2333         my @data;
2334         while ($spec=~m{
2335                 \s*             # ignore whitespace
2336                 (               # 1: match a single word
2337                         \!              # !
2338                 |
2339                         \(              # (
2340                 |
2341                         \)              # )
2342                 |
2343                         \w+\([^\)]*\)   # command(params)
2344                 |
2345                         [^\s()]+        # any other text
2346                 )
2347                 \s*             # ignore whitespace
2348         }gx) {
2349                 my $word=$1;
2350                 if (lc $word eq 'and') {
2351                         $code.=' &';
2352                 }
2353                 elsif (lc $word eq 'or') {
2354                         $code.=' |';
2355                 }
2356                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2357                         $code.=' '.$word;
2358                 }
2359                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2360                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2361                                 push @data, $2;
2362                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2363                         }
2364                         else {
2365                                 push @data, qq{unknown function in pagespec "$word"};
2366                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2367                         }
2368                 }
2369                 else {
2370                         push @data, $word;
2371                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2372                 }
2373         }
2375         if (! length $code) {
2376                 $code="IkiWiki::FailReason->new('empty pagespec')";
2377         }
2379         no warnings;
2380         return eval 'sub { my $page=shift; '.$code.' }';
2383 sub pagespec_match ($$;@) {
2384         my $page=shift;
2385         my $spec=shift;
2386         my @params=@_;
2388         # Backwards compatability with old calling convention.
2389         if (@params == 1) {
2390                 unshift @params, 'location';
2391         }
2393         my $sub=pagespec_translate($spec);
2394         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2395                 if ! defined $sub;
2396         return $sub->($page, @params);
2399 sub pagespec_match_list ($$;@) {
2400         my $page=shift;
2401         my $pagespec=shift;
2402         my %params=@_;
2404         # Backwards compatability with old calling convention.
2405         if (ref $page) {
2406                 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2407                 $params{list}=$page;
2408                 $page=$params{location}; # ugh!
2409         }
2411         my $sub=pagespec_translate($pagespec);
2412         error "syntax error in pagespec \"$pagespec\""
2413                 if ! defined $sub;
2414         my $sort=sortspec_translate($params{sort}, $params{reverse})
2415                 if defined $params{sort};
2417         my @candidates;
2418         if (exists $params{list}) {
2419                 @candidates=exists $params{filter}
2420                         ? grep { ! $params{filter}->($_) } @{$params{list}}
2421                         : @{$params{list}};
2422         }
2423         else {
2424                 @candidates=exists $params{filter}
2425                         ? grep { ! $params{filter}->($_) } keys %pagesources
2426                         : keys %pagesources;
2427         }
2428         
2429         # clear params, remainder is passed to pagespec
2430         $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2431         my $num=$params{num};
2432         delete @params{qw{num deptype reverse sort filter list}};
2433         
2434         # when only the top matches will be returned, it's efficient to
2435         # sort before matching to pagespec,
2436         if (defined $num && defined $sort) {
2437                 @candidates=IkiWiki::SortSpec::sort_pages(
2438                         $sort, @candidates);
2439         }
2440         
2441         my @matches;
2442         my $firstfail;
2443         my $count=0;
2444         my $accum=IkiWiki::SuccessReason->new();
2445         foreach my $p (@candidates) {
2446                 my $r=$sub->($p, %params, location => $page);
2447                 error(sprintf(gettext("cannot match pages: %s"), $r))
2448                         if $r->isa("IkiWiki::ErrorReason");
2449                 unless ($r || $r->influences_static) {
2450                         $r->remove_influence($p);
2451                 }
2452                 $accum |= $r;
2453                 if ($r) {
2454                         push @matches, $p;
2455                         last if defined $num && ++$count == $num;
2456                 }
2457         }
2459         # Add simple dependencies for accumulated influences.
2460         my $i=$accum->influences;
2461         foreach my $k (keys %$i) {
2462                 $depends_simple{$page}{lc $k} |= $i->{$k};
2463         }
2465         # when all matches will be returned, it's efficient to
2466         # sort after matching
2467         if (! defined $num && defined $sort) {
2468                 return IkiWiki::SortSpec::sort_pages(
2469                         $sort, @matches);
2470         }
2471         else {
2472                 return @matches;
2473         }
2476 sub pagespec_valid ($) {
2477         my $spec=shift;
2479         return defined pagespec_translate($spec);
2482 sub glob2re ($) {
2483         my $re=quotemeta(shift);
2484         $re=~s/\\\*/.*/g;
2485         $re=~s/\\\?/./g;
2486         return qr/^$re$/i;
2489 package IkiWiki::FailReason;
2491 use overload (
2492         '""'    => sub { $_[0][0] },
2493         '0+'    => sub { 0 },
2494         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2495         '&'     => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2496         '|'     => sub { $_[1]->merge_influences($_[0]); $_[1] },
2497         fallback => 1,
2498 );
2500 our @ISA = 'IkiWiki::SuccessReason';
2502 package IkiWiki::SuccessReason;
2504 use overload (
2505         '""'    => sub { $_[0][0] },
2506         '0+'    => sub { 1 },
2507         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
2508         '&'     => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2509         '|'     => sub { $_[0]->merge_influences($_[1]); $_[0] },
2510         fallback => 1,
2511 );
2513 sub new {
2514         my $class = shift;
2515         my $value = shift;
2516         return bless [$value, {@_}], $class;
2519 sub influences {
2520         my $this=shift;
2521         $this->[1]={@_} if @_;
2522         my %i=%{$this->[1]};
2523         delete $i{""};
2524         return \%i;
2527 sub influences_static {
2528         return ! $_[0][1]->{""};
2531 sub merge_influences {
2532         my $this=shift;
2533         my $other=shift;
2534         my $anded=shift;
2536         if (! $anded || (($this || %{$this->[1]}) &&
2537                          ($other || %{$other->[1]}))) {
2538                 foreach my $influence (keys %{$other->[1]}) {
2539                         $this->[1]{$influence} |= $other->[1]{$influence};
2540                 }
2541         }
2542         else {
2543                 # influence blocker
2544                 $this->[1]={};
2545         }
2548 sub remove_influence {
2549         my $this=shift;
2550         my $torm=shift;
2552         delete $this->[1]{$torm};
2555 package IkiWiki::ErrorReason;
2557 our @ISA = 'IkiWiki::FailReason';
2559 package IkiWiki::PageSpec;
2561 sub derel ($$) {
2562         my $path=shift;
2563         my $from=shift;
2565         if ($path =~ m!^\.(/|$)!) {
2566                 if ($1) {
2567                         $from=~s#/?[^/]+$## if defined $from;
2568                         $path=~s#^\./##;
2569                         $path="$from/$path" if defined $from && length $from;
2570                 }
2571                 else {
2572                         $path = $from;
2573                         $path = "" unless defined $path;
2574                 }
2575         }
2577         return $path;
2580 my %glob_cache;
2582 sub match_glob ($$;@) {
2583         my $page=shift;
2584         my $glob=shift;
2585         my %params=@_;
2586         
2587         $glob=derel($glob, $params{location});
2589         # Instead of converting the glob to a regex every time,
2590         # cache the compiled regex to save time.
2591         my $re=$glob_cache{$glob};
2592         unless (defined $re) {
2593                 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2594         }
2595         if ($page =~ $re) {
2596                 if (! IkiWiki::isinternal($page) || $params{internal}) {
2597                         return IkiWiki::SuccessReason->new("$glob matches $page");
2598                 }
2599                 else {
2600                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2601                 }
2602         }
2603         else {
2604                 return IkiWiki::FailReason->new("$glob does not match $page");
2605         }
2608 sub match_internal ($$;@) {
2609         return match_glob(shift, shift, @_, internal => 1)
2612 sub match_page ($$;@) {
2613         my $page=shift;
2614         my $match=match_glob($page, shift, @_);
2615         if ($match) {
2616                 my $source=exists $IkiWiki::pagesources{$page} ?
2617                         $IkiWiki::pagesources{$page} :
2618                         $IkiWiki::delpagesources{$page};
2619                 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2620                 if (! defined $type) {  
2621                         return IkiWiki::FailReason->new("$page is not a page");
2622                 }
2623         }
2624         return $match;
2627 sub match_link ($$;@) {
2628         my $page=shift;
2629         my $link=lc(shift);
2630         my %params=@_;
2632         $link=derel($link, $params{location});
2633         my $from=exists $params{location} ? $params{location} : '';
2634         my $linktype=$params{linktype};
2635         my $qualifier='';
2636         if (defined $linktype) {
2637                 $qualifier=" with type $linktype";
2638         }
2640         my $links = $IkiWiki::links{$page};
2641         return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2642                 unless $links && @{$links};
2643         my $bestlink = IkiWiki::bestlink($from, $link);
2644         foreach my $p (@{$links}) {
2645                 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2647                 if (length $bestlink) {
2648                         if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2649                                 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2650                         }
2651                 }
2652                 else {
2653                         if (match_glob($p, $link, %params)) {
2654                                 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2655                         }
2656                         my ($p_rel)=$p=~/^\/?(.*)/;
2657                         $link=~s/^\///;
2658                         if (match_glob($p_rel, $link, %params)) {
2659                                 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2660                         }
2661                 }
2662         }
2663         return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2666 sub match_backlink ($$;@) {
2667         my $page=shift;
2668         my $testpage=shift;
2669         my %params=@_;
2670         if ($testpage eq '.') {
2671                 $testpage = $params{'location'}
2672         }
2673         my $ret=match_link($testpage, $page, @_);
2674         $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2675         return $ret;
2678 sub match_created_before ($$;@) {
2679         my $page=shift;
2680         my $testpage=shift;
2681         my %params=@_;
2682         
2683         $testpage=derel($testpage, $params{location});
2685         if (exists $IkiWiki::pagectime{$testpage}) {
2686                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2687                         return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2688                 }
2689                 else {
2690                         return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2691                 }
2692         }
2693         else {
2694                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2695         }
2698 sub match_created_after ($$;@) {
2699         my $page=shift;
2700         my $testpage=shift;
2701         my %params=@_;
2702         
2703         $testpage=derel($testpage, $params{location});
2705         if (exists $IkiWiki::pagectime{$testpage}) {
2706                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2707                         return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2708                 }
2709                 else {
2710                         return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2711                 }
2712         }
2713         else {
2714                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2715         }
2718 sub match_creation_day ($$;@) {
2719         my $page=shift;
2720         my $d=shift;
2721         if ($d !~ /^\d+$/) {
2722                 return IkiWiki::ErrorReason->new("invalid day $d");
2723         }
2724         if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2725                 return IkiWiki::SuccessReason->new('creation_day matched');
2726         }
2727         else {
2728                 return IkiWiki::FailReason->new('creation_day did not match');
2729         }
2732 sub match_creation_month ($$;@) {
2733         my $page=shift;
2734         my $m=shift;
2735         if ($m !~ /^\d+$/) {
2736                 return IkiWiki::ErrorReason->new("invalid month $m");
2737         }
2738         if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2739                 return IkiWiki::SuccessReason->new('creation_month matched');
2740         }
2741         else {
2742                 return IkiWiki::FailReason->new('creation_month did not match');
2743         }
2746 sub match_creation_year ($$;@) {
2747         my $page=shift;
2748         my $y=shift;
2749         if ($y !~ /^\d+$/) {
2750                 return IkiWiki::ErrorReason->new("invalid year $y");
2751         }
2752         if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2753                 return IkiWiki::SuccessReason->new('creation_year matched');
2754         }
2755         else {
2756                 return IkiWiki::FailReason->new('creation_year did not match');
2757         }
2760 sub match_user ($$;@) {
2761         shift;
2762         my $user=shift;
2763         my %params=@_;
2764         
2765         my $regexp=IkiWiki::glob2re($user);
2766         
2767         if (! exists $params{user}) {
2768                 return IkiWiki::ErrorReason->new("no user specified");
2769         }
2771         if (defined $params{user} && $params{user}=~$regexp) {
2772                 return IkiWiki::SuccessReason->new("user is $user");
2773         }
2774         elsif (! defined $params{user}) {
2775                 return IkiWiki::FailReason->new("not logged in");
2776         }
2777         else {
2778                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2779         }
2782 sub match_admin ($$;@) {
2783         shift;
2784         shift;
2785         my %params=@_;
2786         
2787         if (! exists $params{user}) {
2788                 return IkiWiki::ErrorReason->new("no user specified");
2789         }
2791         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2792                 return IkiWiki::SuccessReason->new("user is an admin");
2793         }
2794         elsif (! defined $params{user}) {
2795                 return IkiWiki::FailReason->new("not logged in");
2796         }
2797         else {
2798                 return IkiWiki::FailReason->new("user is not an admin");
2799         }
2802 sub match_ip ($$;@) {
2803         shift;
2804         my $ip=shift;
2805         my %params=@_;
2806         
2807         if (! exists $params{ip}) {
2808                 return IkiWiki::ErrorReason->new("no IP specified");
2809         }
2811         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2812                 return IkiWiki::SuccessReason->new("IP is $ip");
2813         }
2814         else {
2815                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2816         }
2819 package IkiWiki::SortSpec;
2821 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2822 # are easily available in this namespace, for cmp functions to use them.
2823 sub sort_pages {
2824         my $f=shift;
2825         sort $f @_
2828 sub cmp_title {
2829         IkiWiki::pagetitle(IkiWiki::basename($a))
2830         cmp
2831         IkiWiki::pagetitle(IkiWiki::basename($b))
2834 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
2835 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2836 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }