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