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