]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki.pm
Release 3.20141016.4
[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 @underlayfiles $lastrev $phase};
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 useragent
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 # Phases of processing.
38 sub PHASE_SCAN () { 0 }
39 sub PHASE_RENDER () { 1 }
40 $phase = PHASE_SCAN;
42 # Optimisation.
43 use Memoize;
44 memoize("abs2rel");
45 memoize("sortspec_translate");
46 memoize("pagespec_translate");
47 memoize("template_file");
49 sub getsetup () {
50         wikiname => {
51                 type => "string",
52                 default => "wiki",
53                 description => "name of the wiki",
54                 safe => 1,
55                 rebuild => 1,
56         },
57         adminemail => {
58                 type => "string",
59                 default => undef,
60                 example => 'me@example.com',
61                 description => "contact email for wiki",
62                 safe => 1,
63                 rebuild => 0,
64         },
65         adminuser => {
66                 type => "string",
67                 default => [],
68                 description => "users who are wiki admins",
69                 safe => 1,
70                 rebuild => 0,
71         },
72         banned_users => {
73                 type => "string",
74                 default => [],
75                 description => "users who are banned from the wiki",
76                 safe => 1,
77                 rebuild => 0,
78         },
79         srcdir => {
80                 type => "string",
81                 default => undef,
82                 example => "$ENV{HOME}/wiki",
83                 description => "where the source of the wiki is located",
84                 safe => 0, # path
85                 rebuild => 1,
86         },
87         destdir => {
88                 type => "string",
89                 default => undef,
90                 example => "/var/www/wiki",
91                 description => "where to build the wiki",
92                 safe => 0, # path
93                 rebuild => 1,
94         },
95         url => {
96                 type => "string",
97                 default => '',
98                 example => "http://example.com/wiki",
99                 description => "base url to the wiki",
100                 safe => 1,
101                 rebuild => 1,
102         },
103         cgiurl => {
104                 type => "string",
105                 default => '',
106                 example => "http://example.com/wiki/ikiwiki.cgi",
107                 description => "url to the ikiwiki.cgi",
108                 safe => 1,
109                 rebuild => 1,
110         },
111         reverse_proxy => {
112                 type => "boolean",
113                 default => 0,
114                 description => "do not adjust cgiurl if CGI is accessed via different URL",
115                 advanced => 0,
116                 safe => 1,
117                 rebuild => 0, # only affects CGI requests
118         },
119         cgi_wrapper => {
120                 type => "string",
121                 default => '',
122                 example => "/var/www/wiki/ikiwiki.cgi",
123                 description => "filename of cgi wrapper to generate",
124                 safe => 0, # file
125                 rebuild => 0,
126         },
127         cgi_wrappermode => {
128                 type => "string",
129                 default => '06755',
130                 description => "mode for cgi_wrapper (can safely be made suid)",
131                 safe => 0,
132                 rebuild => 0,
133         },
134         cgi_overload_delay => {
135                 type => "string",
136                 default => '',
137                 example => "10",
138                 description => "number of seconds to delay CGI requests when overloaded",
139                 safe => 1,
140                 rebuild => 0,
141         },
142         cgi_overload_message => {
143                 type => "string",
144                 default => '',
145                 example => "Please wait",
146                 description => "message to display when overloaded (may contain html)",
147                 safe => 1,
148                 rebuild => 0,
149         },
150         only_committed_changes => {
151                 type => "boolean",
152                 default => 0,
153                 description => "enable optimization of only refreshing committed changes?",
154                 safe => 1,
155                 rebuild => 0,
156         },
157         rcs => {
158                 type => "string",
159                 default => '',
160                 description => "rcs backend to use",
161                 safe => 0, # don't allow overriding
162                 rebuild => 0,
163         },
164         default_plugins => {
165                 type => "internal",
166                 default => [qw{mdwn link inline meta htmlscrubber passwordauth
167                                 openid signinedit lockedit conditional
168                                 recentchanges parentlinks editpage
169                                 templatebody}],
170                 description => "plugins to enable by default",
171                 safe => 0,
172                 rebuild => 1,
173         },
174         add_plugins => {
175                 type => "string",
176                 default => [],
177                 description => "plugins to add to the default configuration",
178                 safe => 1,
179                 rebuild => 1,
180         },
181         disable_plugins => {
182                 type => "string",
183                 default => [],
184                 description => "plugins to disable",
185                 safe => 1,
186                 rebuild => 1,
187         },
188         templatedir => {
189                 type => "string",
190                 default => "$installdir/share/ikiwiki/templates",
191                 description => "additional directory to search for template files",
192                 advanced => 1,
193                 safe => 0, # path
194                 rebuild => 1,
195         },
196         underlaydir => {
197                 type => "string",
198                 default => "$installdir/share/ikiwiki/basewiki",
199                 description => "base wiki source location",
200                 advanced => 1,
201                 safe => 0, # path
202                 rebuild => 0,
203         },
204         underlaydirbase => {
205                 type => "internal",
206                 default => "$installdir/share/ikiwiki",
207                 description => "parent directory containing additional underlays",
208                 safe => 0,
209                 rebuild => 0,
210         },
211         wrappers => {
212                 type => "internal",
213                 default => [],
214                 description => "wrappers to generate",
215                 safe => 0,
216                 rebuild => 0,
217         },
218         underlaydirs => {
219                 type => "internal",
220                 default => [],
221                 description => "additional underlays to use",
222                 safe => 0,
223                 rebuild => 0,
224         },
225         verbose => {
226                 type => "boolean",
227                 example => 1,
228                 description => "display verbose messages?",
229                 safe => 1,
230                 rebuild => 0,
231         },
232         syslog => {
233                 type => "boolean",
234                 example => 1,
235                 description => "log to syslog?",
236                 safe => 1,
237                 rebuild => 0,
238         },
239         usedirs => {
240                 type => "boolean",
241                 default => 1,
242                 description => "create output files named page/index.html?",
243                 safe => 0, # changing requires manual transition
244                 rebuild => 1,
245         },
246         prefix_directives => {
247                 type => "boolean",
248                 default => 1,
249                 description => "use '!'-prefixed preprocessor directives?",
250                 safe => 0, # changing requires manual transition
251                 rebuild => 1,
252         },
253         indexpages => {
254                 type => "boolean",
255                 default => 0,
256                 description => "use page/index.mdwn source files",
257                 safe => 1,
258                 rebuild => 1,
259         },
260         discussion => {
261                 type => "boolean",
262                 default => 1,
263                 description => "enable Discussion pages?",
264                 safe => 1,
265                 rebuild => 1,
266         },
267         discussionpage => {
268                 type => "string",
269                 default => gettext("Discussion"),
270                 description => "name of Discussion pages",
271                 safe => 1,
272                 rebuild => 1,
273         },
274         html5 => {
275                 type => "boolean",
276                 default => 0,
277                 description => "generate HTML5?",
278                 advanced => 0,
279                 safe => 1,
280                 rebuild => 1,
281         },
282         sslcookie => {
283                 type => "boolean",
284                 default => 0,
285                 description => "only send cookies over SSL connections?",
286                 advanced => 1,
287                 safe => 1,
288                 rebuild => 0,
289         },
290         default_pageext => {
291                 type => "string",
292                 default => "mdwn",
293                 description => "extension to use for new pages",
294                 safe => 0, # not sanitized
295                 rebuild => 0,
296         },
297         htmlext => {
298                 type => "string",
299                 default => "html",
300                 description => "extension to use for html files",
301                 safe => 0, # not sanitized
302                 rebuild => 1,
303         },
304         timeformat => {
305                 type => "string",
306                 default => '%c',
307                 description => "strftime format string to display date",
308                 advanced => 1,
309                 safe => 1,
310                 rebuild => 1,
311         },
312         locale => {
313                 type => "string",
314                 default => undef,
315                 example => "en_US.UTF-8",
316                 description => "UTF-8 locale to use",
317                 advanced => 1,
318                 safe => 0,
319                 rebuild => 1,
320         },
321         userdir => {
322                 type => "string",
323                 default => "",
324                 example => "users",
325                 description => "put user pages below specified page",
326                 safe => 1,
327                 rebuild => 1,
328         },
329         numbacklinks => {
330                 type => "integer",
331                 default => 10,
332                 description => "how many backlinks to show before hiding excess (0 to show all)",
333                 safe => 1,
334                 rebuild => 1,
335         },
336         hardlink => {
337                 type => "boolean",
338                 default => 0,
339                 description => "attempt to hardlink source files? (optimisation for large files)",
340                 advanced => 1,
341                 safe => 0, # paranoia
342                 rebuild => 0,
343         },
344         umask => {
345                 type => "string",
346                 example => "public",
347                 description => "force ikiwiki to use a particular umask (keywords public, group or private, or a number)",
348                 advanced => 1,
349                 safe => 0, # paranoia
350                 rebuild => 0,
351         },
352         wrappergroup => {
353                 type => "string",
354                 example => "ikiwiki",
355                 description => "group for wrappers to run in",
356                 advanced => 1,
357                 safe => 0, # paranoia
358                 rebuild => 0,
359         },
360         libdir => {
361                 type => "string",
362                 default => "",
363                 example => "$ENV{HOME}/.ikiwiki/",
364                 description => "extra library and plugin directory",
365                 advanced => 1,
366                 safe => 0, # directory
367                 rebuild => 0,
368         },
369         ENV => {
370                 type => "string", 
371                 default => {},
372                 description => "environment variables",
373                 safe => 0, # paranoia
374                 rebuild => 0,
375         },
376         timezone => {
377                 type => "string", 
378                 default => "",
379                 example => "US/Eastern",
380                 description => "time zone name",
381                 safe => 1,
382                 rebuild => 1,
383         },
384         include => {
385                 type => "string",
386                 default => undef,
387                 example => '^\.htaccess$',
388                 description => "regexp of normally excluded files to include",
389                 advanced => 1,
390                 safe => 0, # regexp
391                 rebuild => 1,
392         },
393         exclude => {
394                 type => "string",
395                 default => undef,
396                 example => '^(*\.private|Makefile)$',
397                 description => "regexp of files that should be skipped",
398                 advanced => 1,
399                 safe => 0, # regexp
400                 rebuild => 1,
401         },
402         wiki_file_prune_regexps => {
403                 type => "internal",
404                 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
405                         qr/\.x?html?$/, qr/\.ikiwiki-new$/,
406                         qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
407                         qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
408                         qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
409                 description => "regexps of source files to ignore",
410                 safe => 0,
411                 rebuild => 1,
412         },
413         wiki_file_chars => {
414                 type => "string",
415                 description => "specifies the characters that are allowed in source filenames",
416                 default => "-[:alnum:]+/.:_",
417                 safe => 0,
418                 rebuild => 1,
419         },
420         wiki_file_regexp => {
421                 type => "internal",
422                 description => "regexp of legal source files",
423                 safe => 0,
424                 rebuild => 1,
425         },
426         web_commit_regexp => {
427                 type => "internal",
428                 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
429                 description => "regexp to parse web commits from logs",
430                 safe => 0,
431                 rebuild => 0,
432         },
433         cgi => {
434                 type => "internal",
435                 default => 0,
436                 description => "run as a cgi",
437                 safe => 0,
438                 rebuild => 0,
439         },
440         cgi_disable_uploads => {
441                 type => "internal",
442                 default => 1,
443                 description => "whether CGI should accept file uploads",
444                 safe => 0,
445                 rebuild => 0,
446         },
447         post_commit => {
448                 type => "internal",
449                 default => 0,
450                 description => "run as a post-commit hook",
451                 safe => 0,
452                 rebuild => 0,
453         },
454         rebuild => {
455                 type => "internal",
456                 default => 0,
457                 description => "running in rebuild mode",
458                 safe => 0,
459                 rebuild => 0,
460         },
461         setup => {
462                 type => "internal",
463                 default => undef,
464                 description => "running in setup mode",
465                 safe => 0,
466                 rebuild => 0,
467         },
468         clean => {
469                 type => "internal",
470                 default => 0,
471                 description => "running in clean mode",
472                 safe => 0,
473                 rebuild => 0,
474         },
475         refresh => {
476                 type => "internal",
477                 default => 0,
478                 description => "running in refresh mode",
479                 safe => 0,
480                 rebuild => 0,
481         },
482         test_receive => {
483                 type => "internal",
484                 default => 0,
485                 description => "running in receive test mode",
486                 safe => 0,
487                 rebuild => 0,
488         },
489         wrapper_background_command => {
490                 type => "internal",
491                 default => '',
492                 description => "background shell command to run",
493                 safe => 0,
494                 rebuild => 0,
495         },
496         gettime => {
497                 type => "internal",
498                 description => "running in gettime mode",
499                 safe => 0,
500                 rebuild => 0,
501         },
502         w3mmode => {
503                 type => "internal",
504                 default => 0,
505                 description => "running in w3mmode",
506                 safe => 0,
507                 rebuild => 0,
508         },
509         wikistatedir => {
510                 type => "internal",
511                 default => undef,
512                 description => "path to the .ikiwiki directory holding ikiwiki state",
513                 safe => 0,
514                 rebuild => 0,
515         },
516         setupfile => {
517                 type => "internal",
518                 default => undef,
519                 description => "path to setup file",
520                 safe => 0,
521                 rebuild => 0,
522         },
523         setuptype => {
524                 type => "internal",
525                 default => "Yaml",
526                 description => "perl class to use to dump setup file",
527                 safe => 0,
528                 rebuild => 0,
529         },
530         allow_symlinks_before_srcdir => {
531                 type => "boolean",
532                 default => 0,
533                 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
534                 safe => 0,
535                 rebuild => 0,
536         },
537         cookiejar => {
538                 type => "string",
539                 default => { file => "$ENV{HOME}/.ikiwiki/cookies" },
540                 description => "cookie control",
541                 safe => 0, # hooks into perl module internals
542                 rebuild => 0,
543         },
544         useragent => {
545                 type => "string",
546                 default => "ikiwiki/$version",
547                 example => "Wget/1.13.4 (linux-gnu)",
548                 description => "set custom user agent string for outbound HTTP requests e.g. when fetching aggregated RSS feeds",
549                 safe => 0,
550                 rebuild => 0,
551         },
554 sub defaultconfig () {
555         my %s=getsetup();
556         my @ret;
557         foreach my $key (keys %s) {
558                 push @ret, $key, $s{$key}->{default};
559         }
560         return @ret;
563 # URL to top of wiki as a path starting with /, valid from any wiki page or
564 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
565 my $local_url;
566 # URL to CGI script, similar to $local_url
567 my $local_cgiurl;
569 sub checkconfig () {
570         # locale stuff; avoid LC_ALL since it overrides everything
571         if (defined $ENV{LC_ALL}) {
572                 $ENV{LANG} = $ENV{LC_ALL};
573                 delete $ENV{LC_ALL};
574         }
575         if (defined $config{locale}) {
576                 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
577                         $ENV{LANG}=$config{locale};
578                         define_gettext();
579                 }
580         }
581                 
582         if (! defined $config{wiki_file_regexp}) {
583                 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
584         }
586         if (ref $config{ENV} eq 'HASH') {
587                 foreach my $val (keys %{$config{ENV}}) {
588                         $ENV{$val}=$config{ENV}{$val};
589                 }
590         }
591         if (defined $config{timezone} && length $config{timezone}) {
592                 $ENV{TZ}=$config{timezone};
593         }
594         else {
595                 $config{timezone}=$ENV{TZ};
596         }
598         if ($config{w3mmode}) {
599                 eval q{use Cwd q{abs_path}};
600                 error($@) if $@;
601                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
602                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
603                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
604                         unless $config{cgiurl} =~ m!file:///!;
605                 $config{url}="file://".$config{destdir};
606         }
608         if ($config{cgi} && ! length $config{url}) {
609                 error(gettext("Must specify url to wiki with --url when using --cgi"));
610         }
612         if (defined $config{url} && length $config{url}) {
613                 eval q{use URI};
614                 my $baseurl = URI->new($config{url});
616                 $local_url = $baseurl->path . "/";
617                 $local_cgiurl = undef;
619                 if (length $config{cgiurl}) {
620                         my $cgiurl = URI->new($config{cgiurl});
622                         $local_cgiurl = $cgiurl->path;
624                         if ($cgiurl->scheme eq 'https' &&
625                                 $baseurl->scheme eq 'http') {
626                                 # We assume that the same content is available
627                                 # over both http and https, because if it
628                                 # wasn't, accessing the static content
629                                 # from the CGI would be mixed-content,
630                                 # which would be a security flaw.
632                                 if ($cgiurl->authority ne $baseurl->authority) {
633                                         # use protocol-relative URL for
634                                         # static content
635                                         $local_url = "$config{url}/";
636                                         $local_url =~ s{^http://}{//};
637                                 }
638                                 # else use host-relative URL for static content
640                                 # either way, CGI needs to be absolute
641                                 $local_cgiurl = $config{cgiurl};
642                         }
643                         elsif ($cgiurl->scheme ne $baseurl->scheme) {
644                                 # too far apart, fall back to absolute URLs
645                                 $local_url = "$config{url}/";
646                                 $local_cgiurl = $config{cgiurl};
647                         }
648                         elsif ($cgiurl->authority ne $baseurl->authority) {
649                                 # slightly too far apart, fall back to
650                                 # protocol-relative URLs
651                                 $local_url = "$config{url}/";
652                                 $local_url =~ s{^https?://}{//};
653                                 $local_cgiurl = $config{cgiurl};
654                                 $local_cgiurl =~ s{^https?://}{//};
655                         }
656                         # else keep host-relative URLs
657                 }
659                 $local_url =~ s{//$}{/};
660         }
661         else {
662                 $local_cgiurl = $config{cgiurl};
663         }
665         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
666                 unless exists $config{wikistatedir} && defined $config{wikistatedir};
668         if (defined $config{umask}) {
669                 my $u = possibly_foolish_untaint($config{umask});
671                 if ($u =~ m/^\d+$/) {
672                         umask($u);
673                 }
674                 elsif ($u eq 'private') {
675                         umask(077);
676                 }
677                 elsif ($u eq 'group') {
678                         umask(027);
679                 }
680                 elsif ($u eq 'public') {
681                         umask(022);
682                 }
683                 else {
684                         error(sprintf(gettext("unsupported umask setting %s"), $u));
685                 }
686         }
688         run_hooks(checkconfig => sub { shift->() });
690         return 1;
693 sub listplugins () {
694         my %ret;
696         foreach my $dir (@INC, $config{libdir}) {
697                 next unless defined $dir && length $dir;
698                 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
699                         my ($plugin)=$file=~/.*\/(.*)\.pm$/;
700                         $ret{$plugin}=1;
701                 }
702         }
703         foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
704                 next unless defined $dir && length $dir;
705                 foreach my $file (glob("$dir/plugins/*")) {
706                         $ret{basename($file)}=1 if -x $file;
707                 }
708         }
710         return keys %ret;
713 sub loadplugins () {
714         if (defined $config{libdir} && length $config{libdir}) {
715                 unshift @INC, possibly_foolish_untaint($config{libdir});
716         }
718         foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
719                 loadplugin($plugin);
720         }
721         
722         if ($config{rcs}) {
723                 if (exists $hooks{rcs}) {
724                         error(gettext("cannot use multiple rcs plugins"));
725                 }
726                 loadplugin($config{rcs});
727         }
728         if (! exists $hooks{rcs}) {
729                 loadplugin("norcs");
730         }
732         run_hooks(getopt => sub { shift->() });
733         if (grep /^-/, @ARGV) {
734                 print STDERR "Unknown option (or missing parameter): $_\n"
735                         foreach grep /^-/, @ARGV;
736                 usage();
737         }
739         return 1;
742 sub loadplugin ($;$) {
743         my $plugin=shift;
744         my $force=shift;
746         return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
748         foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
749                          "$installdir/lib/ikiwiki") {
750                 if (defined $dir && -x "$dir/plugins/$plugin") {
751                         eval { require IkiWiki::Plugin::external };
752                         if ($@) {
753                                 my $reason=$@;
754                                 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
755                         }
756                         import IkiWiki::Plugin::external "$dir/plugins/$plugin";
757                         $loaded_plugins{$plugin}=1;
758                         return 1;
759                 }
760         }
762         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
763         eval qq{use $mod};
764         if ($@) {
765                 error("Failed to load plugin $mod: $@");
766         }
767         $loaded_plugins{$plugin}=1;
768         return 1;
771 sub error ($;$) {
772         my $message=shift;
773         my $cleaner=shift;
774         log_message('err' => $message) if $config{syslog};
775         if (defined $cleaner) {
776                 $cleaner->();
777         }
778         die $message."\n";
781 sub debug ($) {
782         return unless $config{verbose};
783         return log_message(debug => @_);
786 my $log_open=0;
787 my $log_failed=0;
788 sub log_message ($$) {
789         my $type=shift;
791         if ($config{syslog}) {
792                 require Sys::Syslog;
793                 if (! $log_open) {
794                         Sys::Syslog::setlogsock('unix');
795                         Sys::Syslog::openlog('ikiwiki', '', 'user');
796                         $log_open=1;
797                 }
798                 eval {
799                         # keep a copy to avoid editing the original config repeatedly
800                         my $wikiname = $config{wikiname};
801                         utf8::encode($wikiname);
802                         Sys::Syslog::syslog($type, "[$wikiname] %s", join(" ", @_));
803                 };
804                 if ($@) {
805                     print STDERR "failed to syslog: $@" unless $log_failed;
806                     $log_failed=1;
807                     print STDERR "@_\n";
808                 }
809                 return $@;
810         }
811         elsif (! $config{cgi}) {
812                 return print "@_\n";
813         }
814         else {
815                 return print STDERR "@_\n";
816         }
819 sub possibly_foolish_untaint ($) {
820         my $tainted=shift;
821         my ($untainted)=$tainted=~/(.*)/s;
822         return $untainted;
825 sub basename ($) {
826         my $file=shift;
828         $file=~s!.*/+!!;
829         return $file;
832 sub dirname ($) {
833         my $file=shift;
835         $file=~s!/*[^/]+$!!;
836         return $file;
839 sub isinternal ($) {
840         my $page=shift;
841         return exists $pagesources{$page} &&
842                 $pagesources{$page} =~ /\._([^.]+)$/;
845 sub pagetype ($) {
846         my $file=shift;
847         
848         if ($file =~ /\.([^.]+)$/) {
849                 return $1 if exists $hooks{htmlize}{$1};
850         }
851         my $base=basename($file);
852         if (exists $hooks{htmlize}{$base} &&
853             $hooks{htmlize}{$base}{noextension}) {
854                 return $base;
855         }
856         return;
859 my %pagename_cache;
861 sub pagename ($) {
862         my $file=shift;
864         if (exists $pagename_cache{$file}) {
865                 return $pagename_cache{$file};
866         }
868         my $type=pagetype($file);
869         my $page=$file;
870         $page=~s/\Q.$type\E*$//
871                 if defined $type && !$hooks{htmlize}{$type}{keepextension}
872                         && !$hooks{htmlize}{$type}{noextension};
873         if ($config{indexpages} && $page=~/(.*)\/index$/) {
874                 $page=$1;
875         }
877         $pagename_cache{$file} = $page;
878         return $page;
881 sub newpagefile ($$) {
882         my $page=shift;
883         my $type=shift;
885         if (! $config{indexpages} || $page eq 'index') {
886                 return $page.".".$type;
887         }
888         else {
889                 return $page."/index.".$type;
890         }
893 sub targetpage ($$;$) {
894         my $page=shift;
895         my $ext=shift;
896         my $filename=shift;
897         
898         if (defined $filename) {
899                 return $page."/".$filename.".".$ext;
900         }
901         elsif (! $config{usedirs} || $page eq 'index') {
902                 return $page.".".$ext;
903         }
904         else {
905                 return $page."/index.".$ext;
906         }
909 sub htmlpage ($) {
910         my $page=shift;
911         
912         return targetpage($page, $config{htmlext});
915 sub srcfile_stat {
916         my $file=shift;
917         my $nothrow=shift;
919         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
920         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
921                 return "$dir/$file", stat(_) if -e "$dir/$file";
922         }
923         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
924         return;
927 sub srcfile ($;$) {
928         return (srcfile_stat(@_))[0];
931 sub add_literal_underlay ($) {
932         my $dir=shift;
934         if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
935                 unshift @{$config{underlaydirs}}, $dir;
936         }
939 sub add_underlay ($) {
940         my $dir = shift;
942         if ($dir !~ /^\//) {
943                 $dir="$config{underlaydirbase}/$dir";
944         }
946         add_literal_underlay($dir);
947         # why does it return 1? we just don't know
948         return 1;
951 sub readfile ($;$$) {
952         my $file=shift;
953         my $binary=shift;
954         my $wantfd=shift;
956         if (-l $file) {
957                 error("cannot read a symlink ($file)");
958         }
959         
960         local $/=undef;
961         open (my $in, "<", $file) || error("failed to read $file: $!");
962         binmode($in) if ($binary);
963         return \*$in if $wantfd;
964         my $ret=<$in>;
965         # check for invalid utf-8, and toss it back to avoid crashes
966         if (! utf8::valid($ret)) {
967                 $ret=encode_utf8($ret);
968         }
969         close $in || error("failed to read $file: $!");
970         return $ret;
973 sub prep_writefile ($$) {
974         my $file=shift;
975         my $destdir=shift;
976         
977         my $test=$file;
978         while (length $test) {
979                 if (-l "$destdir/$test") {
980                         error("cannot write to a symlink ($test)");
981                 }
982                 if (-f _ && $test ne $file) {
983                         # Remove conflicting file.
984                         foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
985                                 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
986                                         if ($f eq $test) {
987                                                 unlink("$destdir/$test");
988                                                 last;
989                                         }
990                                 }
991                         }
992                 }
993                 $test=dirname($test);
994         }
996         my $dir=dirname("$destdir/$file");
997         if (! -d $dir) {
998                 my $d="";
999                 foreach my $s (split(m!/+!, $dir)) {
1000                         $d.="$s/";
1001                         if (! -d $d) {
1002                                 mkdir($d) || error("failed to create directory $d: $!");
1003                         }
1004                 }
1005         }
1007         return 1;
1010 sub writefile ($$$;$$) {
1011         my $file=shift; # can include subdirs
1012         my $destdir=shift; # directory to put file in
1013         my $content=shift;
1014         my $binary=shift;
1015         my $writer=shift;
1016         
1017         prep_writefile($file, $destdir);
1018         
1019         my $newfile="$destdir/$file.ikiwiki-new";
1020         if (-l $newfile) {
1021                 error("cannot write to a symlink ($newfile)");
1022         }
1023         
1024         my $cleanup = sub { unlink($newfile) };
1025         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
1026         binmode($out) if ($binary);
1027         if ($writer) {
1028                 $writer->(\*$out, $cleanup);
1029         }
1030         else {
1031                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
1032         }
1033         close $out || error("failed saving $newfile: $!", $cleanup);
1034         rename($newfile, "$destdir/$file") || 
1035                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1037         return 1;
1040 my %cleared;
1041 sub will_render ($$;$) {
1042         my $page=shift;
1043         my $dest=shift;
1044         my $clear=shift;
1046         # Important security check for independently created files.
1047         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1048             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1049                 my $from_other_page=0;
1050                 # Expensive, but rarely runs.
1051                 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1052                         if (grep {
1053                                 $_ eq $dest ||
1054                                 dirname($_) eq $dest
1055                             } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1056                                 $from_other_page=1;
1057                                 last;
1058                         }
1059                 }
1061                 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1062                         unless $from_other_page;
1063         }
1065         # If $dest exists as a directory, remove conflicting files in it
1066         # rendered from other pages.
1067         if (-d _) {
1068                 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1069                         foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1070                                 if (dirname($f) eq $dest) {
1071                                         unlink("$config{destdir}/$f");
1072                                         rmdir(dirname("$config{destdir}/$f"));
1073                                 }
1074                         }
1075                 }
1076         }
1078         if (! $clear || $cleared{$page}) {
1079                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1080         }
1081         else {
1082                 foreach my $old (@{$renderedfiles{$page}}) {
1083                         delete $destsources{$old};
1084                 }
1085                 $renderedfiles{$page}=[$dest];
1086                 $cleared{$page}=1;
1087         }
1088         $destsources{$dest}=$page;
1090         return 1;
1093 sub bestlink ($$) {
1094         my $page=shift;
1095         my $link=shift;
1096         
1097         my $cwd=$page;
1098         if ($link=~s/^\/+//) {
1099                 # absolute links
1100                 $cwd="";
1101         }
1102         $link=~s/\/$//;
1104         do {
1105                 my $l=$cwd;
1106                 $l.="/" if length $l;
1107                 $l.=$link;
1109                 if (exists $pagesources{$l}) {
1110                         return $l;
1111                 }
1112                 elsif (exists $pagecase{lc $l}) {
1113                         return $pagecase{lc $l};
1114                 }
1115         } while $cwd=~s{/?[^/]+$}{};
1117         if (length $config{userdir}) {
1118                 my $l = "$config{userdir}/".lc($link);
1119                 if (exists $pagesources{$l}) {
1120                         return $l;
1121                 }
1122                 elsif (exists $pagecase{lc $l}) {
1123                         return $pagecase{lc $l};
1124                 }
1125         }
1127         #print STDERR "warning: page $page, broken link: $link\n";
1128         return "";
1131 sub isinlinableimage ($) {
1132         my $file=shift;
1133         
1134         return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1137 sub pagetitle ($;$) {
1138         my $page=shift;
1139         my $unescaped=shift;
1141         if ($unescaped) {
1142                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1143         }
1144         else {
1145                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1146         }
1148         return $page;
1151 sub titlepage ($) {
1152         my $title=shift;
1153         # support use w/o %config set
1154         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1155         $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1156         return $title;
1159 sub linkpage ($) {
1160         my $link=shift;
1161         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1162         $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1163         return $link;
1166 sub cgiurl (@) {
1167         my %params=@_;
1169         my $cgiurl=$local_cgiurl;
1171         if (exists $params{cgiurl}) {
1172                 $cgiurl=$params{cgiurl};
1173                 delete $params{cgiurl};
1174         }
1176         unless (%params) {
1177                 return $cgiurl;
1178         }
1180         return $cgiurl."?".
1181                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1184 sub cgiurl_abs (@) {
1185         eval q{use URI};
1186         URI->new_abs(cgiurl(@_), $config{cgiurl});
1189 sub baseurl (;$) {
1190         my $page=shift;
1192         return $local_url if ! defined $page;
1193         
1194         $page=htmlpage($page);
1195         $page=~s/[^\/]+$//;
1196         $page=~s/[^\/]+\//..\//g;
1197         return $page;
1200 sub urlabs ($$) {
1201         my $url=shift;
1202         my $urlbase=shift;
1204         return $url unless defined $urlbase && length $urlbase;
1206         eval q{use URI};
1207         URI->new_abs($url, $urlbase)->as_string;
1210 sub abs2rel ($$) {
1211         # Work around very innefficient behavior in File::Spec if abs2rel
1212         # is passed two relative paths. It's much faster if paths are
1213         # absolute! (Debian bug #376658; fixed in debian unstable now)
1214         my $path="/".shift;
1215         my $base="/".shift;
1217         require File::Spec;
1218         my $ret=File::Spec->abs2rel($path, $base);
1219         $ret=~s/^// if defined $ret;
1220         return $ret;
1223 sub displaytime ($;$$) {
1224         # Plugins can override this function to mark up the time to
1225         # display.
1226         my $time=formattime($_[0], $_[1]);
1227         if ($config{html5}) {
1228                 return '<time datetime="'.date_3339($_[0]).'"'.
1229                         ($_[2] ? ' pubdate="pubdate"' : '').
1230                         '>'.$time.'</time>';
1231         }
1232         else {
1233                 return '<span class="date">'.$time.'</span>';
1234         }
1237 sub formattime ($;$) {
1238         # Plugins can override this function to format the time.
1239         my $time=shift;
1240         my $format=shift;
1241         if (! defined $format) {
1242                 $format=$config{timeformat};
1243         }
1245         return strftime_utf8($format, localtime($time));
1248 my $strftime_encoding;
1249 sub strftime_utf8 {
1250         # strftime doesn't know about encodings, so make sure
1251         # its output is properly treated as utf8.
1252         # Note that this does not handle utf-8 in the format string.
1253         ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1254                 unless defined $strftime_encoding;
1255         $strftime_encoding
1256                 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1257                 : POSIX::strftime(@_);
1260 sub date_3339 ($) {
1261         my $time=shift;
1263         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1264         POSIX::setlocale(&POSIX::LC_TIME, "C");
1265         my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1266         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1267         return $ret;
1270 sub beautify_urlpath ($) {
1271         my $url=shift;
1273         # Ensure url is not an empty link, and if necessary,
1274         # add ./ to avoid colon confusion.
1275         if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1276                 $url="./$url";
1277         }
1279         if ($config{usedirs}) {
1280                 $url =~ s!/index.$config{htmlext}$!/!;
1281         }
1283         return $url;
1286 sub urlto ($;$$) {
1287         my $to=shift;
1288         my $from=shift;
1289         my $absolute=shift;
1290         
1291         if (! length $to) {
1292                 $to = 'index';
1293         }
1295         if (! $destsources{$to}) {
1296                 $to=htmlpage($to);
1297         }
1299         if ($absolute) {
1300                 return $config{url}.beautify_urlpath("/".$to);
1301         }
1303         if (! defined $from) {
1304                 my $u = $local_url || '';
1305                 $u =~ s{/$}{};
1306                 return $u.beautify_urlpath("/".$to);
1307         }
1309         my $link = abs2rel($to, dirname(htmlpage($from)));
1311         return beautify_urlpath($link);
1314 sub isselflink ($$) {
1315         # Plugins can override this function to support special types
1316         # of selflinks.
1317         my $page=shift;
1318         my $link=shift;
1320         return $page eq $link;
1323 sub htmllink ($$$;@) {
1324         my $lpage=shift; # the page doing the linking
1325         my $page=shift; # the page that will contain the link (different for inline)
1326         my $link=shift;
1327         my %opts=@_;
1329         $link=~s/\/$//;
1331         my $bestlink;
1332         if (! $opts{forcesubpage}) {
1333                 $bestlink=bestlink($lpage, $link);
1334         }
1335         else {
1336                 $bestlink="$lpage/".lc($link);
1337         }
1339         my $linktext;
1340         if (defined $opts{linktext}) {
1341                 $linktext=$opts{linktext};
1342         }
1343         else {
1344                 $linktext=pagetitle(basename($link));
1345         }
1346         
1347         return "<span class=\"selflink\">$linktext</span>"
1348                 if length $bestlink && isselflink($page, $bestlink) &&
1349                    ! defined $opts{anchor};
1350         
1351         if (! $destsources{$bestlink}) {
1352                 $bestlink=htmlpage($bestlink);
1354                 if (! $destsources{$bestlink}) {
1355                         my $cgilink = "";
1356                         if (length $config{cgiurl}) {
1357                                 $cgilink = "<a href=\"".
1358                                         cgiurl(
1359                                                 do => "create",
1360                                                 page => $link,
1361                                                 from => $lpage
1362                                         )."\" rel=\"nofollow\">?</a>";
1363                         }
1364                         return "<span class=\"createlink\">$cgilink$linktext</span>"
1365                 }
1366         }
1367         
1368         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1369         $bestlink=beautify_urlpath($bestlink);
1370         
1371         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1372                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1373         }
1375         if (defined $opts{anchor}) {
1376                 $bestlink.="#".$opts{anchor};
1377         }
1379         my @attrs;
1380         foreach my $attr (qw{rel class title}) {
1381                 if (defined $opts{$attr}) {
1382                         push @attrs, " $attr=\"$opts{$attr}\"";
1383                 }
1384         }
1386         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1389 sub userpage ($) {
1390         my $user=shift;
1391         return length $config{userdir} ? "$config{userdir}/$user" : $user;
1394 sub openiduser ($) {
1395         my $user=shift;
1397         if (defined $user && $user =~ m!^https?://! &&
1398             eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1399                 my $display;
1401                 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1402                         $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1403                 }
1404                 else {
1405                         # backcompat with old version
1406                         my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1407                         $display=$oid->display;
1408                 }
1410                 # Convert "user.somehost.com" to "user [somehost.com]"
1411                 # (also "user.somehost.co.uk")
1412                 if ($display !~ /\[/) {
1413                         $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1414                 }
1415                 # Convert "http://somehost.com/user" to "user [somehost.com]".
1416                 # (also "https://somehost.com/user/")
1417                 if ($display !~ /\[/) {
1418                         $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1419                 }
1420                 $display=~s!^https?://!!; # make sure this is removed
1421                 eval q{use CGI 'escapeHTML'};
1422                 error($@) if $@;
1423                 return escapeHTML($display);
1424         }
1425         return;
1428 sub htmlize ($$$$) {
1429         my $page=shift;
1430         my $destpage=shift;
1431         my $type=shift;
1432         my $content=shift;
1433         
1434         my $oneline = $content !~ /\n/;
1435         
1436         if (exists $hooks{htmlize}{$type}) {
1437                 $content=$hooks{htmlize}{$type}{call}->(
1438                         page => $page,
1439                         content => $content,
1440                 );
1441         }
1442         else {
1443                 error("htmlization of $type not supported");
1444         }
1446         run_hooks(sanitize => sub {
1447                 $content=shift->(
1448                         page => $page,
1449                         destpage => $destpage,
1450                         content => $content,
1451                 );
1452         });
1453         
1454         if ($oneline) {
1455                 # hack to get rid of enclosing junk added by markdown
1456                 # and other htmlizers/sanitizers
1457                 $content=~s/^<p>//i;
1458                 $content=~s/<\/p>\n*$//i;
1459         }
1461         return $content;
1464 sub linkify ($$$) {
1465         my $page=shift;
1466         my $destpage=shift;
1467         my $content=shift;
1469         run_hooks(linkify => sub {
1470                 $content=shift->(
1471                         page => $page,
1472                         destpage => $destpage,
1473                         content => $content,
1474                 );
1475         });
1476         
1477         return $content;
1480 our %preprocessing;
1481 our $preprocess_preview=0;
1482 sub preprocess ($$$;$$) {
1483         my $page=shift; # the page the data comes from
1484         my $destpage=shift; # the page the data will appear in (different for inline)
1485         my $content=shift;
1486         my $scan=shift;
1487         my $preview=shift;
1489         # Using local because it needs to be set within any nested calls
1490         # of this function.
1491         local $preprocess_preview=$preview if defined $preview;
1493         my $handle=sub {
1494                 my $escape=shift;
1495                 my $prefix=shift;
1496                 my $command=shift;
1497                 my $params=shift;
1498                 $params="" if ! defined $params;
1500                 if (length $escape) {
1501                         return "[[$prefix$command $params]]";
1502                 }
1503                 elsif (exists $hooks{preprocess}{$command}) {
1504                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1505                         # Note: preserve order of params, some plugins may
1506                         # consider it significant.
1507                         my @params;
1508                         while ($params =~ m{
1509                                 (?:([-.\w]+)=)?         # 1: named parameter key?
1510                                 (?:
1511                                         """(.*?)"""     # 2: triple-quoted value
1512                                 |
1513                                         "([^"]*?)"      # 3: single-quoted value
1514                                 |
1515                                         '''(.*?)'''     # 4: triple-single-quote
1516                                 |
1517                                         <<([a-zA-Z]+)\n # 5: heredoc start
1518                                         (.*?)\n\5       # 6: heredoc value
1519                                 |
1520                                         (\S+)           # 7: unquoted value
1521                                 )
1522                                 (?:\s+|$)               # delimiter to next param
1523                         }msgx) {
1524                                 my $key=$1;
1525                                 my $val;
1526                                 if (defined $2) {
1527                                         $val=$2;
1528                                         $val=~s/\r\n/\n/mg;
1529                                         $val=~s/^\n+//g;
1530                                         $val=~s/\n+$//g;
1531                                 }
1532                                 elsif (defined $3) {
1533                                         $val=$3;
1534                                 }
1535                                 elsif (defined $4) {
1536                                         $val=$4;
1537                                 }
1538                                 elsif (defined $7) {
1539                                         $val=$7;
1540                                 }
1541                                 elsif (defined $6) {
1542                                         $val=$6;
1543                                 }
1545                                 if (defined $key) {
1546                                         push @params, $key, $val;
1547                                 }
1548                                 else {
1549                                         push @params, $val, '';
1550                                 }
1551                         }
1552                         if ($preprocessing{$page}++ > 8) {
1553                                 # Avoid loops of preprocessed pages preprocessing
1554                                 # other pages that preprocess them, etc.
1555                                 return "[[!$command <span class=\"error\">".
1556                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1557                                                 $page, $preprocessing{$page}).
1558                                         "</span>]]";
1559                         }
1560                         my $ret;
1561                         if (! $scan) {
1562                                 $ret=eval {
1563                                         $hooks{preprocess}{$command}{call}->(
1564                                                 @params,
1565                                                 page => $page,
1566                                                 destpage => $destpage,
1567                                                 preview => $preprocess_preview,
1568                                         );
1569                                 };
1570                                 if ($@) {
1571                                         my $error=$@;
1572                                         chomp $error;
1573                                         eval q{use HTML::Entities};
1574                                         $error = encode_entities($error);
1575                                         $ret="[[!$command <span class=\"error\">".
1576                                                 gettext("Error").": $error"."</span>]]";
1577                                 }
1578                         }
1579                         else {
1580                                 # use void context during scan pass
1581                                 eval {
1582                                         $hooks{preprocess}{$command}{call}->(
1583                                                 @params,
1584                                                 page => $page,
1585                                                 destpage => $destpage,
1586                                                 preview => $preprocess_preview,
1587                                         );
1588                                 };
1589                                 $ret="";
1590                         }
1591                         $preprocessing{$page}--;
1592                         return $ret;
1593                 }
1594                 else {
1595                         return "[[$prefix$command $params]]";
1596                 }
1597         };
1598         
1599         my $regex;
1600         if ($config{prefix_directives}) {
1601                 $regex = qr{
1602                         (\\?)           # 1: escape?
1603                         \[\[(!)         # directive open; 2: prefix
1604                         ([-\w]+)        # 3: command
1605                         (               # 4: the parameters..
1606                                 \s+     # Must have space if parameters present
1607                                 (?:
1608                                         (?:[-.\w]+=)?           # named parameter key?
1609                                         (?:
1610                                                 """.*?"""       # triple-quoted value
1611                                                 |
1612                                                 "[^"]*?"        # single-quoted value
1613                                                 |
1614                                                 '''.*?'''       # triple-single-quote
1615                                                 |
1616                                                 <<([a-zA-Z]+)\n # 5: heredoc start
1617                                                 (?:.*?)\n\5     # heredoc value
1618                                                 |
1619                                                 [^"\s\]]+       # unquoted value
1620                                         )
1621                                         \s*                     # whitespace or end
1622                                                                 # of directive
1623                                 )
1624                         *)?             # 0 or more parameters
1625                         \]\]            # directive closed
1626                 }sx;
1627         }
1628         else {
1629                 $regex = qr{
1630                         (\\?)           # 1: escape?
1631                         \[\[(!?)        # directive open; 2: optional prefix
1632                         ([-\w]+)        # 3: command
1633                         \s+
1634                         (               # 4: the parameters..
1635                                 (?:
1636                                         (?:[-.\w]+=)?           # named parameter key?
1637                                         (?:
1638                                                 """.*?"""       # triple-quoted value
1639                                                 |
1640                                                 "[^"]*?"        # single-quoted value
1641                                                 |
1642                                                 '''.*?'''       # triple-single-quote
1643                                                 |
1644                                                 <<([a-zA-Z]+)\n # 5: heredoc start
1645                                                 (?:.*?)\n\5     # heredoc value
1646                                                 |
1647                                                 [^"\s\]]+       # unquoted value
1648                                         )
1649                                         \s*                     # whitespace or end
1650                                                                 # of directive
1651                                 )
1652                         *)              # 0 or more parameters
1653                         \]\]            # directive closed
1654                 }sx;
1655         }
1657         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1658         return $content;
1661 sub filter ($$$) {
1662         my $page=shift;
1663         my $destpage=shift;
1664         my $content=shift;
1666         run_hooks(filter => sub {
1667                 $content=shift->(page => $page, destpage => $destpage, 
1668                         content => $content);
1669         });
1671         return $content;
1674 sub check_canedit ($$$;$) {
1675         my $page=shift;
1676         my $q=shift;
1677         my $session=shift;
1678         my $nonfatal=shift;
1679         
1680         my $canedit;
1681         run_hooks(canedit => sub {
1682                 return if defined $canedit;
1683                 my $ret=shift->($page, $q, $session);
1684                 if (defined $ret) {
1685                         if ($ret eq "") {
1686                                 $canedit=1;
1687                         }
1688                         elsif (ref $ret eq 'CODE') {
1689                                 $ret->() unless $nonfatal;
1690                                 $canedit=0;
1691                         }
1692                         elsif (defined $ret) {
1693                                 error($ret) unless $nonfatal;
1694                                 $canedit=0;
1695                         }
1696                 }
1697         });
1698         return defined $canedit ? $canedit : 1;
1701 sub check_content (@) {
1702         my %params=@_;
1703         
1704         return 1 if ! exists $hooks{checkcontent}; # optimisation
1706         if (exists $pagesources{$params{page}}) {
1707                 my @diff;
1708                 my %old=map { $_ => 1 }
1709                         split("\n", readfile(srcfile($pagesources{$params{page}})));
1710                 foreach my $line (split("\n", $params{content})) {
1711                         push @diff, $line if ! exists $old{$line};
1712                 }
1713                 $params{diff}=join("\n", @diff);
1714         }
1716         my $ok;
1717         run_hooks(checkcontent => sub {
1718                 return if defined $ok;
1719                 my $ret=shift->(%params);
1720                 if (defined $ret) {
1721                         if ($ret eq "") {
1722                                 $ok=1;
1723                         }
1724                         elsif (ref $ret eq 'CODE') {
1725                                 $ret->() unless $params{nonfatal};
1726                                 $ok=0;
1727                         }
1728                         elsif (defined $ret) {
1729                                 error($ret) unless $params{nonfatal};
1730                                 $ok=0;
1731                         }
1732                 }
1734         });
1735         return defined $ok ? $ok : 1;
1738 sub check_canchange (@) {
1739         my %params = @_;
1740         my $cgi = $params{cgi};
1741         my $session = $params{session};
1742         my @changes = @{$params{changes}};
1744         my %newfiles;
1745         foreach my $change (@changes) {
1746                 # This untaint is safe because we check file_pruned and
1747                 # wiki_file_regexp.
1748                 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1749                 $file=possibly_foolish_untaint($file);
1750                 if (! defined $file || ! length $file ||
1751                     file_pruned($file)) {
1752                         error(gettext("bad file name %s"), $file);
1753                 }
1755                 my $type=pagetype($file);
1756                 my $page=pagename($file) if defined $type;
1758                 if ($change->{action} eq 'add') {
1759                         $newfiles{$file}=1;
1760                 }
1762                 if ($change->{action} eq 'change' ||
1763                     $change->{action} eq 'add') {
1764                         if (defined $page) {
1765                                 check_canedit($page, $cgi, $session);
1766                                 next;
1767                         }
1768                         else {
1769                                 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1770                                         IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1771                                         check_canedit($file, $cgi, $session);
1772                                         next;
1773                                 }
1774                         }
1775                 }
1776                 elsif ($change->{action} eq 'remove') {
1777                         # check_canremove tests to see if the file is present
1778                         # on disk. This will fail when a single commit adds a
1779                         # file and then removes it again. Avoid the problem
1780                         # by not testing the removal in such pairs of changes.
1781                         # (The add is still tested, just to make sure that
1782                         # no data is added to the repo that a web edit
1783                         # could not add.)
1784                         next if $newfiles{$file};
1786                         if (IkiWiki::Plugin::remove->can("check_canremove")) {
1787                                 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1788                                 check_canedit(defined $page ? $page : $file, $cgi, $session);
1789                                 next;
1790                         }
1791                 }
1792                 else {
1793                         error "unknown action ".$change->{action};
1794                 }
1796                 error sprintf(gettext("you are not allowed to change %s"), $file);
1797         }
1801 my $wikilock;
1803 sub lockwiki () {
1804         # Take an exclusive lock on the wiki to prevent multiple concurrent
1805         # run issues. The lock will be dropped on program exit.
1806         if (! -d $config{wikistatedir}) {
1807                 mkdir($config{wikistatedir});
1808         }
1809         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1810                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1811         if (! flock($wikilock, 2)) { # LOCK_EX
1812                 error("failed to get lock");
1813         }
1814         return 1;
1817 sub unlockwiki () {
1818         POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1819         return close($wikilock) if $wikilock;
1820         return;
1823 my $commitlock;
1825 sub commit_hook_enabled () {
1826         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1827                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1828         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1829                 close($commitlock) || error("failed closing commitlock: $!");
1830                 return 0;
1831         }
1832         close($commitlock) || error("failed closing commitlock: $!");
1833         return 1;
1836 sub disable_commit_hook () {
1837         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1838                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1839         if (! flock($commitlock, 2)) { # LOCK_EX
1840                 error("failed to get commit lock");
1841         }
1842         return 1;
1845 sub enable_commit_hook () {
1846         return close($commitlock) if $commitlock;
1847         return;
1850 sub loadindex () {
1851         %oldrenderedfiles=%pagectime=();
1852         my $rebuild=$config{rebuild};
1853         if (! $rebuild) {
1854                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1855                 %destsources=%renderedfiles=%pagecase=%pagestate=
1856                 %depends_simple=%typedlinks=%oldtypedlinks=();
1857         }
1858         my $in;
1859         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1860                 if (-e "$config{wikistatedir}/index") {
1861                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1862                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1863                 }
1864                 else {
1865                         # gettime on first build
1866                         $config{gettime}=1 unless defined $config{gettime};
1867                         return;
1868                 }
1869         }
1871         my $index=Storable::fd_retrieve($in);
1872         if (! defined $index) {
1873                 return 0;
1874         }
1876         my $pages;
1877         if (exists $index->{version} && ! ref $index->{version}) {
1878                 $pages=$index->{page};
1879                 %wikistate=%{$index->{state}};
1880                 # Handle plugins that got disabled by loading a new setup.
1881                 if (exists $config{setupfile}) {
1882                         require IkiWiki::Setup;
1883                         IkiWiki::Setup::disabled_plugins(
1884                                 grep { ! $loaded_plugins{$_} } keys %wikistate);
1885                 }
1886         }
1887         else {
1888                 $pages=$index;
1889                 %wikistate=();
1890         }
1892         foreach my $src (keys %$pages) {
1893                 my $d=$pages->{$src};
1894                 my $page;
1895                 if (exists $d->{page} && ! $rebuild) {
1896                         $page=$d->{page};
1897                 }
1898                 else {
1899                         $page=pagename($src);
1900                 }
1901                 $pagectime{$page}=$d->{ctime};
1902                 $pagesources{$page}=$src;
1903                 if (! $rebuild) {
1904                         $pagemtime{$page}=$d->{mtime};
1905                         $renderedfiles{$page}=$d->{dest};
1906                         if (exists $d->{links} && ref $d->{links}) {
1907                                 $links{$page}=$d->{links};
1908                                 $oldlinks{$page}=[@{$d->{links}}];
1909                         }
1910                         if (ref $d->{depends_simple} eq 'ARRAY') {
1911                                 # old format
1912                                 $depends_simple{$page}={
1913                                         map { $_ => 1 } @{$d->{depends_simple}}
1914                                 };
1915                         }
1916                         elsif (exists $d->{depends_simple}) {
1917                                 $depends_simple{$page}=$d->{depends_simple};
1918                         }
1919                         if (exists $d->{dependslist}) {
1920                                 # old format
1921                                 $depends{$page}={
1922                                         map { $_ => $DEPEND_CONTENT }
1923                                                 @{$d->{dependslist}}
1924                                 };
1925                         }
1926                         elsif (exists $d->{depends} && ! ref $d->{depends}) {
1927                                 # old format
1928                                 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1929                         }
1930                         elsif (exists $d->{depends}) {
1931                                 $depends{$page}=$d->{depends};
1932                         }
1933                         if (exists $d->{state}) {
1934                                 $pagestate{$page}=$d->{state};
1935                         }
1936                         if (exists $d->{typedlinks}) {
1937                                 $typedlinks{$page}=$d->{typedlinks};
1939                                 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1940                                         next unless %$links;
1941                                         $oldtypedlinks{$page}{$type} = {%$links};
1942                                 }
1943                         }
1944                 }
1945                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1946         }
1947         foreach my $page (keys %pagesources) {
1948                 $pagecase{lc $page}=$page;
1949         }
1950         foreach my $page (keys %renderedfiles) {
1951                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1952         }
1953         $lastrev=$index->{lastrev};
1954         @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
1955         return close($in);
1958 sub saveindex () {
1959         run_hooks(savestate => sub { shift->() });
1961         my @plugins=keys %loaded_plugins;
1963         if (! -d $config{wikistatedir}) {
1964                 mkdir($config{wikistatedir});
1965         }
1966         my $newfile="$config{wikistatedir}/indexdb.new";
1967         my $cleanup = sub { unlink($newfile) };
1968         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1970         my %index;
1971         foreach my $page (keys %pagemtime) {
1972                 next unless $pagemtime{$page};
1973                 my $src=$pagesources{$page};
1975                 $index{page}{$src}={
1976                         page => $page,
1977                         ctime => $pagectime{$page},
1978                         mtime => $pagemtime{$page},
1979                         dest => $renderedfiles{$page},
1980                         links => $links{$page},
1981                 };
1983                 if (exists $depends{$page}) {
1984                         $index{page}{$src}{depends} = $depends{$page};
1985                 }
1987                 if (exists $depends_simple{$page}) {
1988                         $index{page}{$src}{depends_simple} = $depends_simple{$page};
1989                 }
1991                 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1992                         $index{page}{$src}{typedlinks} = $typedlinks{$page};
1993                 }
1995                 if (exists $pagestate{$page}) {
1996                         $index{page}{$src}{state}=$pagestate{$page};
1997                 }
1998         }
2000         $index{state}={};
2001         foreach my $id (@plugins) {
2002                 $index{state}{$id}={}; # used to detect disabled plugins
2003                 foreach my $key (keys %{$wikistate{$id}}) {
2004                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
2005                 }
2006         }
2007         
2008         $index{lastrev}=$lastrev;
2009         $index{underlayfiles}=\@underlayfiles;
2011         $index{version}="3";
2012         my $ret=Storable::nstore_fd(\%index, $out);
2013         return if ! defined $ret || ! $ret;
2014         close $out || error("failed saving to $newfile: $!", $cleanup);
2015         rename($newfile, "$config{wikistatedir}/indexdb") ||
2016                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
2017         
2018         return 1;
2021 sub template_file ($) {
2022         my $name=shift;
2023         
2024         my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
2025         my $template;
2026         if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
2027                 $template=srcfile($pagesources{$tpage}, 1);
2028                 $name.=".tmpl";
2029         }
2030         else {
2031                 $template=srcfile($tpage, 1);
2032         }
2034         if (defined $template) {
2035                 return $template, $tpage, 1 if wantarray;
2036                 return $template;
2037         }
2038         else {
2039                 $name=~s:/::; # avoid path traversal
2040                 foreach my $dir ($config{templatedir},
2041                                  "$installdir/share/ikiwiki/templates") {
2042                         if (-e "$dir/$name") {
2043                                 $template="$dir/$name";
2044                                 last;
2045                         }
2046                 }
2047                 if (defined $template) {        
2048                         return $template, $tpage if wantarray;
2049                         return $template;
2050                 }
2051         }
2053         return;
2056 sub template_depends ($$;@) {
2057         my $name=shift;
2058         my $page=shift;
2059         
2060         my ($filename, $tpage, $untrusted)=template_file($name);
2061         if (! defined $filename) {
2062                 error(sprintf(gettext("template %s not found"), $name))
2063         }
2065         if (defined $page && defined $tpage) {
2066                 add_depends($page, $tpage);
2067         }
2069         my @opts=(
2070                 filter => sub {
2071                         my $text_ref = shift;
2072                         ${$text_ref} = decode_utf8(${$text_ref});
2073                         run_hooks(readtemplate => sub {
2074                                 ${$text_ref} = shift->(
2075                                         id => $name,
2076                                         page => $tpage,
2077                                         content => ${$text_ref},
2078                                         untrusted => $untrusted,
2079                                 );
2080                         });
2081                 },
2082                 loop_context_vars => 1,
2083                 die_on_bad_params => 0,
2084                 parent_global_vars => 1,
2085                 filename => $filename,
2086                 @_,
2087                 ($untrusted ? (no_includes => 1) : ()),
2088         );
2089         return @opts if wantarray;
2091         require HTML::Template;
2092         return HTML::Template->new(@opts);
2095 sub template ($;@) {
2096         template_depends(shift, undef, @_);
2099 sub templateactions ($$) {
2100         my $template=shift;
2101         my $page=shift;
2103         my $have_actions=0;
2104         my @actions;
2105         run_hooks(pageactions => sub {
2106                 push @actions, map { { action => $_ } } 
2107                         grep { defined } shift->(page => $page);
2108         });
2109         $template->param(actions => \@actions);
2111         if ($config{cgiurl} && exists $hooks{auth}) {
2112                 $template->param(prefsurl => cgiurl(do => "prefs"));
2113                 $have_actions=1;
2114         }
2116         if ($have_actions || @actions) {
2117                 $template->param(have_actions => 1);
2118         }
2121 sub hook (@) {
2122         my %param=@_;
2123         
2124         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2125                 error 'hook requires type, call, and id parameters';
2126         }
2128         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2129         
2130         $hooks{$param{type}}{$param{id}}=\%param;
2131         return 1;
2134 sub run_hooks ($$) {
2135         # Calls the given sub for each hook of the given type,
2136         # passing it the hook function to call.
2137         my $type=shift;
2138         my $sub=shift;
2140         if (exists $hooks{$type}) {
2141                 my (@first, @middle, @last);
2142                 foreach my $id (keys %{$hooks{$type}}) {
2143                         if ($hooks{$type}{$id}{first}) {
2144                                 push @first, $id;
2145                         }
2146                         elsif ($hooks{$type}{$id}{last}) {
2147                                 push @last, $id;
2148                         }
2149                         else {
2150                                 push @middle, $id;
2151                         }
2152                 }
2153                 foreach my $id (@first, @middle, @last) {
2154                         $sub->($hooks{$type}{$id}{call});
2155                 }
2156         }
2158         return 1;
2161 sub rcs_update () {
2162         $hooks{rcs}{rcs_update}{call}->(@_);
2165 sub rcs_prepedit ($) {
2166         $hooks{rcs}{rcs_prepedit}{call}->(@_);
2169 sub rcs_commit (@) {
2170         $hooks{rcs}{rcs_commit}{call}->(@_);
2173 sub rcs_commit_staged (@) {
2174         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2177 sub rcs_add ($) {
2178         $hooks{rcs}{rcs_add}{call}->(@_);
2181 sub rcs_remove ($) {
2182         $hooks{rcs}{rcs_remove}{call}->(@_);
2185 sub rcs_rename ($$) {
2186         $hooks{rcs}{rcs_rename}{call}->(@_);
2189 sub rcs_recentchanges ($) {
2190         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2193 sub rcs_diff ($;$) {
2194         $hooks{rcs}{rcs_diff}{call}->(@_);
2197 sub rcs_getctime ($) {
2198         $hooks{rcs}{rcs_getctime}{call}->(@_);
2201 sub rcs_getmtime ($) {
2202         $hooks{rcs}{rcs_getmtime}{call}->(@_);
2205 sub rcs_receive () {
2206         $hooks{rcs}{rcs_receive}{call}->();
2209 sub add_depends ($$;$) {
2210         my $page=shift;
2211         my $pagespec=shift;
2212         my $deptype=shift || $DEPEND_CONTENT;
2214         # Is the pagespec a simple page name?
2215         if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2216             $pagespec !~ /[\s*?()!]/) {
2217                 $depends_simple{$page}{lc $pagespec} |= $deptype;
2218                 return 1;
2219         }
2221         # Add explicit dependencies for influences.
2222         my $sub=pagespec_translate($pagespec);
2223         return unless defined $sub;
2224         foreach my $p (keys %pagesources) {
2225                 my $r=$sub->($p, location => $page);
2226                 my $i=$r->influences;
2227                 my $static=$r->influences_static;
2228                 foreach my $k (keys %$i) {
2229                         next unless $r || $static || $k eq $page;
2230                         $depends_simple{$page}{lc $k} |= $i->{$k};
2231                 }
2232                 last if $static;
2233         }
2235         $depends{$page}{$pagespec} |= $deptype;
2236         return 1;
2239 sub deptype (@) {
2240         my $deptype=0;
2241         foreach my $type (@_) {
2242                 if ($type eq 'presence') {
2243                         $deptype |= $DEPEND_PRESENCE;
2244                 }
2245                 elsif ($type eq 'links') { 
2246                         $deptype |= $DEPEND_LINKS;
2247                 }
2248                 elsif ($type eq 'content') {
2249                         $deptype |= $DEPEND_CONTENT;
2250                 }
2251         }
2252         return $deptype;
2255 my $file_prune_regexp;
2256 sub file_pruned ($) {
2257         my $file=shift;
2259         if (defined $config{include} && length $config{include}) {
2260                 return 0 if $file =~ m/$config{include}/;
2261         }
2263         if (! defined $file_prune_regexp) {
2264                 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2265                 $file_prune_regexp=qr/$file_prune_regexp/;
2266         }
2267         return $file =~ m/$file_prune_regexp/;
2270 sub define_gettext () {
2271         # If translation is needed, redefine the gettext function to do it.
2272         # Otherwise, it becomes a quick no-op.
2273         my $gettext_obj;
2274         my $getobj;
2275         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2276             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2277             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2278                 $getobj=sub {
2279                         $gettext_obj=eval q{
2280                                 use Locale::gettext q{textdomain};
2281                                 Locale::gettext->domain('ikiwiki')
2282                         };
2283                 };
2284         }
2286         no warnings 'redefine';
2287         *gettext=sub {
2288                 $getobj->() if $getobj;
2289                 if ($gettext_obj) {
2290                         $gettext_obj->get(shift);
2291                 }
2292                 else {
2293                         return shift;
2294                 }
2295         };
2296         *ngettext=sub {
2297                 $getobj->() if $getobj;
2298                 if ($gettext_obj) {
2299                         $gettext_obj->nget(@_);
2300                 }
2301                 else {
2302                         return ($_[2] == 1 ? $_[0] : $_[1])
2303                 }
2304         };
2307 sub gettext {
2308         define_gettext();
2309         gettext(@_);
2312 sub ngettext {
2313         define_gettext();
2314         ngettext(@_);
2317 sub yesno ($) {
2318         my $val=shift;
2320         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2323 sub inject {
2324         # Injects a new function into the symbol table to replace an
2325         # exported function.
2326         my %params=@_;
2328         # This is deep ugly perl foo, beware.
2329         no strict;
2330         no warnings;
2331         if (! defined $params{parent}) {
2332                 $params{parent}='::';
2333                 $params{old}=\&{$params{name}};
2334                 $params{name}=~s/.*:://;
2335         }
2336         my $parent=$params{parent};
2337         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2338                 $ns = $params{parent} . $ns;
2339                 inject(%params, parent => $ns) unless $ns eq '::main::';
2340                 *{$ns . $params{name}} = $params{call}
2341                         if exists ${$ns}{$params{name}} &&
2342                            \&{${$ns}{$params{name}}} == $params{old};
2343         }
2344         use strict;
2345         use warnings;
2348 sub add_link ($$;$) {
2349         my $page=shift;
2350         my $link=shift;
2351         my $type=shift;
2353         push @{$links{$page}}, $link
2354                 unless grep { $_ eq $link } @{$links{$page}};
2356         if (defined $type) {
2357                 $typedlinks{$page}{$type}{$link} = 1;
2358         }
2361 sub add_autofile ($$$) {
2362         my $file=shift;
2363         my $plugin=shift;
2364         my $generator=shift;
2365         
2366         $autofiles{$file}{plugin}=$plugin;
2367         $autofiles{$file}{generator}=$generator;
2370 sub useragent () {
2371         return LWP::UserAgent->new(
2372                 cookie_jar => $config{cookiejar},
2373                 env_proxy => 1,         # respect proxy env vars
2374                 agent => $config{useragent},
2375         );
2378 sub sortspec_translate ($$) {
2379         my $spec = shift;
2380         my $reverse = shift;
2382         my $code = "";
2383         my @data;
2384         while ($spec =~ m{
2385                 \s*
2386                 (-?)            # group 1: perhaps negated
2387                 \s*
2388                 (               # group 2: a word
2389                         \w+\([^\)]*\)   # command(params)
2390                         |
2391                         [^\s]+          # or anything else
2392                 )
2393                 \s*
2394         }gx) {
2395                 my $negated = $1;
2396                 my $word = $2;
2397                 my $params = undef;
2399                 if ($word =~ m/^(\w+)\((.*)\)$/) {
2400                         # command with parameters
2401                         $params = $2;
2402                         $word = $1;
2403                 }
2404                 elsif ($word !~ m/^\w+$/) {
2405                         error(sprintf(gettext("invalid sort type %s"), $word));
2406                 }
2408                 if (length $code) {
2409                         $code .= " || ";
2410                 }
2412                 if ($negated) {
2413                         $code .= "-";
2414                 }
2416                 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2417                         if (defined $params) {
2418                                 push @data, $params;
2419                                 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2420                         }
2421                         else {
2422                                 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2423                         }
2424                 }
2425                 else {
2426                         error(sprintf(gettext("unknown sort type %s"), $word));
2427                 }
2428         }
2430         if (! length $code) {
2431                 # undefined sorting method... sort arbitrarily
2432                 return sub { 0 };
2433         }
2435         if ($reverse) {
2436                 $code="-($code)";
2437         }
2439         no warnings;
2440         return eval 'sub { '.$code.' }';
2443 sub pagespec_translate ($) {
2444         my $spec=shift;
2446         # Convert spec to perl code.
2447         my $code="";
2448         my @data;
2449         while ($spec=~m{
2450                 \s*             # ignore whitespace
2451                 (               # 1: match a single word
2452                         \!              # !
2453                 |
2454                         \(              # (
2455                 |
2456                         \)              # )
2457                 |
2458                         \w+\([^\)]*\)   # command(params)
2459                 |
2460                         [^\s()]+        # any other text
2461                 )
2462                 \s*             # ignore whitespace
2463         }gx) {
2464                 my $word=$1;
2465                 if (lc $word eq 'and') {
2466                         $code.=' &';
2467                 }
2468                 elsif (lc $word eq 'or') {
2469                         $code.=' |';
2470                 }
2471                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2472                         $code.=' '.$word;
2473                 }
2474                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2475                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2476                                 push @data, $2;
2477                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2478                         }
2479                         else {
2480                                 push @data, qq{unknown function in pagespec "$word"};
2481                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2482                         }
2483                 }
2484                 else {
2485                         push @data, $word;
2486                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2487                 }
2488         }
2490         if (! length $code) {
2491                 $code="IkiWiki::FailReason->new('empty pagespec')";
2492         }
2494         no warnings;
2495         return eval 'sub { my $page=shift; '.$code.' }';
2498 sub pagespec_match ($$;@) {
2499         my $page=shift;
2500         my $spec=shift;
2501         my @params=@_;
2503         # Backwards compatability with old calling convention.
2504         if (@params == 1) {
2505                 unshift @params, 'location';
2506         }
2508         my $sub=pagespec_translate($spec);
2509         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2510                 if ! defined $sub;
2511         return $sub->($page, @params);
2514 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2516 # Not exported yet, but could be in future if it is generally useful.
2517 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2518 # which is "more internal".
2519 sub sort_pages ($$;@) {
2520         my $sort = shift;
2521         my $list = shift;
2522         my %params = @_;
2523         $sort = sortspec_translate($sort, $params{reverse});
2524         return IkiWiki::SortSpec::sort_pages($sort, @$list);
2527 sub pagespec_match_list ($$;@) {
2528         my $page=shift;
2529         my $pagespec=shift;
2530         my %params=@_;
2532         # Backwards compatability with old calling convention.
2533         if (ref $page) {
2534                 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2535                 $params{list}=$page;
2536                 $page=$params{location}; # ugh!
2537         }
2539         my $sub=pagespec_translate($pagespec);
2540         error "syntax error in pagespec \"$pagespec\""
2541                 if ! defined $sub;
2542         my $sort=sortspec_translate($params{sort}, $params{reverse})
2543                 if defined $params{sort};
2545         my @candidates;
2546         if (exists $params{list}) {
2547                 @candidates=exists $params{filter}
2548                         ? grep { ! $params{filter}->($_) } @{$params{list}}
2549                         : @{$params{list}};
2550         }
2551         else {
2552                 @candidates=exists $params{filter}
2553                         ? grep { ! $params{filter}->($_) } keys %pagesources
2554                         : keys %pagesources;
2555         }
2556         
2557         # clear params, remainder is passed to pagespec
2558         $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2559         my $num=$params{num};
2560         delete @params{qw{num deptype reverse sort filter list}};
2561         
2562         # when only the top matches will be returned, it's efficient to
2563         # sort before matching to pagespec,
2564         if (defined $num && defined $sort) {
2565                 @candidates=IkiWiki::SortSpec::sort_pages(
2566                         $sort, @candidates);
2567         }
2568         
2569         my @matches;
2570         my $firstfail;
2571         my $count=0;
2572         my $accum=IkiWiki::SuccessReason->new();
2573         foreach my $p (@candidates) {
2574                 my $r=$sub->($p, %params, location => $page);
2575                 error(sprintf(gettext("cannot match pages: %s"), $r))
2576                         if $r->isa("IkiWiki::ErrorReason");
2577                 unless ($r || $r->influences_static) {
2578                         $r->remove_influence($p);
2579                 }
2580                 $accum |= $r;
2581                 if ($r) {
2582                         push @matches, $p;
2583                         last if defined $num && ++$count == $num;
2584                 }
2585         }
2587         # Add simple dependencies for accumulated influences.
2588         my $i=$accum->influences;
2589         foreach my $k (keys %$i) {
2590                 $depends_simple{$page}{lc $k} |= $i->{$k};
2591         }
2593         # when all matches will be returned, it's efficient to
2594         # sort after matching
2595         if (! defined $num && defined $sort) {
2596                 return IkiWiki::SortSpec::sort_pages(
2597                         $sort, @matches);
2598         }
2599         else {
2600                 return @matches;
2601         }
2604 sub pagespec_valid ($) {
2605         my $spec=shift;
2607         return defined pagespec_translate($spec);
2610 sub glob2re ($) {
2611         my $re=quotemeta(shift);
2612         $re=~s/\\\*/.*/g;
2613         $re=~s/\\\?/./g;
2614         return qr/^$re$/i;
2617 package IkiWiki::FailReason;
2619 use overload (
2620         '""'    => sub { $_[0][0] },
2621         '0+'    => sub { 0 },
2622         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2623         '&'     => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2624         '|'     => sub { $_[1]->merge_influences($_[0]); $_[1] },
2625         fallback => 1,
2626 );
2628 our @ISA = 'IkiWiki::SuccessReason';
2630 package IkiWiki::SuccessReason;
2632 # A blessed array-ref:
2634 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2635 # [1]{""}:
2636 #      - if absent or false, the influences of this evaluation are "static",
2637 #        see the influences_static method
2638 #      - if true, they are dynamic (not static)
2639 # [1]{any other key}:
2640 #      the dependency types of influences, as returned by the influences method
2642 use overload (
2643         # in string context, it's the human-readable reason
2644         '""'    => sub { $_[0][0] },
2645         # in boolean context, SuccessReason is 1 and FailReason is 0
2646         '0+'    => sub { 1 },
2647         # negating a result gives the opposite result with the same influences
2648         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
2649         # A & B = (A ? B : A) with the influences of both
2650         '&'     => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2651         # A | B = (A ? A : B) with the influences of both
2652         '|'     => sub { $_[0]->merge_influences($_[1]); $_[0] },
2653         fallback => 1,
2654 );
2656 # SuccessReason->new("human-readable reason", page => deptype, ...)
2658 sub new {
2659         my $class = shift;
2660         my $value = shift;
2661         return bless [$value, {@_}], $class;
2664 # influences(): return a reference to a copy of the hash
2665 # { page => dependency type } describing the pages that indirectly influenced
2666 # this result, but would not cause a dependency through ikiwiki's core
2667 # dependency logic.
2669 # See [[todo/dependency_types]] for extensive discussion of what this means.
2671 # influences(page => deptype, ...): remove all influences, replace them
2672 # with the arguments, and return a reference to a copy of the new influences.
2674 sub influences {
2675         my $this=shift;
2676         $this->[1]={@_} if @_;
2677         my %i=%{$this->[1]};
2678         delete $i{""};
2679         return \%i;
2682 # True if this result has the same influences whichever page it matches,
2683 # For instance, whether bar matches backlink(foo) is influenced only by
2684 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2685 # which does not mention bar anywhere.
2687 # False if this result would have different influences when matching
2688 # different pages. For instance, when testing whether link(foo) matches bar,
2689 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2690 # bar's links could change the outcome; so its influences are not the same
2691 # as when testing whether link(foo) matches baz.
2693 # Static influences are one of the things that make pagespec_match_list
2694 # more efficient than repeated calls to pagespec_match.
2696 sub influences_static {
2697         return ! $_[0][1]->{""};
2700 # Change the influences of $this to be the influences of "$this & $other"
2701 # or "$this | $other".
2703 # If both $this and $other are either successful or have influences,
2704 # or this is an "or" operation, the result has all the influences from
2705 # either of the arguments. It has dynamic influences if either argument
2706 # has dynamic influences.
2708 # If this is an "and" operation, and at least one argument is a
2709 # FailReason with no influences, the result has no influences, and they
2710 # are not dynamic. For instance, link(foo) matching bar is influenced
2711 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2712 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2713 # bar, because it would be false however often you edit bar.
2715 sub merge_influences {
2716         my $this=shift;
2717         my $other=shift;
2718         my $anded=shift;
2720         # This "if" is odd because it needs to avoid negating $this
2721         # or $other, which would alter the objects in-place. Be careful.
2722         if (! $anded || (($this || %{$this->[1]}) &&
2723                          ($other || %{$other->[1]}))) {
2724                 foreach my $influence (keys %{$other->[1]}) {
2725                         $this->[1]{$influence} |= $other->[1]{$influence};
2726                 }
2727         }
2728         else {
2729                 # influence blocker
2730                 $this->[1]={};
2731         }
2734 # Change $this so it is not considered to be influenced by $torm.
2736 sub remove_influence {
2737         my $this=shift;
2738         my $torm=shift;
2740         delete $this->[1]{$torm};
2743 package IkiWiki::ErrorReason;
2745 our @ISA = 'IkiWiki::FailReason';
2747 package IkiWiki::PageSpec;
2749 sub derel ($$) {
2750         my $path=shift;
2751         my $from=shift;
2753         if ($path =~ m!^\.(/|$)!) {
2754                 if ($1) {
2755                         $from=~s#/?[^/]+$## if defined $from;
2756                         $path=~s#^\./##;
2757                         $path="$from/$path" if defined $from && length $from;
2758                 }
2759                 else {
2760                         $path = $from;
2761                         $path = "" unless defined $path;
2762                 }
2763         }
2765         return $path;
2768 my %glob_cache;
2770 sub match_glob ($$;@) {
2771         my $page=shift;
2772         my $glob=shift;
2773         my %params=@_;
2774         
2775         $glob=derel($glob, $params{location});
2777         # Instead of converting the glob to a regex every time,
2778         # cache the compiled regex to save time.
2779         my $re=$glob_cache{$glob};
2780         unless (defined $re) {
2781                 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2782         }
2783         if ($page =~ $re) {
2784                 if (! IkiWiki::isinternal($page) || $params{internal}) {
2785                         return IkiWiki::SuccessReason->new("$glob matches $page");
2786                 }
2787                 else {
2788                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2789                 }
2790         }
2791         else {
2792                 return IkiWiki::FailReason->new("$glob does not match $page");
2793         }
2796 sub match_internal ($$;@) {
2797         return match_glob(shift, shift, @_, internal => 1)
2800 sub match_page ($$;@) {
2801         my $page=shift;
2802         my $match=match_glob($page, shift, @_);
2803         if ($match) {
2804                 my $source=exists $IkiWiki::pagesources{$page} ?
2805                         $IkiWiki::pagesources{$page} :
2806                         $IkiWiki::delpagesources{$page};
2807                 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2808                 if (! defined $type) {  
2809                         return IkiWiki::FailReason->new("$page is not a page");
2810                 }
2811         }
2812         return $match;
2815 sub match_link ($$;@) {
2816         my $page=shift;
2817         my $link=lc(shift);
2818         my %params=@_;
2820         $link=derel($link, $params{location});
2821         my $from=exists $params{location} ? $params{location} : '';
2822         my $linktype=$params{linktype};
2823         my $qualifier='';
2824         if (defined $linktype) {
2825                 $qualifier=" with type $linktype";
2826         }
2828         my $links = $IkiWiki::links{$page};
2829         return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2830                 unless $links && @{$links};
2831         my $bestlink = IkiWiki::bestlink($from, $link);
2832         foreach my $p (@{$links}) {
2833                 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2835                 if (length $bestlink) {
2836                         if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2837                                 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2838                         }
2839                 }
2840                 else {
2841                         if (match_glob($p, $link, %params)) {
2842                                 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2843                         }
2844                         my ($p_rel)=$p=~/^\/?(.*)/;
2845                         $link=~s/^\///;
2846                         if (match_glob($p_rel, $link, %params)) {
2847                                 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2848                         }
2849                 }
2850         }
2851         return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2854 sub match_backlink ($$;@) {
2855         my $page=shift;
2856         my $testpage=shift;
2857         my %params=@_;
2858         if ($testpage eq '.') {
2859                 $testpage = $params{'location'}
2860         }
2861         my $ret=match_link($testpage, $page, @_);
2862         $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2863         return $ret;
2866 sub match_created_before ($$;@) {
2867         my $page=shift;
2868         my $testpage=shift;
2869         my %params=@_;
2870         
2871         $testpage=derel($testpage, $params{location});
2873         if (exists $IkiWiki::pagectime{$testpage}) {
2874                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2875                         return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2876                 }
2877                 else {
2878                         return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2879                 }
2880         }
2881         else {
2882                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2883         }
2886 sub match_created_after ($$;@) {
2887         my $page=shift;
2888         my $testpage=shift;
2889         my %params=@_;
2890         
2891         $testpage=derel($testpage, $params{location});
2893         if (exists $IkiWiki::pagectime{$testpage}) {
2894                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2895                         return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2896                 }
2897                 else {
2898                         return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2899                 }
2900         }
2901         else {
2902                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2903         }
2906 sub match_creation_day ($$;@) {
2907         my $page=shift;
2908         my $d=shift;
2909         if ($d !~ /^\d+$/) {
2910                 return IkiWiki::ErrorReason->new("invalid day $d");
2911         }
2912         if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2913                 return IkiWiki::SuccessReason->new('creation_day matched');
2914         }
2915         else {
2916                 return IkiWiki::FailReason->new('creation_day did not match');
2917         }
2920 sub match_creation_month ($$;@) {
2921         my $page=shift;
2922         my $m=shift;
2923         if ($m !~ /^\d+$/) {
2924                 return IkiWiki::ErrorReason->new("invalid month $m");
2925         }
2926         if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2927                 return IkiWiki::SuccessReason->new('creation_month matched');
2928         }
2929         else {
2930                 return IkiWiki::FailReason->new('creation_month did not match');
2931         }
2934 sub match_creation_year ($$;@) {
2935         my $page=shift;
2936         my $y=shift;
2937         if ($y !~ /^\d+$/) {
2938                 return IkiWiki::ErrorReason->new("invalid year $y");
2939         }
2940         if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2941                 return IkiWiki::SuccessReason->new('creation_year matched');
2942         }
2943         else {
2944                 return IkiWiki::FailReason->new('creation_year did not match');
2945         }
2948 sub match_user ($$;@) {
2949         shift;
2950         my $user=shift;
2951         my %params=@_;
2952         
2953         if (! exists $params{user}) {
2954                 return IkiWiki::ErrorReason->new("no user specified");
2955         }
2957         my $regexp=IkiWiki::glob2re($user);
2958         
2959         if (defined $params{user} && $params{user}=~$regexp) {
2960                 return IkiWiki::SuccessReason->new("user is $user");
2961         }
2962         elsif (! defined $params{user}) {
2963                 return IkiWiki::FailReason->new("not logged in");
2964         }
2965         else {
2966                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2967         }
2970 sub match_admin ($$;@) {
2971         shift;
2972         shift;
2973         my %params=@_;
2974         
2975         if (! exists $params{user}) {
2976                 return IkiWiki::ErrorReason->new("no user specified");
2977         }
2979         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2980                 return IkiWiki::SuccessReason->new("user is an admin");
2981         }
2982         elsif (! defined $params{user}) {
2983                 return IkiWiki::FailReason->new("not logged in");
2984         }
2985         else {
2986                 return IkiWiki::FailReason->new("user is not an admin");
2987         }
2990 sub match_ip ($$;@) {
2991         shift;
2992         my $ip=shift;
2993         my %params=@_;
2994         
2995         if (! exists $params{ip}) {
2996                 return IkiWiki::ErrorReason->new("no IP specified");
2997         }
2998         
2999         my $regexp=IkiWiki::glob2re(lc $ip);
3001         if (defined $params{ip} && lc $params{ip}=~$regexp) {
3002                 return IkiWiki::SuccessReason->new("IP is $ip");
3003         }
3004         else {
3005                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
3006         }
3009 package IkiWiki::SortSpec;
3011 # This is in the SortSpec namespace so that the $a and $b that sort() uses
3012 # are easily available in this namespace, for cmp functions to use them.
3013 sub sort_pages {
3014         my $f=shift;
3015         sort $f @_
3018 sub cmp_title {
3019         IkiWiki::pagetitle(IkiWiki::basename($a))
3020         cmp
3021         IkiWiki::pagetitle(IkiWiki::basename($b))
3024 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
3025 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
3026 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }