]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki.pm
page.tmpl: tell mobile browsers we have a responsive layout, unless told not to
[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 => "use elements new in HTML5 like <section>?",
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         },
552         responsive_layout => {
553                 type => "boolean",
554                 default => 1,
555                 description => "theme has a responsive layout? (mobile-optimized)",
556                 safe => 1,
557                 rebuild => 1,
558         },
561 sub defaultconfig () {
562         my %s=getsetup();
563         my @ret;
564         foreach my $key (keys %s) {
565                 push @ret, $key, $s{$key}->{default};
566         }
567         return @ret;
570 # URL to top of wiki as a path starting with /, valid from any wiki page or
571 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
572 my $local_url;
573 # URL to CGI script, similar to $local_url
574 my $local_cgiurl;
576 sub checkconfig () {
577         # locale stuff; avoid LC_ALL since it overrides everything
578         if (defined $ENV{LC_ALL}) {
579                 $ENV{LANG} = $ENV{LC_ALL};
580                 delete $ENV{LC_ALL};
581         }
582         if (defined $config{locale}) {
583                 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
584                         $ENV{LANG}=$config{locale};
585                         define_gettext();
586                 }
587         }
588                 
589         if (! defined $config{wiki_file_regexp}) {
590                 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
591         }
593         if (ref $config{ENV} eq 'HASH') {
594                 foreach my $val (keys %{$config{ENV}}) {
595                         $ENV{$val}=$config{ENV}{$val};
596                 }
597         }
598         if (defined $config{timezone} && length $config{timezone}) {
599                 $ENV{TZ}=$config{timezone};
600         }
601         else {
602                 $config{timezone}=$ENV{TZ};
603         }
605         if ($config{w3mmode}) {
606                 eval q{use Cwd q{abs_path}};
607                 error($@) if $@;
608                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
609                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
610                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
611                         unless $config{cgiurl} =~ m!file:///!;
612                 $config{url}="file://".$config{destdir};
613         }
615         if ($config{cgi} && ! length $config{url}) {
616                 error(gettext("Must specify url to wiki with --url when using --cgi"));
617         }
619         if (defined $config{url} && length $config{url}) {
620                 eval q{use URI};
621                 my $baseurl = URI->new($config{url});
623                 $local_url = $baseurl->path . "/";
624                 $local_cgiurl = undef;
626                 if (length $config{cgiurl}) {
627                         my $cgiurl = URI->new($config{cgiurl});
629                         $local_cgiurl = $cgiurl->path;
631                         if ($cgiurl->scheme eq 'https' &&
632                                 $baseurl->scheme eq 'http') {
633                                 # We assume that the same content is available
634                                 # over both http and https, because if it
635                                 # wasn't, accessing the static content
636                                 # from the CGI would be mixed-content,
637                                 # which would be a security flaw.
639                                 if ($cgiurl->authority ne $baseurl->authority) {
640                                         # use protocol-relative URL for
641                                         # static content
642                                         $local_url = "$config{url}/";
643                                         $local_url =~ s{^http://}{//};
644                                 }
645                                 # else use host-relative URL for static content
647                                 # either way, CGI needs to be absolute
648                                 $local_cgiurl = $config{cgiurl};
649                         }
650                         elsif ($cgiurl->scheme ne $baseurl->scheme) {
651                                 # too far apart, fall back to absolute URLs
652                                 $local_url = "$config{url}/";
653                                 $local_cgiurl = $config{cgiurl};
654                         }
655                         elsif ($cgiurl->authority ne $baseurl->authority) {
656                                 # slightly too far apart, fall back to
657                                 # protocol-relative URLs
658                                 $local_url = "$config{url}/";
659                                 $local_url =~ s{^https?://}{//};
660                                 $local_cgiurl = $config{cgiurl};
661                                 $local_cgiurl =~ s{^https?://}{//};
662                         }
663                         # else keep host-relative URLs
664                 }
666                 $local_url =~ s{//$}{/};
667         }
668         else {
669                 $local_cgiurl = $config{cgiurl};
670         }
672         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
673                 unless exists $config{wikistatedir} && defined $config{wikistatedir};
675         if (defined $config{umask}) {
676                 my $u = possibly_foolish_untaint($config{umask});
678                 if ($u =~ m/^\d+$/) {
679                         umask($u);
680                 }
681                 elsif ($u eq 'private') {
682                         umask(077);
683                 }
684                 elsif ($u eq 'group') {
685                         umask(027);
686                 }
687                 elsif ($u eq 'public') {
688                         umask(022);
689                 }
690                 else {
691                         error(sprintf(gettext("unsupported umask setting %s"), $u));
692                 }
693         }
695         run_hooks(checkconfig => sub { shift->() });
697         return 1;
700 sub listplugins () {
701         my %ret;
703         foreach my $dir (@INC, $config{libdir}) {
704                 next unless defined $dir && length $dir;
705                 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
706                         my ($plugin)=$file=~/.*\/(.*)\.pm$/;
707                         $ret{$plugin}=1;
708                 }
709         }
710         foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
711                 next unless defined $dir && length $dir;
712                 foreach my $file (glob("$dir/plugins/*")) {
713                         $ret{basename($file)}=1 if -x $file;
714                 }
715         }
717         return keys %ret;
720 sub loadplugins () {
721         if (defined $config{libdir} && length $config{libdir}) {
722                 unshift @INC, possibly_foolish_untaint($config{libdir});
723         }
725         foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
726                 loadplugin($plugin);
727         }
728         
729         if ($config{rcs}) {
730                 if (exists $hooks{rcs}) {
731                         error(gettext("cannot use multiple rcs plugins"));
732                 }
733                 loadplugin($config{rcs});
734         }
735         if (! exists $hooks{rcs}) {
736                 loadplugin("norcs");
737         }
739         run_hooks(getopt => sub { shift->() });
740         if (grep /^-/, @ARGV) {
741                 print STDERR "Unknown option (or missing parameter): $_\n"
742                         foreach grep /^-/, @ARGV;
743                 usage();
744         }
746         return 1;
749 sub loadplugin ($;$) {
750         my $plugin=shift;
751         my $force=shift;
753         return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
755         foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
756                          "$installdir/lib/ikiwiki") {
757                 if (defined $dir && -x "$dir/plugins/$plugin") {
758                         eval { require IkiWiki::Plugin::external };
759                         if ($@) {
760                                 my $reason=$@;
761                                 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
762                         }
763                         import IkiWiki::Plugin::external "$dir/plugins/$plugin";
764                         $loaded_plugins{$plugin}=1;
765                         return 1;
766                 }
767         }
769         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
770         eval qq{use $mod};
771         if ($@) {
772                 error("Failed to load plugin $mod: $@");
773         }
774         $loaded_plugins{$plugin}=1;
775         return 1;
778 sub error ($;$) {
779         my $message=shift;
780         my $cleaner=shift;
781         log_message('err' => $message) if $config{syslog};
782         if (defined $cleaner) {
783                 $cleaner->();
784         }
785         die $message."\n";
788 sub debug ($) {
789         return unless $config{verbose};
790         return log_message(debug => @_);
793 my $log_open=0;
794 my $log_failed=0;
795 sub log_message ($$) {
796         my $type=shift;
798         if ($config{syslog}) {
799                 require Sys::Syslog;
800                 if (! $log_open) {
801                         Sys::Syslog::setlogsock('unix');
802                         Sys::Syslog::openlog('ikiwiki', '', 'user');
803                         $log_open=1;
804                 }
805                 eval {
806                         # keep a copy to avoid editing the original config repeatedly
807                         my $wikiname = $config{wikiname};
808                         utf8::encode($wikiname);
809                         Sys::Syslog::syslog($type, "[$wikiname] %s", join(" ", @_));
810                 };
811                 if ($@) {
812                     print STDERR "failed to syslog: $@" unless $log_failed;
813                     $log_failed=1;
814                     print STDERR "@_\n";
815                 }
816                 return $@;
817         }
818         elsif (! $config{cgi}) {
819                 return print "@_\n";
820         }
821         else {
822                 return print STDERR "@_\n";
823         }
826 sub possibly_foolish_untaint ($) {
827         my $tainted=shift;
828         my ($untainted)=$tainted=~/(.*)/s;
829         return $untainted;
832 sub basename ($) {
833         my $file=shift;
835         $file=~s!.*/+!!;
836         return $file;
839 sub dirname ($) {
840         my $file=shift;
842         $file=~s!/*[^/]+$!!;
843         return $file;
846 sub isinternal ($) {
847         my $page=shift;
848         return exists $pagesources{$page} &&
849                 $pagesources{$page} =~ /\._([^.]+)$/;
852 sub pagetype ($) {
853         my $file=shift;
854         
855         if ($file =~ /\.([^.]+)$/) {
856                 return $1 if exists $hooks{htmlize}{$1};
857         }
858         my $base=basename($file);
859         if (exists $hooks{htmlize}{$base} &&
860             $hooks{htmlize}{$base}{noextension}) {
861                 return $base;
862         }
863         return;
866 my %pagename_cache;
868 sub pagename ($) {
869         my $file=shift;
871         if (exists $pagename_cache{$file}) {
872                 return $pagename_cache{$file};
873         }
875         my $type=pagetype($file);
876         my $page=$file;
877         $page=~s/\Q.$type\E*$//
878                 if defined $type && !$hooks{htmlize}{$type}{keepextension}
879                         && !$hooks{htmlize}{$type}{noextension};
880         if ($config{indexpages} && $page=~/(.*)\/index$/) {
881                 $page=$1;
882         }
884         $pagename_cache{$file} = $page;
885         return $page;
888 sub newpagefile ($$) {
889         my $page=shift;
890         my $type=shift;
892         if (! $config{indexpages} || $page eq 'index') {
893                 return $page.".".$type;
894         }
895         else {
896                 return $page."/index.".$type;
897         }
900 sub targetpage ($$;$) {
901         my $page=shift;
902         my $ext=shift;
903         my $filename=shift;
904         
905         if (defined $filename) {
906                 return $page."/".$filename.".".$ext;
907         }
908         elsif (! $config{usedirs} || $page eq 'index') {
909                 return $page.".".$ext;
910         }
911         else {
912                 return $page."/index.".$ext;
913         }
916 sub htmlpage ($) {
917         my $page=shift;
918         
919         return targetpage($page, $config{htmlext});
922 sub srcfile_stat {
923         my $file=shift;
924         my $nothrow=shift;
926         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
927         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
928                 return "$dir/$file", stat(_) if -e "$dir/$file";
929         }
930         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
931         return;
934 sub srcfile ($;$) {
935         return (srcfile_stat(@_))[0];
938 sub add_literal_underlay ($) {
939         my $dir=shift;
941         if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
942                 unshift @{$config{underlaydirs}}, $dir;
943         }
946 sub add_underlay ($) {
947         my $dir = shift;
949         if ($dir !~ /^\//) {
950                 $dir="$config{underlaydirbase}/$dir";
951         }
953         add_literal_underlay($dir);
954         # why does it return 1? we just don't know
955         return 1;
958 sub readfile ($;$$) {
959         my $file=shift;
960         my $binary=shift;
961         my $wantfd=shift;
963         if (-l $file) {
964                 error("cannot read a symlink ($file)");
965         }
966         
967         local $/=undef;
968         open (my $in, "<", $file) || error("failed to read $file: $!");
969         binmode($in) if ($binary);
970         return \*$in if $wantfd;
971         my $ret=<$in>;
972         # check for invalid utf-8, and toss it back to avoid crashes
973         if (! utf8::valid($ret)) {
974                 $ret=encode_utf8($ret);
975         }
976         close $in || error("failed to read $file: $!");
977         return $ret;
980 sub prep_writefile ($$) {
981         my $file=shift;
982         my $destdir=shift;
983         
984         my $test=$file;
985         while (length $test) {
986                 if (-l "$destdir/$test") {
987                         error("cannot write to a symlink ($test)");
988                 }
989                 if (-f _ && $test ne $file) {
990                         # Remove conflicting file.
991                         foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
992                                 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
993                                         if ($f eq $test) {
994                                                 unlink("$destdir/$test");
995                                                 last;
996                                         }
997                                 }
998                         }
999                 }
1000                 $test=dirname($test);
1001         }
1003         my $dir=dirname("$destdir/$file");
1004         if (! -d $dir) {
1005                 my $d="";
1006                 foreach my $s (split(m!/+!, $dir)) {
1007                         $d.="$s/";
1008                         if (! -d $d) {
1009                                 mkdir($d) || error("failed to create directory $d: $!");
1010                         }
1011                 }
1012         }
1014         return 1;
1017 sub writefile ($$$;$$) {
1018         my $file=shift; # can include subdirs
1019         my $destdir=shift; # directory to put file in
1020         my $content=shift;
1021         my $binary=shift;
1022         my $writer=shift;
1023         
1024         prep_writefile($file, $destdir);
1025         
1026         my $newfile="$destdir/$file.ikiwiki-new";
1027         if (-l $newfile) {
1028                 error("cannot write to a symlink ($newfile)");
1029         }
1030         
1031         my $cleanup = sub { unlink($newfile) };
1032         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
1033         binmode($out) if ($binary);
1034         if ($writer) {
1035                 $writer->(\*$out, $cleanup);
1036         }
1037         else {
1038                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
1039         }
1040         close $out || error("failed saving $newfile: $!", $cleanup);
1041         rename($newfile, "$destdir/$file") || 
1042                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1044         return 1;
1047 my %cleared;
1048 sub will_render ($$;$) {
1049         my $page=shift;
1050         my $dest=shift;
1051         my $clear=shift;
1053         # Important security check for independently created files.
1054         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1055             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1056                 my $from_other_page=0;
1057                 # Expensive, but rarely runs.
1058                 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1059                         if (grep {
1060                                 $_ eq $dest ||
1061                                 dirname($_) eq $dest
1062                             } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1063                                 $from_other_page=1;
1064                                 last;
1065                         }
1066                 }
1068                 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1069                         unless $from_other_page;
1070         }
1072         # If $dest exists as a directory, remove conflicting files in it
1073         # rendered from other pages.
1074         if (-d _) {
1075                 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1076                         foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1077                                 if (dirname($f) eq $dest) {
1078                                         unlink("$config{destdir}/$f");
1079                                         rmdir(dirname("$config{destdir}/$f"));
1080                                 }
1081                         }
1082                 }
1083         }
1085         if (! $clear || $cleared{$page}) {
1086                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1087         }
1088         else {
1089                 foreach my $old (@{$renderedfiles{$page}}) {
1090                         delete $destsources{$old};
1091                 }
1092                 $renderedfiles{$page}=[$dest];
1093                 $cleared{$page}=1;
1094         }
1095         $destsources{$dest}=$page;
1097         return 1;
1100 sub bestlink ($$) {
1101         my $page=shift;
1102         my $link=shift;
1103         
1104         my $cwd=$page;
1105         if ($link=~s/^\/+//) {
1106                 # absolute links
1107                 $cwd="";
1108         }
1109         $link=~s/\/$//;
1111         do {
1112                 my $l=$cwd;
1113                 $l.="/" if length $l;
1114                 $l.=$link;
1116                 if (exists $pagesources{$l}) {
1117                         return $l;
1118                 }
1119                 elsif (exists $pagecase{lc $l}) {
1120                         return $pagecase{lc $l};
1121                 }
1122         } while $cwd=~s{/?[^/]+$}{};
1124         if (length $config{userdir}) {
1125                 my $l = "$config{userdir}/".lc($link);
1126                 if (exists $pagesources{$l}) {
1127                         return $l;
1128                 }
1129                 elsif (exists $pagecase{lc $l}) {
1130                         return $pagecase{lc $l};
1131                 }
1132         }
1134         #print STDERR "warning: page $page, broken link: $link\n";
1135         return "";
1138 sub isinlinableimage ($) {
1139         my $file=shift;
1140         
1141         return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1144 sub pagetitle ($;$) {
1145         my $page=shift;
1146         my $unescaped=shift;
1148         if ($unescaped) {
1149                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1150         }
1151         else {
1152                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1153         }
1155         return $page;
1158 sub titlepage ($) {
1159         my $title=shift;
1160         # support use w/o %config set
1161         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1162         $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1163         return $title;
1166 sub linkpage ($) {
1167         my $link=shift;
1168         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1169         $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1170         return $link;
1173 sub cgiurl (@) {
1174         my %params=@_;
1176         my $cgiurl=$local_cgiurl;
1178         if (exists $params{cgiurl}) {
1179                 $cgiurl=$params{cgiurl};
1180                 delete $params{cgiurl};
1181         }
1183         unless (%params) {
1184                 return $cgiurl;
1185         }
1187         return $cgiurl."?".
1188                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1191 sub cgiurl_abs (@) {
1192         eval q{use URI};
1193         URI->new_abs(cgiurl(@_), $config{cgiurl});
1196 sub baseurl (;$) {
1197         my $page=shift;
1199         return $local_url if ! defined $page;
1200         
1201         $page=htmlpage($page);
1202         $page=~s/[^\/]+$//;
1203         $page=~s/[^\/]+\//..\//g;
1204         return $page;
1207 sub urlabs ($$) {
1208         my $url=shift;
1209         my $urlbase=shift;
1211         return $url unless defined $urlbase && length $urlbase;
1213         eval q{use URI};
1214         URI->new_abs($url, $urlbase)->as_string;
1217 sub abs2rel ($$) {
1218         # Work around very innefficient behavior in File::Spec if abs2rel
1219         # is passed two relative paths. It's much faster if paths are
1220         # absolute! (Debian bug #376658; fixed in debian unstable now)
1221         my $path="/".shift;
1222         my $base="/".shift;
1224         require File::Spec;
1225         my $ret=File::Spec->abs2rel($path, $base);
1226         $ret=~s/^// if defined $ret;
1227         return $ret;
1230 sub displaytime ($;$$) {
1231         # Plugins can override this function to mark up the time to
1232         # display.
1233         my $time=formattime($_[0], $_[1]);
1234         if ($config{html5}) {
1235                 return '<time datetime="'.date_3339($_[0]).'"'.
1236                         ($_[2] ? ' pubdate="pubdate"' : '').
1237                         '>'.$time.'</time>';
1238         }
1239         else {
1240                 return '<span class="date">'.$time.'</span>';
1241         }
1244 sub formattime ($;$) {
1245         # Plugins can override this function to format the time.
1246         my $time=shift;
1247         my $format=shift;
1248         if (! defined $format) {
1249                 $format=$config{timeformat};
1250         }
1252         return strftime_utf8($format, localtime($time));
1255 my $strftime_encoding;
1256 sub strftime_utf8 {
1257         # strftime doesn't know about encodings, so make sure
1258         # its output is properly treated as utf8.
1259         # Note that this does not handle utf-8 in the format string.
1260         ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1261                 unless defined $strftime_encoding;
1262         $strftime_encoding
1263                 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1264                 : POSIX::strftime(@_);
1267 sub date_3339 ($) {
1268         my $time=shift;
1270         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1271         POSIX::setlocale(&POSIX::LC_TIME, "C");
1272         my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1273         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1274         return $ret;
1277 sub beautify_urlpath ($) {
1278         my $url=shift;
1280         # Ensure url is not an empty link, and if necessary,
1281         # add ./ to avoid colon confusion.
1282         if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1283                 $url="./$url";
1284         }
1286         if ($config{usedirs}) {
1287                 $url =~ s!/index.$config{htmlext}$!/!;
1288         }
1290         return $url;
1293 sub urlto ($;$$) {
1294         my $to=shift;
1295         my $from=shift;
1296         my $absolute=shift;
1297         
1298         if (! length $to) {
1299                 $to = 'index';
1300         }
1302         if (! $destsources{$to}) {
1303                 $to=htmlpage($to);
1304         }
1306         if ($absolute) {
1307                 return $config{url}.beautify_urlpath("/".$to);
1308         }
1310         if (! defined $from) {
1311                 my $u = $local_url || '';
1312                 $u =~ s{/$}{};
1313                 return $u.beautify_urlpath("/".$to);
1314         }
1316         my $link = abs2rel($to, dirname(htmlpage($from)));
1318         return beautify_urlpath($link);
1321 sub isselflink ($$) {
1322         # Plugins can override this function to support special types
1323         # of selflinks.
1324         my $page=shift;
1325         my $link=shift;
1327         return $page eq $link;
1330 sub htmllink ($$$;@) {
1331         my $lpage=shift; # the page doing the linking
1332         my $page=shift; # the page that will contain the link (different for inline)
1333         my $link=shift;
1334         my %opts=@_;
1336         $link=~s/\/$//;
1338         my $bestlink;
1339         if (! $opts{forcesubpage}) {
1340                 $bestlink=bestlink($lpage, $link);
1341         }
1342         else {
1343                 $bestlink="$lpage/".lc($link);
1344         }
1346         my $linktext;
1347         if (defined $opts{linktext}) {
1348                 $linktext=$opts{linktext};
1349         }
1350         else {
1351                 $linktext=pagetitle(basename($link));
1352         }
1353         
1354         return "<span class=\"selflink\">$linktext</span>"
1355                 if length $bestlink && isselflink($page, $bestlink) &&
1356                    ! defined $opts{anchor};
1357         
1358         if (! $destsources{$bestlink}) {
1359                 $bestlink=htmlpage($bestlink);
1361                 if (! $destsources{$bestlink}) {
1362                         my $cgilink = "";
1363                         if (length $config{cgiurl}) {
1364                                 $cgilink = "<a href=\"".
1365                                         cgiurl(
1366                                                 do => "create",
1367                                                 page => $link,
1368                                                 from => $lpage
1369                                         )."\" rel=\"nofollow\">?</a>";
1370                         }
1371                         return "<span class=\"createlink\">$cgilink$linktext</span>"
1372                 }
1373         }
1374         
1375         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1376         $bestlink=beautify_urlpath($bestlink);
1377         
1378         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1379                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1380         }
1382         if (defined $opts{anchor}) {
1383                 $bestlink.="#".$opts{anchor};
1384         }
1386         my @attrs;
1387         foreach my $attr (qw{rel class title}) {
1388                 if (defined $opts{$attr}) {
1389                         push @attrs, " $attr=\"$opts{$attr}\"";
1390                 }
1391         }
1393         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1396 sub userpage ($) {
1397         my $user=shift;
1398         return length $config{userdir} ? "$config{userdir}/$user" : $user;
1401 sub openiduser ($) {
1402         my $user=shift;
1404         if (defined $user && $user =~ m!^https?://! &&
1405             eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1406                 my $display;
1408                 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1409                         $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1410                 }
1411                 else {
1412                         # backcompat with old version
1413                         my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1414                         $display=$oid->display;
1415                 }
1417                 # Convert "user.somehost.com" to "user [somehost.com]"
1418                 # (also "user.somehost.co.uk")
1419                 if ($display !~ /\[/) {
1420                         $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1421                 }
1422                 # Convert "http://somehost.com/user" to "user [somehost.com]".
1423                 # (also "https://somehost.com/user/")
1424                 if ($display !~ /\[/) {
1425                         $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1426                 }
1427                 $display=~s!^https?://!!; # make sure this is removed
1428                 eval q{use CGI 'escapeHTML'};
1429                 error($@) if $@;
1430                 return escapeHTML($display);
1431         }
1432         return;
1435 sub htmlize ($$$$) {
1436         my $page=shift;
1437         my $destpage=shift;
1438         my $type=shift;
1439         my $content=shift;
1440         
1441         my $oneline = $content !~ /\n/;
1442         
1443         if (exists $hooks{htmlize}{$type}) {
1444                 $content=$hooks{htmlize}{$type}{call}->(
1445                         page => $page,
1446                         content => $content,
1447                 );
1448         }
1449         else {
1450                 error("htmlization of $type not supported");
1451         }
1453         run_hooks(sanitize => sub {
1454                 $content=shift->(
1455                         page => $page,
1456                         destpage => $destpage,
1457                         content => $content,
1458                 );
1459         });
1460         
1461         if ($oneline) {
1462                 # hack to get rid of enclosing junk added by markdown
1463                 # and other htmlizers/sanitizers
1464                 $content=~s/^<p>//i;
1465                 $content=~s/<\/p>\n*$//i;
1466         }
1468         return $content;
1471 sub linkify ($$$) {
1472         my $page=shift;
1473         my $destpage=shift;
1474         my $content=shift;
1476         run_hooks(linkify => sub {
1477                 $content=shift->(
1478                         page => $page,
1479                         destpage => $destpage,
1480                         content => $content,
1481                 );
1482         });
1483         
1484         return $content;
1487 our %preprocessing;
1488 our $preprocess_preview=0;
1489 sub preprocess ($$$;$$) {
1490         my $page=shift; # the page the data comes from
1491         my $destpage=shift; # the page the data will appear in (different for inline)
1492         my $content=shift;
1493         my $scan=shift;
1494         my $preview=shift;
1496         # Using local because it needs to be set within any nested calls
1497         # of this function.
1498         local $preprocess_preview=$preview if defined $preview;
1500         my $handle=sub {
1501                 my $escape=shift;
1502                 my $prefix=shift;
1503                 my $command=shift;
1504                 my $params=shift;
1505                 $params="" if ! defined $params;
1507                 if (length $escape) {
1508                         return "[[$prefix$command $params]]";
1509                 }
1510                 elsif (exists $hooks{preprocess}{$command}) {
1511                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1512                         # Note: preserve order of params, some plugins may
1513                         # consider it significant.
1514                         my @params;
1515                         while ($params =~ m{
1516                                 (?:([-.\w]+)=)?         # 1: named parameter key?
1517                                 (?:
1518                                         """(.*?)"""     # 2: triple-quoted value
1519                                 |
1520                                         "([^"]*?)"      # 3: single-quoted value
1521                                 |
1522                                         '''(.*?)'''     # 4: triple-single-quote
1523                                 |
1524                                         <<([a-zA-Z]+)\n # 5: heredoc start
1525                                         (.*?)\n\5       # 6: heredoc value
1526                                 |
1527                                         (\S+)           # 7: unquoted value
1528                                 )
1529                                 (?:\s+|$)               # delimiter to next param
1530                         }msgx) {
1531                                 my $key=$1;
1532                                 my $val;
1533                                 if (defined $2) {
1534                                         $val=$2;
1535                                         $val=~s/\r\n/\n/mg;
1536                                         $val=~s/^\n+//g;
1537                                         $val=~s/\n+$//g;
1538                                 }
1539                                 elsif (defined $3) {
1540                                         $val=$3;
1541                                 }
1542                                 elsif (defined $4) {
1543                                         $val=$4;
1544                                 }
1545                                 elsif (defined $7) {
1546                                         $val=$7;
1547                                 }
1548                                 elsif (defined $6) {
1549                                         $val=$6;
1550                                 }
1552                                 if (defined $key) {
1553                                         push @params, $key, $val;
1554                                 }
1555                                 else {
1556                                         push @params, $val, '';
1557                                 }
1558                         }
1559                         if ($preprocessing{$page}++ > 8) {
1560                                 # Avoid loops of preprocessed pages preprocessing
1561                                 # other pages that preprocess them, etc.
1562                                 return "[[!$command <span class=\"error\">".
1563                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1564                                                 $page, $preprocessing{$page}).
1565                                         "</span>]]";
1566                         }
1567                         my $ret;
1568                         if (! $scan) {
1569                                 $ret=eval {
1570                                         $hooks{preprocess}{$command}{call}->(
1571                                                 @params,
1572                                                 page => $page,
1573                                                 destpage => $destpage,
1574                                                 preview => $preprocess_preview,
1575                                         );
1576                                 };
1577                                 if ($@) {
1578                                         my $error=$@;
1579                                         chomp $error;
1580                                         $ret="[[!$command <span class=\"error\">".
1581                                                 gettext("Error").": $error"."</span>]]";
1582                                 }
1583                         }
1584                         else {
1585                                 # use void context during scan pass
1586                                 eval {
1587                                         $hooks{preprocess}{$command}{call}->(
1588                                                 @params,
1589                                                 page => $page,
1590                                                 destpage => $destpage,
1591                                                 preview => $preprocess_preview,
1592                                         );
1593                                 };
1594                                 $ret="";
1595                         }
1596                         $preprocessing{$page}--;
1597                         return $ret;
1598                 }
1599                 else {
1600                         return "[[$prefix$command $params]]";
1601                 }
1602         };
1603         
1604         my $regex;
1605         if ($config{prefix_directives}) {
1606                 $regex = qr{
1607                         (\\?)           # 1: escape?
1608                         \[\[(!)         # directive open; 2: prefix
1609                         ([-\w]+)        # 3: command
1610                         (               # 4: the parameters..
1611                                 \s+     # Must have space if parameters present
1612                                 (?:
1613                                         (?:[-.\w]+=)?           # named parameter key?
1614                                         (?:
1615                                                 """.*?"""       # triple-quoted value
1616                                                 |
1617                                                 "[^"]*?"        # single-quoted value
1618                                                 |
1619                                                 '''.*?'''       # triple-single-quote
1620                                                 |
1621                                                 <<([a-zA-Z]+)\n # 5: heredoc start
1622                                                 (?:.*?)\n\5     # heredoc value
1623                                                 |
1624                                                 [^"\s\]]+       # unquoted value
1625                                         )
1626                                         \s*                     # whitespace or end
1627                                                                 # of directive
1628                                 )
1629                         *)?             # 0 or more parameters
1630                         \]\]            # directive closed
1631                 }sx;
1632         }
1633         else {
1634                 $regex = qr{
1635                         (\\?)           # 1: escape?
1636                         \[\[(!?)        # directive open; 2: optional prefix
1637                         ([-\w]+)        # 3: command
1638                         \s+
1639                         (               # 4: the parameters..
1640                                 (?:
1641                                         (?:[-.\w]+=)?           # named parameter key?
1642                                         (?:
1643                                                 """.*?"""       # triple-quoted value
1644                                                 |
1645                                                 "[^"]*?"        # single-quoted value
1646                                                 |
1647                                                 '''.*?'''       # triple-single-quote
1648                                                 |
1649                                                 <<([a-zA-Z]+)\n # 5: heredoc start
1650                                                 (?:.*?)\n\5     # heredoc value
1651                                                 |
1652                                                 [^"\s\]]+       # unquoted value
1653                                         )
1654                                         \s*                     # whitespace or end
1655                                                                 # of directive
1656                                 )
1657                         *)              # 0 or more parameters
1658                         \]\]            # directive closed
1659                 }sx;
1660         }
1662         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1663         return $content;
1666 sub filter ($$$) {
1667         my $page=shift;
1668         my $destpage=shift;
1669         my $content=shift;
1671         run_hooks(filter => sub {
1672                 $content=shift->(page => $page, destpage => $destpage, 
1673                         content => $content);
1674         });
1676         return $content;
1679 sub check_canedit ($$$;$) {
1680         my $page=shift;
1681         my $q=shift;
1682         my $session=shift;
1683         my $nonfatal=shift;
1684         
1685         my $canedit;
1686         run_hooks(canedit => sub {
1687                 return if defined $canedit;
1688                 my $ret=shift->($page, $q, $session);
1689                 if (defined $ret) {
1690                         if ($ret eq "") {
1691                                 $canedit=1;
1692                         }
1693                         elsif (ref $ret eq 'CODE') {
1694                                 $ret->() unless $nonfatal;
1695                                 $canedit=0;
1696                         }
1697                         elsif (defined $ret) {
1698                                 error($ret) unless $nonfatal;
1699                                 $canedit=0;
1700                         }
1701                 }
1702         });
1703         return defined $canedit ? $canedit : 1;
1706 sub check_content (@) {
1707         my %params=@_;
1708         
1709         return 1 if ! exists $hooks{checkcontent}; # optimisation
1711         if (exists $pagesources{$params{page}}) {
1712                 my @diff;
1713                 my %old=map { $_ => 1 }
1714                         split("\n", readfile(srcfile($pagesources{$params{page}})));
1715                 foreach my $line (split("\n", $params{content})) {
1716                         push @diff, $line if ! exists $old{$line};
1717                 }
1718                 $params{diff}=join("\n", @diff);
1719         }
1721         my $ok;
1722         run_hooks(checkcontent => sub {
1723                 return if defined $ok;
1724                 my $ret=shift->(%params);
1725                 if (defined $ret) {
1726                         if ($ret eq "") {
1727                                 $ok=1;
1728                         }
1729                         elsif (ref $ret eq 'CODE') {
1730                                 $ret->() unless $params{nonfatal};
1731                                 $ok=0;
1732                         }
1733                         elsif (defined $ret) {
1734                                 error($ret) unless $params{nonfatal};
1735                                 $ok=0;
1736                         }
1737                 }
1739         });
1740         return defined $ok ? $ok : 1;
1743 sub check_canchange (@) {
1744         my %params = @_;
1745         my $cgi = $params{cgi};
1746         my $session = $params{session};
1747         my @changes = @{$params{changes}};
1749         my %newfiles;
1750         foreach my $change (@changes) {
1751                 # This untaint is safe because we check file_pruned and
1752                 # wiki_file_regexp.
1753                 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1754                 $file=possibly_foolish_untaint($file);
1755                 if (! defined $file || ! length $file ||
1756                     file_pruned($file)) {
1757                         error(gettext("bad file name %s"), $file);
1758                 }
1760                 my $type=pagetype($file);
1761                 my $page=pagename($file) if defined $type;
1763                 if ($change->{action} eq 'add') {
1764                         $newfiles{$file}=1;
1765                 }
1767                 if ($change->{action} eq 'change' ||
1768                     $change->{action} eq 'add') {
1769                         if (defined $page) {
1770                                 check_canedit($page, $cgi, $session);
1771                                 next;
1772                         }
1773                         else {
1774                                 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1775                                         IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1776                                         check_canedit($file, $cgi, $session);
1777                                         next;
1778                                 }
1779                         }
1780                 }
1781                 elsif ($change->{action} eq 'remove') {
1782                         # check_canremove tests to see if the file is present
1783                         # on disk. This will fail when a single commit adds a
1784                         # file and then removes it again. Avoid the problem
1785                         # by not testing the removal in such pairs of changes.
1786                         # (The add is still tested, just to make sure that
1787                         # no data is added to the repo that a web edit
1788                         # could not add.)
1789                         next if $newfiles{$file};
1791                         if (IkiWiki::Plugin::remove->can("check_canremove")) {
1792                                 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1793                                 check_canedit(defined $page ? $page : $file, $cgi, $session);
1794                                 next;
1795                         }
1796                 }
1797                 else {
1798                         error "unknown action ".$change->{action};
1799                 }
1801                 error sprintf(gettext("you are not allowed to change %s"), $file);
1802         }
1806 my $wikilock;
1808 sub lockwiki () {
1809         # Take an exclusive lock on the wiki to prevent multiple concurrent
1810         # run issues. The lock will be dropped on program exit.
1811         if (! -d $config{wikistatedir}) {
1812                 mkdir($config{wikistatedir});
1813         }
1814         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1815                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1816         if (! flock($wikilock, 2)) { # LOCK_EX
1817                 error("failed to get lock");
1818         }
1819         return 1;
1822 sub unlockwiki () {
1823         POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1824         return close($wikilock) if $wikilock;
1825         return;
1828 my $commitlock;
1830 sub commit_hook_enabled () {
1831         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1832                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1833         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1834                 close($commitlock) || error("failed closing commitlock: $!");
1835                 return 0;
1836         }
1837         close($commitlock) || error("failed closing commitlock: $!");
1838         return 1;
1841 sub disable_commit_hook () {
1842         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1843                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1844         if (! flock($commitlock, 2)) { # LOCK_EX
1845                 error("failed to get commit lock");
1846         }
1847         return 1;
1850 sub enable_commit_hook () {
1851         return close($commitlock) if $commitlock;
1852         return;
1855 sub loadindex () {
1856         %oldrenderedfiles=%pagectime=();
1857         my $rebuild=$config{rebuild};
1858         if (! $rebuild) {
1859                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1860                 %destsources=%renderedfiles=%pagecase=%pagestate=
1861                 %depends_simple=%typedlinks=%oldtypedlinks=();
1862         }
1863         my $in;
1864         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1865                 if (-e "$config{wikistatedir}/index") {
1866                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1867                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1868                 }
1869                 else {
1870                         # gettime on first build
1871                         $config{gettime}=1 unless defined $config{gettime};
1872                         return;
1873                 }
1874         }
1876         my $index=Storable::fd_retrieve($in);
1877         if (! defined $index) {
1878                 return 0;
1879         }
1881         my $pages;
1882         if (exists $index->{version} && ! ref $index->{version}) {
1883                 $pages=$index->{page};
1884                 %wikistate=%{$index->{state}};
1885                 # Handle plugins that got disabled by loading a new setup.
1886                 if (exists $config{setupfile}) {
1887                         require IkiWiki::Setup;
1888                         IkiWiki::Setup::disabled_plugins(
1889                                 grep { ! $loaded_plugins{$_} } keys %wikistate);
1890                 }
1891         }
1892         else {
1893                 $pages=$index;
1894                 %wikistate=();
1895         }
1897         foreach my $src (keys %$pages) {
1898                 my $d=$pages->{$src};
1899                 my $page;
1900                 if (exists $d->{page} && ! $rebuild) {
1901                         $page=$d->{page};
1902                 }
1903                 else {
1904                         $page=pagename($src);
1905                 }
1906                 $pagectime{$page}=$d->{ctime};
1907                 $pagesources{$page}=$src;
1908                 if (! $rebuild) {
1909                         $pagemtime{$page}=$d->{mtime};
1910                         $renderedfiles{$page}=$d->{dest};
1911                         if (exists $d->{links} && ref $d->{links}) {
1912                                 $links{$page}=$d->{links};
1913                                 $oldlinks{$page}=[@{$d->{links}}];
1914                         }
1915                         if (ref $d->{depends_simple} eq 'ARRAY') {
1916                                 # old format
1917                                 $depends_simple{$page}={
1918                                         map { $_ => 1 } @{$d->{depends_simple}}
1919                                 };
1920                         }
1921                         elsif (exists $d->{depends_simple}) {
1922                                 $depends_simple{$page}=$d->{depends_simple};
1923                         }
1924                         if (exists $d->{dependslist}) {
1925                                 # old format
1926                                 $depends{$page}={
1927                                         map { $_ => $DEPEND_CONTENT }
1928                                                 @{$d->{dependslist}}
1929                                 };
1930                         }
1931                         elsif (exists $d->{depends} && ! ref $d->{depends}) {
1932                                 # old format
1933                                 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1934                         }
1935                         elsif (exists $d->{depends}) {
1936                                 $depends{$page}=$d->{depends};
1937                         }
1938                         if (exists $d->{state}) {
1939                                 $pagestate{$page}=$d->{state};
1940                         }
1941                         if (exists $d->{typedlinks}) {
1942                                 $typedlinks{$page}=$d->{typedlinks};
1944                                 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1945                                         next unless %$links;
1946                                         $oldtypedlinks{$page}{$type} = {%$links};
1947                                 }
1948                         }
1949                 }
1950                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1951         }
1952         foreach my $page (keys %pagesources) {
1953                 $pagecase{lc $page}=$page;
1954         }
1955         foreach my $page (keys %renderedfiles) {
1956                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1957         }
1958         $lastrev=$index->{lastrev};
1959         @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
1960         return close($in);
1963 sub saveindex () {
1964         run_hooks(savestate => sub { shift->() });
1966         my @plugins=keys %loaded_plugins;
1968         if (! -d $config{wikistatedir}) {
1969                 mkdir($config{wikistatedir});
1970         }
1971         my $newfile="$config{wikistatedir}/indexdb.new";
1972         my $cleanup = sub { unlink($newfile) };
1973         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1975         my %index;
1976         foreach my $page (keys %pagemtime) {
1977                 next unless $pagemtime{$page};
1978                 my $src=$pagesources{$page};
1980                 $index{page}{$src}={
1981                         page => $page,
1982                         ctime => $pagectime{$page},
1983                         mtime => $pagemtime{$page},
1984                         dest => $renderedfiles{$page},
1985                         links => $links{$page},
1986                 };
1988                 if (exists $depends{$page}) {
1989                         $index{page}{$src}{depends} = $depends{$page};
1990                 }
1992                 if (exists $depends_simple{$page}) {
1993                         $index{page}{$src}{depends_simple} = $depends_simple{$page};
1994                 }
1996                 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1997                         $index{page}{$src}{typedlinks} = $typedlinks{$page};
1998                 }
2000                 if (exists $pagestate{$page}) {
2001                         $index{page}{$src}{state}=$pagestate{$page};
2002                 }
2003         }
2005         $index{state}={};
2006         foreach my $id (@plugins) {
2007                 $index{state}{$id}={}; # used to detect disabled plugins
2008                 foreach my $key (keys %{$wikistate{$id}}) {
2009                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
2010                 }
2011         }
2012         
2013         $index{lastrev}=$lastrev;
2014         $index{underlayfiles}=\@underlayfiles;
2016         $index{version}="3";
2017         my $ret=Storable::nstore_fd(\%index, $out);
2018         return if ! defined $ret || ! $ret;
2019         close $out || error("failed saving to $newfile: $!", $cleanup);
2020         rename($newfile, "$config{wikistatedir}/indexdb") ||
2021                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
2022         
2023         return 1;
2026 sub template_file ($) {
2027         my $name=shift;
2028         
2029         my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
2030         my $template;
2031         if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
2032                 $template=srcfile($pagesources{$tpage}, 1);
2033                 $name.=".tmpl";
2034         }
2035         else {
2036                 $template=srcfile($tpage, 1);
2037         }
2039         if (defined $template) {
2040                 return $template, $tpage, 1 if wantarray;
2041                 return $template;
2042         }
2043         else {
2044                 $name=~s:/::; # avoid path traversal
2045                 foreach my $dir ($config{templatedir},
2046                                  "$installdir/share/ikiwiki/templates") {
2047                         if (-e "$dir/$name") {
2048                                 $template="$dir/$name";
2049                                 last;
2050                         }
2051                 }
2052                 if (defined $template) {        
2053                         return $template, $tpage if wantarray;
2054                         return $template;
2055                 }
2056         }
2058         return;
2061 sub template_depends ($$;@) {
2062         my $name=shift;
2063         my $page=shift;
2064         
2065         my ($filename, $tpage, $untrusted)=template_file($name);
2066         if (! defined $filename) {
2067                 error(sprintf(gettext("template %s not found"), $name))
2068         }
2070         if (defined $page && defined $tpage) {
2071                 add_depends($page, $tpage);
2072         }
2074         my @opts=(
2075                 filter => sub {
2076                         my $text_ref = shift;
2077                         ${$text_ref} = decode_utf8(${$text_ref});
2078                         run_hooks(readtemplate => sub {
2079                                 ${$text_ref} = shift->(
2080                                         id => $name,
2081                                         page => $tpage,
2082                                         content => ${$text_ref},
2083                                         untrusted => $untrusted,
2084                                 );
2085                         });
2086                 },
2087                 loop_context_vars => 1,
2088                 die_on_bad_params => 0,
2089                 parent_global_vars => 1,
2090                 filename => $filename,
2091                 @_,
2092                 ($untrusted ? (no_includes => 1) : ()),
2093         );
2094         return @opts if wantarray;
2096         require HTML::Template;
2097         return HTML::Template->new(@opts);
2100 sub template ($;@) {
2101         template_depends(shift, undef, @_);
2104 sub templateactions ($$) {
2105         my $template=shift;
2106         my $page=shift;
2108         my $have_actions=0;
2109         my @actions;
2110         run_hooks(pageactions => sub {
2111                 push @actions, map { { action => $_ } } 
2112                         grep { defined } shift->(page => $page);
2113         });
2114         $template->param(actions => \@actions);
2116         if ($config{cgiurl} && exists $hooks{auth}) {
2117                 $template->param(prefsurl => cgiurl(do => "prefs"));
2118                 $have_actions=1;
2119         }
2121         if ($have_actions || @actions) {
2122                 $template->param(have_actions => 1);
2123         }
2126 sub hook (@) {
2127         my %param=@_;
2128         
2129         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2130                 error 'hook requires type, call, and id parameters';
2131         }
2133         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2134         
2135         $hooks{$param{type}}{$param{id}}=\%param;
2136         return 1;
2139 sub run_hooks ($$) {
2140         # Calls the given sub for each hook of the given type,
2141         # passing it the hook function to call.
2142         my $type=shift;
2143         my $sub=shift;
2145         if (exists $hooks{$type}) {
2146                 my (@first, @middle, @last);
2147                 foreach my $id (keys %{$hooks{$type}}) {
2148                         if ($hooks{$type}{$id}{first}) {
2149                                 push @first, $id;
2150                         }
2151                         elsif ($hooks{$type}{$id}{last}) {
2152                                 push @last, $id;
2153                         }
2154                         else {
2155                                 push @middle, $id;
2156                         }
2157                 }
2158                 foreach my $id (@first, @middle, @last) {
2159                         $sub->($hooks{$type}{$id}{call});
2160                 }
2161         }
2163         return 1;
2166 sub rcs_update () {
2167         $hooks{rcs}{rcs_update}{call}->(@_);
2170 sub rcs_prepedit ($) {
2171         $hooks{rcs}{rcs_prepedit}{call}->(@_);
2174 sub rcs_commit (@) {
2175         $hooks{rcs}{rcs_commit}{call}->(@_);
2178 sub rcs_commit_staged (@) {
2179         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2182 sub rcs_add ($) {
2183         $hooks{rcs}{rcs_add}{call}->(@_);
2186 sub rcs_remove ($) {
2187         $hooks{rcs}{rcs_remove}{call}->(@_);
2190 sub rcs_rename ($$) {
2191         $hooks{rcs}{rcs_rename}{call}->(@_);
2194 sub rcs_recentchanges ($) {
2195         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2198 sub rcs_diff ($;$) {
2199         $hooks{rcs}{rcs_diff}{call}->(@_);
2202 sub rcs_getctime ($) {
2203         $hooks{rcs}{rcs_getctime}{call}->(@_);
2206 sub rcs_getmtime ($) {
2207         $hooks{rcs}{rcs_getmtime}{call}->(@_);
2210 sub rcs_receive () {
2211         $hooks{rcs}{rcs_receive}{call}->();
2214 sub add_depends ($$;$) {
2215         my $page=shift;
2216         my $pagespec=shift;
2217         my $deptype=shift || $DEPEND_CONTENT;
2219         # Is the pagespec a simple page name?
2220         if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2221             $pagespec !~ /[\s*?()!]/) {
2222                 $depends_simple{$page}{lc $pagespec} |= $deptype;
2223                 return 1;
2224         }
2226         # Add explicit dependencies for influences.
2227         my $sub=pagespec_translate($pagespec);
2228         return unless defined $sub;
2229         foreach my $p (keys %pagesources) {
2230                 my $r=$sub->($p, location => $page);
2231                 my $i=$r->influences;
2232                 my $static=$r->influences_static;
2233                 foreach my $k (keys %$i) {
2234                         next unless $r || $static || $k eq $page;
2235                         $depends_simple{$page}{lc $k} |= $i->{$k};
2236                 }
2237                 last if $static;
2238         }
2240         $depends{$page}{$pagespec} |= $deptype;
2241         return 1;
2244 sub deptype (@) {
2245         my $deptype=0;
2246         foreach my $type (@_) {
2247                 if ($type eq 'presence') {
2248                         $deptype |= $DEPEND_PRESENCE;
2249                 }
2250                 elsif ($type eq 'links') { 
2251                         $deptype |= $DEPEND_LINKS;
2252                 }
2253                 elsif ($type eq 'content') {
2254                         $deptype |= $DEPEND_CONTENT;
2255                 }
2256         }
2257         return $deptype;
2260 my $file_prune_regexp;
2261 sub file_pruned ($) {
2262         my $file=shift;
2264         if (defined $config{include} && length $config{include}) {
2265                 return 0 if $file =~ m/$config{include}/;
2266         }
2268         if (! defined $file_prune_regexp) {
2269                 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2270                 $file_prune_regexp=qr/$file_prune_regexp/;
2271         }
2272         return $file =~ m/$file_prune_regexp/;
2275 sub define_gettext () {
2276         # If translation is needed, redefine the gettext function to do it.
2277         # Otherwise, it becomes a quick no-op.
2278         my $gettext_obj;
2279         my $getobj;
2280         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2281             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2282             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2283                 $getobj=sub {
2284                         $gettext_obj=eval q{
2285                                 use Locale::gettext q{textdomain};
2286                                 Locale::gettext->domain('ikiwiki')
2287                         };
2288                 };
2289         }
2291         no warnings 'redefine';
2292         *gettext=sub {
2293                 $getobj->() if $getobj;
2294                 if ($gettext_obj) {
2295                         $gettext_obj->get(shift);
2296                 }
2297                 else {
2298                         return shift;
2299                 }
2300         };
2301         *ngettext=sub {
2302                 $getobj->() if $getobj;
2303                 if ($gettext_obj) {
2304                         $gettext_obj->nget(@_);
2305                 }
2306                 else {
2307                         return ($_[2] == 1 ? $_[0] : $_[1])
2308                 }
2309         };
2312 sub gettext {
2313         define_gettext();
2314         gettext(@_);
2317 sub ngettext {
2318         define_gettext();
2319         ngettext(@_);
2322 sub yesno ($) {
2323         my $val=shift;
2325         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2328 sub inject {
2329         # Injects a new function into the symbol table to replace an
2330         # exported function.
2331         my %params=@_;
2333         # This is deep ugly perl foo, beware.
2334         no strict;
2335         no warnings;
2336         if (! defined $params{parent}) {
2337                 $params{parent}='::';
2338                 $params{old}=\&{$params{name}};
2339                 $params{name}=~s/.*:://;
2340         }
2341         my $parent=$params{parent};
2342         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2343                 $ns = $params{parent} . $ns;
2344                 inject(%params, parent => $ns) unless $ns eq '::main::';
2345                 *{$ns . $params{name}} = $params{call}
2346                         if exists ${$ns}{$params{name}} &&
2347                            \&{${$ns}{$params{name}}} == $params{old};
2348         }
2349         use strict;
2350         use warnings;
2353 sub add_link ($$;$) {
2354         my $page=shift;
2355         my $link=shift;
2356         my $type=shift;
2358         push @{$links{$page}}, $link
2359                 unless grep { $_ eq $link } @{$links{$page}};
2361         if (defined $type) {
2362                 $typedlinks{$page}{$type}{$link} = 1;
2363         }
2366 sub add_autofile ($$$) {
2367         my $file=shift;
2368         my $plugin=shift;
2369         my $generator=shift;
2370         
2371         $autofiles{$file}{plugin}=$plugin;
2372         $autofiles{$file}{generator}=$generator;
2375 sub useragent () {
2376         return LWP::UserAgent->new(
2377                 cookie_jar => $config{cookiejar},
2378                 env_proxy => 1,         # respect proxy env vars
2379                 agent => $config{useragent},
2380         );
2383 sub sortspec_translate ($$) {
2384         my $spec = shift;
2385         my $reverse = shift;
2387         my $code = "";
2388         my @data;
2389         while ($spec =~ m{
2390                 \s*
2391                 (-?)            # group 1: perhaps negated
2392                 \s*
2393                 (               # group 2: a word
2394                         \w+\([^\)]*\)   # command(params)
2395                         |
2396                         [^\s]+          # or anything else
2397                 )
2398                 \s*
2399         }gx) {
2400                 my $negated = $1;
2401                 my $word = $2;
2402                 my $params = undef;
2404                 if ($word =~ m/^(\w+)\((.*)\)$/) {
2405                         # command with parameters
2406                         $params = $2;
2407                         $word = $1;
2408                 }
2409                 elsif ($word !~ m/^\w+$/) {
2410                         error(sprintf(gettext("invalid sort type %s"), $word));
2411                 }
2413                 if (length $code) {
2414                         $code .= " || ";
2415                 }
2417                 if ($negated) {
2418                         $code .= "-";
2419                 }
2421                 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2422                         if (defined $params) {
2423                                 push @data, $params;
2424                                 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2425                         }
2426                         else {
2427                                 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2428                         }
2429                 }
2430                 else {
2431                         error(sprintf(gettext("unknown sort type %s"), $word));
2432                 }
2433         }
2435         if (! length $code) {
2436                 # undefined sorting method... sort arbitrarily
2437                 return sub { 0 };
2438         }
2440         if ($reverse) {
2441                 $code="-($code)";
2442         }
2444         no warnings;
2445         return eval 'sub { '.$code.' }';
2448 sub pagespec_translate ($) {
2449         my $spec=shift;
2451         # Convert spec to perl code.
2452         my $code="";
2453         my @data;
2454         while ($spec=~m{
2455                 \s*             # ignore whitespace
2456                 (               # 1: match a single word
2457                         \!              # !
2458                 |
2459                         \(              # (
2460                 |
2461                         \)              # )
2462                 |
2463                         \w+\([^\)]*\)   # command(params)
2464                 |
2465                         [^\s()]+        # any other text
2466                 )
2467                 \s*             # ignore whitespace
2468         }gx) {
2469                 my $word=$1;
2470                 if (lc $word eq 'and') {
2471                         $code.=' &';
2472                 }
2473                 elsif (lc $word eq 'or') {
2474                         $code.=' |';
2475                 }
2476                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2477                         $code.=' '.$word;
2478                 }
2479                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2480                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2481                                 push @data, $2;
2482                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2483                         }
2484                         else {
2485                                 push @data, qq{unknown function in pagespec "$word"};
2486                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2487                         }
2488                 }
2489                 else {
2490                         push @data, $word;
2491                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2492                 }
2493         }
2495         if (! length $code) {
2496                 $code="IkiWiki::FailReason->new('empty pagespec')";
2497         }
2499         no warnings;
2500         return eval 'sub { my $page=shift; '.$code.' }';
2503 sub pagespec_match ($$;@) {
2504         my $page=shift;
2505         my $spec=shift;
2506         my @params=@_;
2508         # Backwards compatability with old calling convention.
2509         if (@params == 1) {
2510                 unshift @params, 'location';
2511         }
2513         my $sub=pagespec_translate($spec);
2514         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2515                 if ! defined $sub;
2516         return $sub->($page, @params);
2519 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2521 # Not exported yet, but could be in future if it is generally useful.
2522 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2523 # which is "more internal".
2524 sub sort_pages ($$;@) {
2525         my $sort = shift;
2526         my $list = shift;
2527         my %params = @_;
2528         $sort = sortspec_translate($sort, $params{reverse});
2529         return IkiWiki::SortSpec::sort_pages($sort, @$list);
2532 sub pagespec_match_list ($$;@) {
2533         my $page=shift;
2534         my $pagespec=shift;
2535         my %params=@_;
2537         # Backwards compatability with old calling convention.
2538         if (ref $page) {
2539                 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2540                 $params{list}=$page;
2541                 $page=$params{location}; # ugh!
2542         }
2544         my $sub=pagespec_translate($pagespec);
2545         error "syntax error in pagespec \"$pagespec\""
2546                 if ! defined $sub;
2547         my $sort=sortspec_translate($params{sort}, $params{reverse})
2548                 if defined $params{sort};
2550         my @candidates;
2551         if (exists $params{list}) {
2552                 @candidates=exists $params{filter}
2553                         ? grep { ! $params{filter}->($_) } @{$params{list}}
2554                         : @{$params{list}};
2555         }
2556         else {
2557                 @candidates=exists $params{filter}
2558                         ? grep { ! $params{filter}->($_) } keys %pagesources
2559                         : keys %pagesources;
2560         }
2561         
2562         # clear params, remainder is passed to pagespec
2563         $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2564         my $num=$params{num};
2565         delete @params{qw{num deptype reverse sort filter list}};
2566         
2567         # when only the top matches will be returned, it's efficient to
2568         # sort before matching to pagespec,
2569         if (defined $num && defined $sort) {
2570                 @candidates=IkiWiki::SortSpec::sort_pages(
2571                         $sort, @candidates);
2572         }
2573         
2574         my @matches;
2575         my $firstfail;
2576         my $count=0;
2577         my $accum=IkiWiki::SuccessReason->new();
2578         foreach my $p (@candidates) {
2579                 my $r=$sub->($p, %params, location => $page);
2580                 error(sprintf(gettext("cannot match pages: %s"), $r))
2581                         if $r->isa("IkiWiki::ErrorReason");
2582                 unless ($r || $r->influences_static) {
2583                         $r->remove_influence($p);
2584                 }
2585                 $accum |= $r;
2586                 if ($r) {
2587                         push @matches, $p;
2588                         last if defined $num && ++$count == $num;
2589                 }
2590         }
2592         # Add simple dependencies for accumulated influences.
2593         my $i=$accum->influences;
2594         foreach my $k (keys %$i) {
2595                 $depends_simple{$page}{lc $k} |= $i->{$k};
2596         }
2598         # when all matches will be returned, it's efficient to
2599         # sort after matching
2600         if (! defined $num && defined $sort) {
2601                 return IkiWiki::SortSpec::sort_pages(
2602                         $sort, @matches);
2603         }
2604         else {
2605                 return @matches;
2606         }
2609 sub pagespec_valid ($) {
2610         my $spec=shift;
2612         return defined pagespec_translate($spec);
2615 sub glob2re ($) {
2616         my $re=quotemeta(shift);
2617         $re=~s/\\\*/.*/g;
2618         $re=~s/\\\?/./g;
2619         return qr/^$re$/i;
2622 package IkiWiki::FailReason;
2624 use overload (
2625         '""'    => sub { $_[0][0] },
2626         '0+'    => sub { 0 },
2627         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2628         '&'     => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2629         '|'     => sub { $_[1]->merge_influences($_[0]); $_[1] },
2630         fallback => 1,
2631 );
2633 our @ISA = 'IkiWiki::SuccessReason';
2635 package IkiWiki::SuccessReason;
2637 # A blessed array-ref:
2639 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2640 # [1]{""}:
2641 #      - if absent or false, the influences of this evaluation are "static",
2642 #        see the influences_static method
2643 #      - if true, they are dynamic (not static)
2644 # [1]{any other key}:
2645 #      the dependency types of influences, as returned by the influences method
2647 use overload (
2648         # in string context, it's the human-readable reason
2649         '""'    => sub { $_[0][0] },
2650         # in boolean context, SuccessReason is 1 and FailReason is 0
2651         '0+'    => sub { 1 },
2652         # negating a result gives the opposite result with the same influences
2653         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
2654         # A & B = (A ? B : A) with the influences of both
2655         '&'     => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2656         # A | B = (A ? A : B) with the influences of both
2657         '|'     => sub { $_[0]->merge_influences($_[1]); $_[0] },
2658         fallback => 1,
2659 );
2661 # SuccessReason->new("human-readable reason", page => deptype, ...)
2663 sub new {
2664         my $class = shift;
2665         my $value = shift;
2666         return bless [$value, {@_}], $class;
2669 # influences(): return a reference to a copy of the hash
2670 # { page => dependency type } describing the pages that indirectly influenced
2671 # this result, but would not cause a dependency through ikiwiki's core
2672 # dependency logic.
2674 # See [[todo/dependency_types]] for extensive discussion of what this means.
2676 # influences(page => deptype, ...): remove all influences, replace them
2677 # with the arguments, and return a reference to a copy of the new influences.
2679 sub influences {
2680         my $this=shift;
2681         $this->[1]={@_} if @_;
2682         my %i=%{$this->[1]};
2683         delete $i{""};
2684         return \%i;
2687 # True if this result has the same influences whichever page it matches,
2688 # For instance, whether bar matches backlink(foo) is influenced only by
2689 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2690 # which does not mention bar anywhere.
2692 # False if this result would have different influences when matching
2693 # different pages. For instance, when testing whether link(foo) matches bar,
2694 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2695 # bar's links could change the outcome; so its influences are not the same
2696 # as when testing whether link(foo) matches baz.
2698 # Static influences are one of the things that make pagespec_match_list
2699 # more efficient than repeated calls to pagespec_match.
2701 sub influences_static {
2702         return ! $_[0][1]->{""};
2705 # Change the influences of $this to be the influences of "$this & $other"
2706 # or "$this | $other".
2708 # If both $this and $other are either successful or have influences,
2709 # or this is an "or" operation, the result has all the influences from
2710 # either of the arguments. It has dynamic influences if either argument
2711 # has dynamic influences.
2713 # If this is an "and" operation, and at least one argument is a
2714 # FailReason with no influences, the result has no influences, and they
2715 # are not dynamic. For instance, link(foo) matching bar is influenced
2716 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2717 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2718 # bar, because it would be false however often you edit bar.
2720 sub merge_influences {
2721         my $this=shift;
2722         my $other=shift;
2723         my $anded=shift;
2725         # This "if" is odd because it needs to avoid negating $this
2726         # or $other, which would alter the objects in-place. Be careful.
2727         if (! $anded || (($this || %{$this->[1]}) &&
2728                          ($other || %{$other->[1]}))) {
2729                 foreach my $influence (keys %{$other->[1]}) {
2730                         $this->[1]{$influence} |= $other->[1]{$influence};
2731                 }
2732         }
2733         else {
2734                 # influence blocker
2735                 $this->[1]={};
2736         }
2739 # Change $this so it is not considered to be influenced by $torm.
2741 sub remove_influence {
2742         my $this=shift;
2743         my $torm=shift;
2745         delete $this->[1]{$torm};
2748 package IkiWiki::ErrorReason;
2750 our @ISA = 'IkiWiki::FailReason';
2752 package IkiWiki::PageSpec;
2754 sub derel ($$) {
2755         my $path=shift;
2756         my $from=shift;
2758         if ($path =~ m!^\.(/|$)!) {
2759                 if ($1) {
2760                         $from=~s#/?[^/]+$## if defined $from;
2761                         $path=~s#^\./##;
2762                         $path="$from/$path" if defined $from && length $from;
2763                 }
2764                 else {
2765                         $path = $from;
2766                         $path = "" unless defined $path;
2767                 }
2768         }
2770         return $path;
2773 my %glob_cache;
2775 sub match_glob ($$;@) {
2776         my $page=shift;
2777         my $glob=shift;
2778         my %params=@_;
2779         
2780         $glob=derel($glob, $params{location});
2782         # Instead of converting the glob to a regex every time,
2783         # cache the compiled regex to save time.
2784         my $re=$glob_cache{$glob};
2785         unless (defined $re) {
2786                 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2787         }
2788         if ($page =~ $re) {
2789                 if (! IkiWiki::isinternal($page) || $params{internal}) {
2790                         return IkiWiki::SuccessReason->new("$glob matches $page");
2791                 }
2792                 else {
2793                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2794                 }
2795         }
2796         else {
2797                 return IkiWiki::FailReason->new("$glob does not match $page");
2798         }
2801 sub match_internal ($$;@) {
2802         return match_glob(shift, shift, @_, internal => 1)
2805 sub match_page ($$;@) {
2806         my $page=shift;
2807         my $match=match_glob($page, shift, @_);
2808         if ($match) {
2809                 my $source=exists $IkiWiki::pagesources{$page} ?
2810                         $IkiWiki::pagesources{$page} :
2811                         $IkiWiki::delpagesources{$page};
2812                 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2813                 if (! defined $type) {  
2814                         return IkiWiki::FailReason->new("$page is not a page");
2815                 }
2816         }
2817         return $match;
2820 sub match_link ($$;@) {
2821         my $page=shift;
2822         my $link=lc(shift);
2823         my %params=@_;
2825         $link=derel($link, $params{location});
2826         my $from=exists $params{location} ? $params{location} : '';
2827         my $linktype=$params{linktype};
2828         my $qualifier='';
2829         if (defined $linktype) {
2830                 $qualifier=" with type $linktype";
2831         }
2833         my $links = $IkiWiki::links{$page};
2834         return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2835                 unless $links && @{$links};
2836         my $bestlink = IkiWiki::bestlink($from, $link);
2837         foreach my $p (@{$links}) {
2838                 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2840                 if (length $bestlink) {
2841                         if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2842                                 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2843                         }
2844                 }
2845                 else {
2846                         if (match_glob($p, $link, %params)) {
2847                                 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2848                         }
2849                         my ($p_rel)=$p=~/^\/?(.*)/;
2850                         $link=~s/^\///;
2851                         if (match_glob($p_rel, $link, %params)) {
2852                                 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2853                         }
2854                 }
2855         }
2856         return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2859 sub match_backlink ($$;@) {
2860         my $page=shift;
2861         my $testpage=shift;
2862         my %params=@_;
2863         if ($testpage eq '.') {
2864                 $testpage = $params{'location'}
2865         }
2866         my $ret=match_link($testpage, $page, @_);
2867         $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2868         return $ret;
2871 sub match_created_before ($$;@) {
2872         my $page=shift;
2873         my $testpage=shift;
2874         my %params=@_;
2875         
2876         $testpage=derel($testpage, $params{location});
2878         if (exists $IkiWiki::pagectime{$testpage}) {
2879                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2880                         return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2881                 }
2882                 else {
2883                         return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2884                 }
2885         }
2886         else {
2887                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2888         }
2891 sub match_created_after ($$;@) {
2892         my $page=shift;
2893         my $testpage=shift;
2894         my %params=@_;
2895         
2896         $testpage=derel($testpage, $params{location});
2898         if (exists $IkiWiki::pagectime{$testpage}) {
2899                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2900                         return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2901                 }
2902                 else {
2903                         return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2904                 }
2905         }
2906         else {
2907                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2908         }
2911 sub match_creation_day ($$;@) {
2912         my $page=shift;
2913         my $d=shift;
2914         if ($d !~ /^\d+$/) {
2915                 return IkiWiki::ErrorReason->new("invalid day $d");
2916         }
2917         if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2918                 return IkiWiki::SuccessReason->new('creation_day matched');
2919         }
2920         else {
2921                 return IkiWiki::FailReason->new('creation_day did not match');
2922         }
2925 sub match_creation_month ($$;@) {
2926         my $page=shift;
2927         my $m=shift;
2928         if ($m !~ /^\d+$/) {
2929                 return IkiWiki::ErrorReason->new("invalid month $m");
2930         }
2931         if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2932                 return IkiWiki::SuccessReason->new('creation_month matched');
2933         }
2934         else {
2935                 return IkiWiki::FailReason->new('creation_month did not match');
2936         }
2939 sub match_creation_year ($$;@) {
2940         my $page=shift;
2941         my $y=shift;
2942         if ($y !~ /^\d+$/) {
2943                 return IkiWiki::ErrorReason->new("invalid year $y");
2944         }
2945         if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2946                 return IkiWiki::SuccessReason->new('creation_year matched');
2947         }
2948         else {
2949                 return IkiWiki::FailReason->new('creation_year did not match');
2950         }
2953 sub match_user ($$;@) {
2954         shift;
2955         my $user=shift;
2956         my %params=@_;
2957         
2958         if (! exists $params{user}) {
2959                 return IkiWiki::ErrorReason->new("no user specified");
2960         }
2962         my $regexp=IkiWiki::glob2re($user);
2963         
2964         if (defined $params{user} && $params{user}=~$regexp) {
2965                 return IkiWiki::SuccessReason->new("user is $user");
2966         }
2967         elsif (! defined $params{user}) {
2968                 return IkiWiki::FailReason->new("not logged in");
2969         }
2970         else {
2971                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2972         }
2975 sub match_admin ($$;@) {
2976         shift;
2977         shift;
2978         my %params=@_;
2979         
2980         if (! exists $params{user}) {
2981                 return IkiWiki::ErrorReason->new("no user specified");
2982         }
2984         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2985                 return IkiWiki::SuccessReason->new("user is an admin");
2986         }
2987         elsif (! defined $params{user}) {
2988                 return IkiWiki::FailReason->new("not logged in");
2989         }
2990         else {
2991                 return IkiWiki::FailReason->new("user is not an admin");
2992         }
2995 sub match_ip ($$;@) {
2996         shift;
2997         my $ip=shift;
2998         my %params=@_;
2999         
3000         if (! exists $params{ip}) {
3001                 return IkiWiki::ErrorReason->new("no IP specified");
3002         }
3003         
3004         my $regexp=IkiWiki::glob2re(lc $ip);
3006         if (defined $params{ip} && lc $params{ip}=~$regexp) {
3007                 return IkiWiki::SuccessReason->new("IP is $ip");
3008         }
3009         else {
3010                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
3011         }
3014 package IkiWiki::SortSpec;
3016 # This is in the SortSpec namespace so that the $a and $b that sort() uses
3017 # are easily available in this namespace, for cmp functions to use them.
3018 sub sort_pages {
3019         my $f=shift;
3020         sort $f @_
3023 sub cmp_title {
3024         IkiWiki::pagetitle(IkiWiki::basename($a))
3025         cmp
3026         IkiWiki::pagetitle(IkiWiki::basename($b))
3029 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
3030 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
3031 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }