]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki.pm
cleaned up, updated and submitted for patch
[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         },
569         deterministic => {
570                 type => "boolean",
571                 default => 0,
572                 description => "try harder to produce deterministic output",
573                 safe => 1,
574                 rebuild => 1,
575                 advanced => 1,
576         },
579 sub getlibdirs () {
580         my @libdirs;
581         if ($config{libdirs}) {
582                 @libdirs = @{$config{libdirs}};
583         }
584         if (length $config{libdir}) {
585                 push @libdirs, $config{libdir};
586         }
587         return @libdirs;
590 sub defaultconfig () {
591         my %s=getsetup();
592         my @ret;
593         foreach my $key (keys %s) {
594                 push @ret, $key, $s{$key}->{default};
595         }
596         return @ret;
599 # URL to top of wiki as a path starting with /, valid from any wiki page or
600 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
601 my $local_url;
602 # URL to CGI script, similar to $local_url
603 my $local_cgiurl;
605 sub checkconfig () {
606         # locale stuff; avoid LC_ALL since it overrides everything
607         if (defined $ENV{LC_ALL}) {
608                 $ENV{LANG} = $ENV{LC_ALL};
609                 delete $ENV{LC_ALL};
610         }
611         if (defined $config{locale}) {
612                 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
613                         $ENV{LANG}=$config{locale};
614                         define_gettext();
615                 }
616         }
617                 
618         if (! defined $config{wiki_file_regexp}) {
619                 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
620         }
622         if (ref $config{ENV} eq 'HASH') {
623                 foreach my $val (keys %{$config{ENV}}) {
624                         $ENV{$val}=$config{ENV}{$val};
625                 }
626         }
627         if (defined $config{timezone} && length $config{timezone}) {
628                 $ENV{TZ}=$config{timezone};
629         }
630         elsif (defined $ENV{TZ} && length $ENV{TZ}) {
631                 $config{timezone}=$ENV{TZ};
632         }
633         else {
634                 eval q{use Config qw()};
635                 error($@) if $@;
637                 if ($Config::Config{d_gnulibc} && -e '/etc/localtime') {
638                         $config{timezone}=$ENV{TZ}=':/etc/localtime';
639                 }
640                 else {
641                         $config{timezone}=$ENV{TZ}='GMT';
642                 }
643         }
645         if ($config{w3mmode}) {
646                 eval q{use Cwd q{abs_path}};
647                 error($@) if $@;
648                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
649                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
650                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
651                         unless $config{cgiurl} =~ m!file:///!;
652                 $config{url}="file://".$config{destdir};
653         }
655         if ($config{cgi} && ! length $config{url}) {
656                 error(gettext("Must specify url to wiki with --url when using --cgi"));
657         }
659         if (defined $config{url} && length $config{url}) {
660                 eval q{use URI};
661                 my $baseurl = URI->new($config{url});
663                 $local_url = $baseurl->path . "/";
664                 $local_cgiurl = undef;
666                 if (length $config{cgiurl}) {
667                         my $cgiurl = URI->new($config{cgiurl});
669                         $local_cgiurl = $cgiurl->path;
671                         if ($cgiurl->scheme eq 'https' &&
672                                 $baseurl->scheme eq 'http') {
673                                 # We assume that the same content is available
674                                 # over both http and https, because if it
675                                 # wasn't, accessing the static content
676                                 # from the CGI would be mixed-content,
677                                 # which would be a security flaw.
679                                 if ($cgiurl->authority ne $baseurl->authority) {
680                                         # use protocol-relative URL for
681                                         # static content
682                                         $local_url = "$config{url}/";
683                                         $local_url =~ s{^http://}{//};
684                                 }
685                                 # else use host-relative URL for static content
687                                 # either way, CGI needs to be absolute
688                                 $local_cgiurl = $config{cgiurl};
689                         }
690                         elsif ($cgiurl->scheme ne $baseurl->scheme) {
691                                 # too far apart, fall back to absolute URLs
692                                 $local_url = "$config{url}/";
693                                 $local_cgiurl = $config{cgiurl};
694                         }
695                         elsif ($cgiurl->authority ne $baseurl->authority) {
696                                 # slightly too far apart, fall back to
697                                 # protocol-relative URLs
698                                 $local_url = "$config{url}/";
699                                 $local_url =~ s{^https?://}{//};
700                                 $local_cgiurl = $config{cgiurl};
701                                 $local_cgiurl =~ s{^https?://}{//};
702                         }
703                         # else keep host-relative URLs
704                 }
706                 $local_url =~ s{//$}{/};
707         }
708         else {
709                 $local_cgiurl = $config{cgiurl};
710         }
712         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
713                 unless exists $config{wikistatedir} && defined $config{wikistatedir};
715         if (defined $config{umask}) {
716                 my $u = possibly_foolish_untaint($config{umask});
718                 if ($u =~ m/^\d+$/) {
719                         umask($u);
720                 }
721                 elsif ($u eq 'private') {
722                         umask(077);
723                 }
724                 elsif ($u eq 'group') {
725                         umask(027);
726                 }
727                 elsif ($u eq 'public') {
728                         umask(022);
729                 }
730                 else {
731                         error(sprintf(gettext("unsupported umask setting %s"), $u));
732                 }
733         }
735         run_hooks(checkconfig => sub { shift->() });
737         return 1;
740 sub listplugins () {
741         my %ret;
743         foreach my $dir (@INC, getlibdirs()) {
744                 next unless defined $dir && length $dir;
745                 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
746                         my ($plugin)=$file=~/.*\/(.*)\.pm$/;
747                         $ret{$plugin}=1;
748                 }
749         }
750         foreach my $dir (getlibdirs(), "$installdir/lib/ikiwiki") {
751                 next unless defined $dir && length $dir;
752                 foreach my $file (glob("$dir/plugins/*")) {
753                         $ret{basename($file)}=1 if -x $file;
754                 }
755         }
757         return keys %ret;
760 sub loadplugins () {
761         foreach my $dir (getlibdirs()) {
762                 unshift @INC, possibly_foolish_untaint($dir);
763         }
765         foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
766                 loadplugin($plugin);
767         }
768         
769         if ($config{rcs}) {
770                 if (exists $hooks{rcs}) {
771                         error(gettext("cannot use multiple rcs plugins"));
772                 }
773                 loadplugin($config{rcs});
774         }
775         if (! exists $hooks{rcs}) {
776                 loadplugin("norcs");
777         }
779         run_hooks(getopt => sub { shift->() });
780         if (grep /^-/, @ARGV) {
781                 print STDERR "Unknown option (or missing parameter): $_\n"
782                         foreach grep /^-/, @ARGV;
783                 usage();
784         }
786         return 1;
789 sub loadplugin ($;$) {
790         my $plugin=shift;
791         my $force=shift;
793         return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
795         foreach my $possiblytainteddir (getlibdirs(), "$installdir/lib/ikiwiki") {
796                 my $dir = possibly_foolish_untaint($possiblytainteddir);
797                 if (defined $dir && -x "$dir/plugins/$plugin") {
798                         eval { require IkiWiki::Plugin::external };
799                         if ($@) {
800                                 my $reason=$@;
801                                 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
802                         }
803                         import IkiWiki::Plugin::external "$dir/plugins/$plugin";
804                         $loaded_plugins{$plugin}=1;
805                         return 1;
806                 }
807         }
809         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
810         eval qq{use $mod};
811         if ($@) {
812                 error("Failed to load plugin $mod: $@");
813         }
814         $loaded_plugins{$plugin}=1;
815         return 1;
818 sub error ($;$) {
819         my $message=shift;
820         my $cleaner=shift;
821         log_message('err' => $message) if $config{syslog};
822         if (defined $cleaner) {
823                 $cleaner->();
824         }
825         die $message."\n";
828 sub debug ($) {
829         return unless $config{verbose};
830         return log_message(debug => @_);
833 my $log_open=0;
834 my $log_failed=0;
835 sub log_message ($$) {
836         my $type=shift;
838         if ($config{syslog}) {
839                 require Sys::Syslog;
840                 if (! $log_open) {
841                         Sys::Syslog::setlogsock('unix');
842                         Sys::Syslog::openlog('ikiwiki', '', 'user');
843                         $log_open=1;
844                 }
845                 eval {
846                         my $message = "[$config{wikiname}] ".join(" ", @_);
847                         utf8::encode($message);
848                         Sys::Syslog::syslog($type, "%s", $message);
849                 };
850                 if ($@) {
851                     print STDERR "failed to syslog: $@" unless $log_failed;
852                     $log_failed=1;
853                     print STDERR "@_\n";
854                 }
855                 return $@;
856         }
857         elsif (! $config{cgi}) {
858                 return print "@_\n";
859         }
860         else {
861                 return print STDERR "@_\n";
862         }
865 sub possibly_foolish_untaint ($) {
866         my $tainted=shift;
867         my ($untainted)=$tainted=~/(.*)/s;
868         return $untainted;
871 sub basename ($) {
872         my $file=shift;
874         $file=~s!.*/+!!;
875         return $file;
878 sub dirname ($) {
879         my $file=shift;
881         $file=~s!/*[^/]+$!!;
882         return $file;
885 sub isinternal ($) {
886         my $page=shift;
887         return exists $pagesources{$page} &&
888                 $pagesources{$page} =~ /\._([^.]+)$/;
891 sub pagetype ($) {
892         my $file=shift;
893         
894         if ($file =~ /\.([^.]+)$/) {
895                 return $1 if exists $hooks{htmlize}{$1};
896         }
897         my $base=basename($file);
898         if (exists $hooks{htmlize}{$base} &&
899             $hooks{htmlize}{$base}{noextension}) {
900                 return $base;
901         }
902         return;
905 my %pagename_cache;
907 sub pagename ($) {
908         my $file=shift;
910         if (exists $pagename_cache{$file}) {
911                 return $pagename_cache{$file};
912         }
914         my $type=pagetype($file);
915         my $page=$file;
916         $page=~s/\Q.$type\E*$//
917                 if defined $type && !$hooks{htmlize}{$type}{keepextension}
918                         && !$hooks{htmlize}{$type}{noextension};
919         if ($config{indexpages} && $page=~/(.*)\/index$/) {
920                 $page=$1;
921         }
923         $pagename_cache{$file} = $page;
924         return $page;
927 sub newpagefile ($$) {
928         my $page=shift;
929         my $type=shift;
931         if (! $config{indexpages} || $page eq 'index') {
932                 return $page.".".$type;
933         }
934         else {
935                 return $page."/index.".$type;
936         }
939 sub targetpage ($$;$) {
940         my $page=shift;
941         my $ext=shift;
942         my $filename=shift;
943         
944         if (defined $filename) {
945                 return $page."/".$filename.".".$ext;
946         }
947         elsif (! $config{usedirs} || $page eq 'index') {
948                 return $page.".".$ext;
949         }
950         else {
951                 return $page."/index.".$ext;
952         }
955 sub htmlpage ($) {
956         my $page=shift;
957         
958         return targetpage($page, $config{htmlext});
961 sub srcfile_stat {
962         my $file=shift;
963         my $nothrow=shift;
965         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
966         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
967                 return "$dir/$file", stat(_) if -e "$dir/$file";
968         }
969         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
970         return;
973 sub srcfile ($;$) {
974         return (srcfile_stat(@_))[0];
977 sub add_literal_underlay ($) {
978         my $dir=shift;
980         if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
981                 unshift @{$config{underlaydirs}}, $dir;
982         }
985 sub add_underlay ($) {
986         my $dir = shift;
988         if ($dir !~ /^\//) {
989                 $dir="$config{underlaydirbase}/$dir";
990         }
992         add_literal_underlay($dir);
993         # why does it return 1? we just don't know
994         return 1;
997 sub readfile ($;$$) {
998         my $file=shift;
999         my $binary=shift;
1000         my $wantfd=shift;
1002         if (-l $file) {
1003                 error("cannot read a symlink ($file)");
1004         }
1005         
1006         local $/=undef;
1007         open (my $in, "<", $file) || error("failed to read $file: $!");
1008         binmode($in) if ($binary);
1009         return \*$in if $wantfd;
1010         my $ret=<$in>;
1011         # check for invalid utf-8, and toss it back to avoid crashes
1012         if (! utf8::valid($ret)) {
1013                 $ret=encode_utf8($ret);
1014         }
1015         close $in || error("failed to read $file: $!");
1016         return $ret;
1019 sub prep_writefile ($$) {
1020         my $file=shift;
1021         my $destdir=shift;
1022         
1023         my $test=$file;
1024         while (length $test) {
1025                 if (-l "$destdir/$test") {
1026                         error("cannot write to a symlink ($test)");
1027                 }
1028                 if (-f _ && $test ne $file) {
1029                         # Remove conflicting file.
1030                         foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1031                                 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1032                                         if ($f eq $test) {
1033                                                 unlink("$destdir/$test");
1034                                                 last;
1035                                         }
1036                                 }
1037                         }
1038                 }
1039                 $test=dirname($test);
1040         }
1042         my $dir=dirname("$destdir/$file");
1043         if (! -d $dir) {
1044                 my $d="";
1045                 foreach my $s (split(m!/+!, $dir)) {
1046                         $d.="$s/";
1047                         if (! -d $d) {
1048                                 mkdir($d) || error("failed to create directory $d: $!");
1049                         }
1050                 }
1051         }
1053         return 1;
1056 sub writefile ($$$;$$) {
1057         my $file=shift; # can include subdirs
1058         my $destdir=shift; # directory to put file in
1059         my $content=shift;
1060         my $binary=shift;
1061         my $writer=shift;
1062         
1063         prep_writefile($file, $destdir);
1064         
1065         my $newfile="$destdir/$file.ikiwiki-new";
1066         if (-l $newfile) {
1067                 error("cannot write to a symlink ($newfile)");
1068         }
1069         
1070         my $cleanup = sub { unlink($newfile) };
1071         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
1072         binmode($out) if ($binary);
1073         if ($writer) {
1074                 $writer->(\*$out, $cleanup);
1075         }
1076         else {
1077                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
1078         }
1079         close $out || error("failed saving $newfile: $!", $cleanup);
1080         rename($newfile, "$destdir/$file") || 
1081                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1083         return 1;
1086 my %cleared;
1087 sub will_render ($$;$) {
1088         my $page=shift;
1089         my $dest=shift;
1090         my $clear=shift;
1092         # Important security check for independently created files.
1093         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1094             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1095                 my $from_other_page=0;
1096                 # Expensive, but rarely runs.
1097                 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1098                         if (grep {
1099                                 $_ eq $dest ||
1100                                 dirname($_) eq $dest
1101                             } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1102                                 $from_other_page=1;
1103                                 last;
1104                         }
1105                 }
1107                 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1108                         unless $from_other_page;
1109         }
1111         # If $dest exists as a directory, remove conflicting files in it
1112         # rendered from other pages.
1113         if (-d _) {
1114                 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1115                         foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1116                                 if (dirname($f) eq $dest) {
1117                                         unlink("$config{destdir}/$f");
1118                                         rmdir(dirname("$config{destdir}/$f"));
1119                                 }
1120                         }
1121                 }
1122         }
1124         if (! $clear || $cleared{$page}) {
1125                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1126         }
1127         else {
1128                 foreach my $old (@{$renderedfiles{$page}}) {
1129                         delete $destsources{$old};
1130                 }
1131                 $renderedfiles{$page}=[$dest];
1132                 $cleared{$page}=1;
1133         }
1134         $destsources{$dest}=$page;
1136         return 1;
1139 sub bestlink ($$) {
1140         my $page=shift;
1141         my $link=shift;
1142         
1143         my $cwd=$page;
1144         if ($link=~s/^\/+//) {
1145                 # absolute links
1146                 $cwd="";
1147         }
1148         $link=~s/\/$//;
1150         do {
1151                 my $l=$cwd;
1152                 $l.="/" if length $l;
1153                 $l.=$link;
1155                 if (exists $pagesources{$l}) {
1156                         return $l;
1157                 }
1158                 elsif (exists $pagecase{lc $l}) {
1159                         return $pagecase{lc $l};
1160                 }
1161         } while $cwd=~s{/?[^/]+$}{};
1163         if (length $config{userdir}) {
1164                 my $l = "$config{userdir}/".lc($link);
1165                 if (exists $pagesources{$l}) {
1166                         return $l;
1167                 }
1168                 elsif (exists $pagecase{lc $l}) {
1169                         return $pagecase{lc $l};
1170                 }
1171         }
1173         #print STDERR "warning: page $page, broken link: $link\n";
1174         return "";
1177 sub isinlinableimage ($) {
1178         my $file=shift;
1179         
1180         return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1183 sub pagetitle ($;$) {
1184         my $page=shift;
1185         my $unescaped=shift;
1187         if ($unescaped) {
1188                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1189         }
1190         else {
1191                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1192         }
1194         return $page;
1197 sub titlepage ($) {
1198         my $title=shift;
1199         # support use w/o %config set
1200         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1201         $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1202         return $title;
1205 sub linkpage ($) {
1206         my $link=shift;
1207         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1208         $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1209         return $link;
1212 sub cgiurl (@) {
1213         my %params=@_;
1215         my $cgiurl=$local_cgiurl;
1217         if (exists $params{cgiurl}) {
1218                 $cgiurl=$params{cgiurl};
1219                 delete $params{cgiurl};
1220         }
1222         unless (%params) {
1223                 return $cgiurl;
1224         }
1226         return $cgiurl."?".
1227                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), sort(keys %params));
1230 sub cgiurl_abs (@) {
1231         eval q{use URI};
1232         URI->new_abs(cgiurl(@_), $config{cgiurl});
1235 sub baseurl (;$) {
1236         my $page=shift;
1238         return $local_url if ! defined $page;
1239         
1240         $page=htmlpage($page);
1241         $page=~s/[^\/]+$//;
1242         $page=~s/[^\/]+\//..\//g;
1243         return $page;
1246 sub urlabs ($$) {
1247         my $url=shift;
1248         my $urlbase=shift;
1250         return $url unless defined $urlbase && length $urlbase;
1252         eval q{use URI};
1253         URI->new_abs($url, $urlbase)->as_string;
1256 sub abs2rel ($$) {
1257         # Work around very innefficient behavior in File::Spec if abs2rel
1258         # is passed two relative paths. It's much faster if paths are
1259         # absolute! (Debian bug #376658; fixed in debian unstable now)
1260         my $path="/".shift;
1261         my $base="/".shift;
1263         require File::Spec;
1264         my $ret=File::Spec->abs2rel($path, $base);
1265         $ret=~s/^// if defined $ret;
1266         return $ret;
1269 sub displaytime ($;$$) {
1270         # Plugins can override this function to mark up the time to
1271         # display.
1272         my $time=formattime($_[0], $_[1]);
1273         if ($config{html5}) {
1274                 return '<time datetime="'.date_3339($_[0]).'"'.
1275                         ($_[2] ? ' pubdate="pubdate"' : '').
1276                         '>'.$time.'</time>';
1277         }
1278         else {
1279                 return '<span class="date">'.$time.'</span>';
1280         }
1283 sub formattime ($;$) {
1284         # Plugins can override this function to format the time.
1285         my $time=shift;
1286         my $format=shift;
1287         if (! defined $format) {
1288                 $format=$config{timeformat};
1289         }
1291         return strftime_utf8($format, localtime($time));
1294 my $strftime_encoding;
1295 sub strftime_utf8 {
1296         # strftime doesn't know about encodings, so make sure
1297         # its output is properly treated as utf8.
1298         # Note that this does not handle utf-8 in the format string.
1299         ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1300                 unless defined $strftime_encoding;
1301         $strftime_encoding
1302                 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1303                 : POSIX::strftime(@_);
1306 sub date_3339 ($) {
1307         my $time=shift;
1309         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1310         POSIX::setlocale(&POSIX::LC_TIME, "C");
1311         my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1312         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1313         return $ret;
1316 sub beautify_urlpath ($) {
1317         my $url=shift;
1319         # Ensure url is not an empty link, and if necessary,
1320         # add ./ to avoid colon confusion.
1321         if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1322                 $url="./$url";
1323         }
1325         if ($config{usedirs}) {
1326                 $url =~ s!/index.$config{htmlext}$!/!;
1327         }
1329         return $url;
1332 sub urlto ($;$$) {
1333         my $to=shift;
1334         my $from=shift;
1335         my $absolute=shift;
1336         
1337         if (! length $to) {
1338                 $to = 'index';
1339         }
1341         if (! $destsources{$to}) {
1342                 $to=htmlpage($to);
1343         }
1345         if ($absolute) {
1346                 return $config{url}.beautify_urlpath("/".$to);
1347         }
1349         if (! defined $from) {
1350                 my $u = $local_url || '';
1351                 $u =~ s{/$}{};
1352                 return $u.beautify_urlpath("/".$to);
1353         }
1355         my $link = abs2rel($to, dirname(htmlpage($from)));
1357         return beautify_urlpath($link);
1360 sub isselflink ($$) {
1361         # Plugins can override this function to support special types
1362         # of selflinks.
1363         my $page=shift;
1364         my $link=shift;
1366         return $page eq $link;
1369 sub htmllink ($$$;@) {
1370         my $lpage=shift; # the page doing the linking
1371         my $page=shift; # the page that will contain the link (different for inline)
1372         my $link=shift;
1373         my %opts=@_;
1375         $link=~s/\/$//;
1377         my $bestlink;
1378         if (! $opts{forcesubpage}) {
1379                 $bestlink=bestlink($lpage, $link);
1380         }
1381         else {
1382                 $bestlink="$lpage/".lc($link);
1383         }
1385         my $linktext;
1386         if (defined $opts{linktext}) {
1387                 $linktext=$opts{linktext};
1388         }
1389         else {
1390                 $linktext=pagetitle(basename($link));
1391         }
1392         
1393         return "<span class=\"selflink\">$linktext</span>"
1394                 if length $bestlink && isselflink($page, $bestlink) &&
1395                    ! defined $opts{anchor};
1396         
1397         if (! $destsources{$bestlink}) {
1398                 $bestlink=htmlpage($bestlink);
1400                 if (! $destsources{$bestlink}) {
1401                         my $cgilink = "";
1402                         if (length $config{cgiurl}) {
1403                                 $cgilink = "<a href=\"".
1404                                         cgiurl(
1405                                                 do => "create",
1406                                                 page => $link,
1407                                                 from => $lpage
1408                                         )."\" rel=\"nofollow\">?</a>";
1409                         }
1410                         return "<span class=\"createlink\">$cgilink$linktext</span>"
1411                 }
1412         }
1413         
1414         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1415         $bestlink=beautify_urlpath($bestlink);
1416         
1417         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1418                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1419         }
1421         if (defined $opts{anchor}) {
1422                 $bestlink.="#".$opts{anchor};
1423         }
1425         my @attrs;
1426         foreach my $attr (qw{rel class title}) {
1427                 if (defined $opts{$attr}) {
1428                         push @attrs, " $attr=\"$opts{$attr}\"";
1429                 }
1430         }
1432         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1435 sub userpage ($) {
1436         my $user=shift;
1437         return length $config{userdir} ? "$config{userdir}/$user" : $user;
1440 # Username to display for openid accounts.
1441 sub openiduser ($) {
1442         my $user=shift;
1444         if (defined $user && $user =~ m!^https?://! &&
1445             eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1446                 my $display;
1448                 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1449                         $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1450                 }
1451                 else {
1452                         # backcompat with old version
1453                         my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1454                         $display=$oid->display;
1455                 }
1457                 # Convert "user.somehost.com" to "user [somehost.com]"
1458                 # (also "user.somehost.co.uk")
1459                 if ($display !~ /\[/) {
1460                         $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1461                 }
1462                 # Convert "http://somehost.com/user" to "user [somehost.com]".
1463                 # (also "https://somehost.com/user/")
1464                 if ($display !~ /\[/) {
1465                         $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1466                 }
1467                 $display=~s!^https?://!!; # make sure this is removed
1468                 eval q{use CGI 'escapeHTML'};
1469                 error($@) if $@;
1470                 return escapeHTML($display);
1471         }
1472         return;
1475 # Username to display for emailauth accounts. 
1476 sub emailuser ($) {
1477         my $user=shift;
1478         if (defined $user && $user =~ m/(.+)@/) {
1479                 my $nick=$1;
1480                 # remove any characters from not allowed in wiki files
1481                 # support use w/o %config set
1482                 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1483                 $nick=~s/[^$chars]/_/g;
1484                 return $nick;
1485         }
1486         return;
1489 # Some user information should not be exposed in commit metadata, etc.
1490 # This generates a cloaked form of such information.
1491 sub cloak ($) {
1492         my $user=shift;
1493         # cloak email address using http://xmlns.com/foaf/spec/#term_mbox_sha1sum
1494         if ($user=~m/(.+)@/) {
1495                 my $nick=$1;
1496                 eval q{use Digest::SHA};
1497                 return $user if $@;
1498                 return $nick.'@'.Digest::SHA::sha1_hex("mailto:$user");
1499         }
1500         else {
1501                 return $user;
1502         }
1505 sub htmlize ($$$$) {
1506         my $page=shift;
1507         my $destpage=shift;
1508         my $type=shift;
1509         my $content=shift;
1510         
1511         my $oneline = $content !~ /\n/;
1512         
1513         if (exists $hooks{htmlize}{$type}) {
1514                 $content=$hooks{htmlize}{$type}{call}->(
1515                         page => $page,
1516                         content => $content,
1517                 );
1518         }
1519         else {
1520                 error("htmlization of $type not supported");
1521         }
1523         run_hooks(sanitize => sub {
1524                 $content=shift->(
1525                         page => $page,
1526                         destpage => $destpage,
1527                         content => $content,
1528                 );
1529         });
1530         
1531         if ($oneline) {
1532                 # hack to get rid of enclosing junk added by markdown
1533                 # and other htmlizers/sanitizers
1534                 $content=~s/^<p>//i;
1535                 $content=~s/<\/p>\n*$//i;
1536         }
1538         return $content;
1541 sub linkify ($$$) {
1542         my $page=shift;
1543         my $destpage=shift;
1544         my $content=shift;
1546         run_hooks(linkify => sub {
1547                 $content=shift->(
1548                         page => $page,
1549                         destpage => $destpage,
1550                         content => $content,
1551                 );
1552         });
1553         
1554         return $content;
1557 our %preprocessing;
1558 our $preprocess_preview=0;
1559 sub preprocess ($$$;$$) {
1560         my $page=shift; # the page the data comes from
1561         my $destpage=shift; # the page the data will appear in (different for inline)
1562         my $content=shift;
1563         my $scan=shift;
1564         my $preview=shift;
1566         # Using local because it needs to be set within any nested calls
1567         # of this function.
1568         local $preprocess_preview=$preview if defined $preview;
1570         my $handle=sub {
1571                 my $escape=shift;
1572                 my $prefix=shift;
1573                 my $command=shift;
1574                 my $params=shift;
1575                 $params="" if ! defined $params;
1577                 if (length $escape) {
1578                         return "[[$prefix$command $params]]";
1579                 }
1580                 elsif (exists $hooks{preprocess}{$command}) {
1581                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1582                         # Note: preserve order of params, some plugins may
1583                         # consider it significant.
1584                         my @params;
1585                         while ($params =~ m{
1586                                 (?:([-.\w]+)=)?         # 1: named parameter key?
1587                                 (?:
1588                                         """(.*?)"""     # 2: triple-quoted value
1589                                 |
1590                                         "([^"]*?)"      # 3: single-quoted value
1591                                 |
1592                                         '''(.*?)'''     # 4: triple-single-quote
1593                                 |
1594                                         <<([a-zA-Z]+)\n # 5: heredoc start
1595                                         (.*?)\n\5       # 6: heredoc value
1596                                 |
1597                                         (\S+)           # 7: unquoted value
1598                                 )
1599                                 (?:\s+|$)               # delimiter to next param
1600                         }msgx) {
1601                                 my $key=$1;
1602                                 my $val;
1603                                 if (defined $2) {
1604                                         $val=$2;
1605                                         $val=~s/\r\n/\n/mg;
1606                                         $val=~s/^\n+//g;
1607                                         $val=~s/\n+$//g;
1608                                 }
1609                                 elsif (defined $3) {
1610                                         $val=$3;
1611                                 }
1612                                 elsif (defined $4) {
1613                                         $val=$4;
1614                                 }
1615                                 elsif (defined $7) {
1616                                         $val=$7;
1617                                 }
1618                                 elsif (defined $6) {
1619                                         $val=$6;
1620                                 }
1622                                 if (defined $key) {
1623                                         push @params, $key, $val;
1624                                 }
1625                                 else {
1626                                         push @params, $val, '';
1627                                 }
1628                         }
1629                         if ($preprocessing{$page}++ > 8) {
1630                                 # Avoid loops of preprocessed pages preprocessing
1631                                 # other pages that preprocess them, etc.
1632                                 return "[[!$command <span class=\"error\">".
1633                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1634                                                 $page, $preprocessing{$page}).
1635                                         "</span>]]";
1636                         }
1637                         my $ret;
1638                         if (! $scan) {
1639                                 $ret=eval {
1640                                         $hooks{preprocess}{$command}{call}->(
1641                                                 @params,
1642                                                 page => $page,
1643                                                 destpage => $destpage,
1644                                                 preview => $preprocess_preview,
1645                                         );
1646                                 };
1647                                 if ($@) {
1648                                         my $error=$@;
1649                                         chomp $error;
1650                                         eval q{use HTML::Entities};
1651                                         $error = encode_entities($error);
1652                                         $ret="[[!$command <span class=\"error\">".
1653                                                 gettext("Error").": $error"."</span>]]";
1654                                 }
1655                         }
1656                         else {
1657                                 # use void context during scan pass
1658                                 eval {
1659                                         $hooks{preprocess}{$command}{call}->(
1660                                                 @params,
1661                                                 page => $page,
1662                                                 destpage => $destpage,
1663                                                 preview => $preprocess_preview,
1664                                         );
1665                                 };
1666                                 $ret="";
1667                         }
1668                         $preprocessing{$page}--;
1669                         return $ret;
1670                 }
1671                 else {
1672                         return "[[$prefix$command $params]]";
1673                 }
1674         };
1675         
1676         my $regex;
1677         if ($config{prefix_directives}) {
1678                 $regex = qr{
1679                         (\\?)           # 1: escape?
1680                         \[\[(!)         # directive open; 2: prefix
1681                         ([-\w]+)        # 3: command
1682                         (               # 4: the parameters..
1683                                 \s+     # Must have space if parameters present
1684                                 (?:
1685                                         (?:[-.\w]+=)?           # named parameter key?
1686                                         (?:
1687                                                 """.*?"""       # triple-quoted value
1688                                                 |
1689                                                 "[^"]*?"        # single-quoted value
1690                                                 |
1691                                                 '''.*?'''       # triple-single-quote
1692                                                 |
1693                                                 <<([a-zA-Z]+)\n # 5: heredoc start
1694                                                 (?:.*?)\n\5     # heredoc value
1695                                                 |
1696                                                 [^"\s\]]+       # unquoted value
1697                                         )
1698                                         \s*                     # whitespace or end
1699                                                                 # of directive
1700                                 )
1701                         *)?             # 0 or more parameters
1702                         \]\]            # directive closed
1703                 }sx;
1704         }
1705         else {
1706                 $regex = qr{
1707                         (\\?)           # 1: escape?
1708                         \[\[(!?)        # directive open; 2: optional prefix
1709                         ([-\w]+)        # 3: command
1710                         \s+
1711                         (               # 4: the parameters..
1712                                 (?:
1713                                         (?:[-.\w]+=)?           # named parameter key?
1714                                         (?:
1715                                                 """.*?"""       # triple-quoted value
1716                                                 |
1717                                                 "[^"]*?"        # single-quoted value
1718                                                 |
1719                                                 '''.*?'''       # triple-single-quote
1720                                                 |
1721                                                 <<([a-zA-Z]+)\n # 5: heredoc start
1722                                                 (?:.*?)\n\5     # heredoc value
1723                                                 |
1724                                                 [^"\s\]]+       # unquoted value
1725                                         )
1726                                         \s*                     # whitespace or end
1727                                                                 # of directive
1728                                 )
1729                         *)              # 0 or more parameters
1730                         \]\]            # directive closed
1731                 }sx;
1732         }
1734         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1735         return $content;
1738 sub filter ($$$) {
1739         my $page=shift;
1740         my $destpage=shift;
1741         my $content=shift;
1743         run_hooks(filter => sub {
1744                 $content=shift->(page => $page, destpage => $destpage, 
1745                         content => $content);
1746         });
1748         return $content;
1751 sub check_canedit ($$$;$) {
1752         my $page=shift;
1753         my $q=shift;
1754         my $session=shift;
1755         my $nonfatal=shift;
1756         
1757         my $canedit;
1758         run_hooks(canedit => sub {
1759                 return if defined $canedit;
1760                 my $ret=shift->($page, $q, $session);
1761                 if (defined $ret) {
1762                         if ($ret eq "") {
1763                                 $canedit=1;
1764                         }
1765                         elsif (ref $ret eq 'CODE') {
1766                                 $ret->() unless $nonfatal;
1767                                 $canedit=0;
1768                         }
1769                         elsif (defined $ret) {
1770                                 error($ret) unless $nonfatal;
1771                                 $canedit=0;
1772                         }
1773                 }
1774         });
1775         return defined $canedit ? $canedit : 1;
1778 sub check_content (@) {
1779         my %params=@_;
1780         
1781         return 1 if ! exists $hooks{checkcontent}; # optimisation
1783         if (exists $pagesources{$params{page}}) {
1784                 my @diff;
1785                 my %old=map { $_ => 1 }
1786                         split("\n", readfile(srcfile($pagesources{$params{page}})));
1787                 foreach my $line (split("\n", $params{content})) {
1788                         push @diff, $line if ! exists $old{$line};
1789                 }
1790                 $params{diff}=join("\n", @diff);
1791         }
1793         my $ok;
1794         run_hooks(checkcontent => sub {
1795                 return if defined $ok;
1796                 my $ret=shift->(%params);
1797                 if (defined $ret) {
1798                         if ($ret eq "") {
1799                                 $ok=1;
1800                         }
1801                         elsif (ref $ret eq 'CODE') {
1802                                 $ret->() unless $params{nonfatal};
1803                                 $ok=0;
1804                         }
1805                         elsif (defined $ret) {
1806                                 error($ret) unless $params{nonfatal};
1807                                 $ok=0;
1808                         }
1809                 }
1811         });
1812         return defined $ok ? $ok : 1;
1815 sub check_canchange (@) {
1816         my %params = @_;
1817         my $cgi = $params{cgi};
1818         my $session = $params{session};
1819         my @changes = @{$params{changes}};
1821         my %newfiles;
1822         foreach my $change (@changes) {
1823                 # This untaint is safe because we check file_pruned and
1824                 # wiki_file_regexp.
1825                 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1826                 $file=possibly_foolish_untaint($file);
1827                 if (! defined $file || ! length $file ||
1828                     file_pruned($file)) {
1829                         error(gettext("bad file name %s"), $file);
1830                 }
1832                 my $type=pagetype($file);
1833                 my $page=pagename($file) if defined $type;
1835                 if ($change->{action} eq 'add') {
1836                         $newfiles{$file}=1;
1837                 }
1839                 if ($change->{action} eq 'change' ||
1840                     $change->{action} eq 'add') {
1841                         if (defined $page) {
1842                                 check_canedit($page, $cgi, $session);
1843                                 next;
1844                         }
1845                         else {
1846                                 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1847                                         IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1848                                         check_canedit($file, $cgi, $session);
1849                                         next;
1850                                 }
1851                         }
1852                 }
1853                 elsif ($change->{action} eq 'remove') {
1854                         # check_canremove tests to see if the file is present
1855                         # on disk. This will fail when a single commit adds a
1856                         # file and then removes it again. Avoid the problem
1857                         # by not testing the removal in such pairs of changes.
1858                         # (The add is still tested, just to make sure that
1859                         # no data is added to the repo that a web edit
1860                         # could not add.)
1861                         next if $newfiles{$file};
1863                         if (IkiWiki::Plugin::remove->can("check_canremove")) {
1864                                 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1865                                 check_canedit(defined $page ? $page : $file, $cgi, $session);
1866                                 next;
1867                         }
1868                 }
1869                 else {
1870                         error "unknown action ".$change->{action};
1871                 }
1873                 error sprintf(gettext("you are not allowed to change %s"), $file);
1874         }
1878 my $wikilock;
1880 sub lockwiki () {
1881         # Take an exclusive lock on the wiki to prevent multiple concurrent
1882         # run issues. The lock will be dropped on program exit.
1883         if (! -d $config{wikistatedir}) {
1884                 mkdir($config{wikistatedir});
1885         }
1886         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1887                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1888         if (! flock($wikilock, LOCK_EX | LOCK_NB)) {
1889                 debug("failed to get lock; waiting...");
1890                 if (! flock($wikilock, LOCK_EX)) {
1891                         error("failed to get lock");
1892                 }
1893         }
1894         return 1;
1897 sub unlockwiki () {
1898         POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1899         return close($wikilock) if $wikilock;
1900         return;
1903 my $commitlock;
1905 sub commit_hook_enabled () {
1906         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1907                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1908         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1909                 close($commitlock) || error("failed closing commitlock: $!");
1910                 return 0;
1911         }
1912         close($commitlock) || error("failed closing commitlock: $!");
1913         return 1;
1916 sub disable_commit_hook () {
1917         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1918                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1919         if (! flock($commitlock, 2)) { # LOCK_EX
1920                 error("failed to get commit lock");
1921         }
1922         return 1;
1925 sub enable_commit_hook () {
1926         return close($commitlock) if $commitlock;
1927         return;
1930 sub loadindex () {
1931         %oldrenderedfiles=%pagectime=();
1932         my $rebuild=$config{rebuild};
1933         if (! $rebuild) {
1934                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1935                 %destsources=%renderedfiles=%pagecase=%pagestate=
1936                 %depends_simple=%typedlinks=%oldtypedlinks=();
1937         }
1938         my $in;
1939         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1940                 if (-e "$config{wikistatedir}/index") {
1941                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1942                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1943                 }
1944                 else {
1945                         # gettime on first build
1946                         $config{gettime}=1 unless defined $config{gettime};
1947                         return;
1948                 }
1949         }
1951         my $index=Storable::fd_retrieve($in);
1952         if (! defined $index) {
1953                 return 0;
1954         }
1956         my $pages;
1957         if (exists $index->{version} && ! ref $index->{version}) {
1958                 $pages=$index->{page};
1959                 %wikistate=%{$index->{state}};
1960                 # Handle plugins that got disabled by loading a new setup.
1961                 if (exists $config{setupfile}) {
1962                         require IkiWiki::Setup;
1963                         IkiWiki::Setup::disabled_plugins(
1964                                 grep { ! $loaded_plugins{$_} } keys %wikistate);
1965                 }
1966         }
1967         else {
1968                 $pages=$index;
1969                 %wikistate=();
1970         }
1972         foreach my $src (keys %$pages) {
1973                 my $d=$pages->{$src};
1974                 my $page;
1975                 if (exists $d->{page} && ! $rebuild) {
1976                         $page=$d->{page};
1977                 }
1978                 else {
1979                         $page=pagename($src);
1980                 }
1981                 $pagectime{$page}=$d->{ctime};
1982                 $pagesources{$page}=$src;
1983                 if (! $rebuild) {
1984                         $pagemtime{$page}=$d->{mtime};
1985                         $renderedfiles{$page}=$d->{dest};
1986                         if (exists $d->{links} && ref $d->{links}) {
1987                                 $links{$page}=$d->{links};
1988                                 $oldlinks{$page}=[@{$d->{links}}];
1989                         }
1990                         if (ref $d->{depends_simple} eq 'ARRAY') {
1991                                 # old format
1992                                 $depends_simple{$page}={
1993                                         map { $_ => 1 } @{$d->{depends_simple}}
1994                                 };
1995                         }
1996                         elsif (exists $d->{depends_simple}) {
1997                                 $depends_simple{$page}=$d->{depends_simple};
1998                         }
1999                         if (exists $d->{dependslist}) {
2000                                 # old format
2001                                 $depends{$page}={
2002                                         map { $_ => $DEPEND_CONTENT }
2003                                                 @{$d->{dependslist}}
2004                                 };
2005                         }
2006                         elsif (exists $d->{depends} && ! ref $d->{depends}) {
2007                                 # old format
2008                                 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
2009                         }
2010                         elsif (exists $d->{depends}) {
2011                                 $depends{$page}=$d->{depends};
2012                         }
2013                         if (exists $d->{state}) {
2014                                 $pagestate{$page}=$d->{state};
2015                         }
2016                         if (exists $d->{typedlinks}) {
2017                                 $typedlinks{$page}=$d->{typedlinks};
2019                                 while (my ($type, $links) = each %{$typedlinks{$page}}) {
2020                                         next unless %$links;
2021                                         $oldtypedlinks{$page}{$type} = {%$links};
2022                                 }
2023                         }
2024                 }
2025                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
2026         }
2027         foreach my $page (keys %pagesources) {
2028                 $pagecase{lc $page}=$page;
2029         }
2030         foreach my $page (keys %renderedfiles) {
2031                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
2032         }
2033         $lastrev=$index->{lastrev};
2034         @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
2035         return close($in);
2038 sub saveindex () {
2039         run_hooks(savestate => sub { shift->() });
2041         my @plugins=keys %loaded_plugins;
2043         if (! -d $config{wikistatedir}) {
2044                 mkdir($config{wikistatedir});
2045         }
2046         my $newfile="$config{wikistatedir}/indexdb.new";
2047         my $cleanup = sub { unlink($newfile) };
2048         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
2050         my %index;
2051         foreach my $page (keys %pagemtime) {
2052                 next unless $pagemtime{$page};
2053                 my $src=$pagesources{$page};
2055                 $index{page}{$src}={
2056                         page => $page,
2057                         ctime => $pagectime{$page},
2058                         mtime => $pagemtime{$page},
2059                         dest => $renderedfiles{$page},
2060                         links => $links{$page},
2061                 };
2063                 if (exists $depends{$page}) {
2064                         $index{page}{$src}{depends} = $depends{$page};
2065                 }
2067                 if (exists $depends_simple{$page}) {
2068                         $index{page}{$src}{depends_simple} = $depends_simple{$page};
2069                 }
2071                 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
2072                         $index{page}{$src}{typedlinks} = $typedlinks{$page};
2073                 }
2075                 if (exists $pagestate{$page}) {
2076                         $index{page}{$src}{state}=$pagestate{$page};
2077                 }
2078         }
2080         $index{state}={};
2081         foreach my $id (@plugins) {
2082                 $index{state}{$id}={}; # used to detect disabled plugins
2083                 foreach my $key (keys %{$wikistate{$id}}) {
2084                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
2085                 }
2086         }
2087         
2088         $index{lastrev}=$lastrev;
2089         $index{underlayfiles}=\@underlayfiles;
2091         $index{version}="3";
2092         my $ret=Storable::nstore_fd(\%index, $out);
2093         return if ! defined $ret || ! $ret;
2094         close $out || error("failed saving to $newfile: $!", $cleanup);
2095         rename($newfile, "$config{wikistatedir}/indexdb") ||
2096                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
2097         
2098         return 1;
2101 sub template_file ($) {
2102         my $name=shift;
2103         
2104         my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
2105         my $template;
2106         if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
2107                 $template=srcfile($pagesources{$tpage}, 1);
2108                 $name.=".tmpl";
2109         }
2110         else {
2111                 $template=srcfile($tpage, 1);
2112         }
2114         if (defined $template) {
2115                 return $template, $tpage, 1 if wantarray;
2116                 return $template;
2117         }
2118         else {
2119                 $name=~s:/::; # avoid path traversal
2120                 foreach my $dir ($config{templatedir},
2121                                  "$installdir/share/ikiwiki/templates") {
2122                         if (-e "$dir/$name") {
2123                                 $template="$dir/$name";
2124                                 last;
2125                         }
2126                 }
2127                 if (defined $template) {        
2128                         return $template, $tpage if wantarray;
2129                         return $template;
2130                 }
2131         }
2133         return;
2136 sub template_depends ($$;@) {
2137         my $name=shift;
2138         my $page=shift;
2139         
2140         my ($filename, $tpage, $untrusted)=template_file($name);
2141         if (! defined $filename) {
2142                 error(sprintf(gettext("template %s not found"), $name))
2143         }
2145         if (defined $page && defined $tpage) {
2146                 add_depends($page, $tpage);
2147         }
2149         my @opts=(
2150                 filter => sub {
2151                         my $text_ref = shift;
2152                         ${$text_ref} = decode_utf8(${$text_ref});
2153                         run_hooks(readtemplate => sub {
2154                                 ${$text_ref} = shift->(
2155                                         id => $name,
2156                                         page => $tpage,
2157                                         content => ${$text_ref},
2158                                         untrusted => $untrusted,
2159                                 );
2160                         });
2161                 },
2162                 loop_context_vars => 1,
2163                 die_on_bad_params => 0,
2164                 parent_global_vars => 1,
2165                 filename => $filename,
2166                 @_,
2167                 ($untrusted ? (no_includes => 1) : ()),
2168         );
2169         return @opts if wantarray;
2171         require HTML::Template;
2172         return HTML::Template->new(@opts);
2175 sub template ($;@) {
2176         template_depends(shift, undef, @_);
2179 sub templateactions ($$) {
2180         my $template=shift;
2181         my $page=shift;
2183         my $have_actions=0;
2184         my @actions;
2185         run_hooks(pageactions => sub {
2186                 push @actions, map { { action => $_ } } 
2187                         grep { defined } shift->(page => $page);
2188         });
2189         $template->param(actions => \@actions);
2191         if ($config{cgiurl} && exists $hooks{auth}) {
2192                 $template->param(prefsurl => cgiurl(do => "prefs"));
2193                 $have_actions=1;
2194         }
2196         if ($have_actions || @actions) {
2197                 $template->param(have_actions => 1);
2198         }
2201 sub hook (@) {
2202         my %param=@_;
2203         
2204         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2205                 error 'hook requires type, call, and id parameters';
2206         }
2208         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2209         
2210         $hooks{$param{type}}{$param{id}}=\%param;
2211         return 1;
2214 sub run_hooks ($$) {
2215         # Calls the given sub for each hook of the given type,
2216         # passing it the hook function to call.
2217         my $type=shift;
2218         my $sub=shift;
2220         if (exists $hooks{$type}) {
2221                 my (@first, @middle, @last);
2222                 foreach my $id (keys %{$hooks{$type}}) {
2223                         if ($hooks{$type}{$id}{first}) {
2224                                 push @first, $id;
2225                         }
2226                         elsif ($hooks{$type}{$id}{last}) {
2227                                 push @last, $id;
2228                         }
2229                         else {
2230                                 push @middle, $id;
2231                         }
2232                 }
2233                 foreach my $id (@first, @middle, @last) {
2234                         $sub->($hooks{$type}{$id}{call});
2235                 }
2236         }
2238         return 1;
2241 sub rcs_update () {
2242         $hooks{rcs}{rcs_update}{call}->(@_);
2245 sub rcs_prepedit ($) {
2246         $hooks{rcs}{rcs_prepedit}{call}->(@_);
2249 sub rcs_commit (@) {
2250         $hooks{rcs}{rcs_commit}{call}->(@_);
2253 sub rcs_commit_staged (@) {
2254         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2257 sub rcs_add ($) {
2258         $hooks{rcs}{rcs_add}{call}->(@_);
2261 sub rcs_remove ($) {
2262         $hooks{rcs}{rcs_remove}{call}->(@_);
2265 sub rcs_rename ($$) {
2266         $hooks{rcs}{rcs_rename}{call}->(@_);
2269 sub rcs_recentchanges ($) {
2270         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2273 sub rcs_diff ($;$) {
2274         $hooks{rcs}{rcs_diff}{call}->(@_);
2277 sub rcs_getctime ($) {
2278         $hooks{rcs}{rcs_getctime}{call}->(@_);
2281 sub rcs_getmtime ($) {
2282         $hooks{rcs}{rcs_getmtime}{call}->(@_);
2285 sub rcs_receive () {
2286         $hooks{rcs}{rcs_receive}{call}->();
2289 sub add_depends ($$;$) {
2290         my $page=shift;
2291         my $pagespec=shift;
2292         my $deptype=shift || $DEPEND_CONTENT;
2294         # Is the pagespec a simple page name?
2295         if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2296             $pagespec !~ /[\s*?()!]/) {
2297                 $depends_simple{$page}{lc $pagespec} |= $deptype;
2298                 return 1;
2299         }
2301         # Add explicit dependencies for influences.
2302         my $sub=pagespec_translate($pagespec);
2303         return unless defined $sub;
2304         foreach my $p (keys %pagesources) {
2305                 my $r=$sub->($p, location => $page);
2306                 my $i=$r->influences;
2307                 my $static=$r->influences_static;
2308                 foreach my $k (keys %$i) {
2309                         next unless $r || $static || $k eq $page;
2310                         $depends_simple{$page}{lc $k} |= $i->{$k};
2311                 }
2312                 last if $static;
2313         }
2315         $depends{$page}{$pagespec} |= $deptype;
2316         return 1;
2319 sub deptype (@) {
2320         my $deptype=0;
2321         foreach my $type (@_) {
2322                 if ($type eq 'presence') {
2323                         $deptype |= $DEPEND_PRESENCE;
2324                 }
2325                 elsif ($type eq 'links') { 
2326                         $deptype |= $DEPEND_LINKS;
2327                 }
2328                 elsif ($type eq 'content') {
2329                         $deptype |= $DEPEND_CONTENT;
2330                 }
2331         }
2332         return $deptype;
2335 my $file_prune_regexp;
2336 sub file_pruned ($) {
2337         my $file=shift;
2339         if (defined $config{include} && length $config{include}) {
2340                 return 0 if $file =~ m/$config{include}/;
2341         }
2343         if (! defined $file_prune_regexp) {
2344                 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2345                 $file_prune_regexp=qr/$file_prune_regexp/;
2346         }
2347         return $file =~ m/$file_prune_regexp/;
2350 sub define_gettext () {
2351         # If translation is needed, redefine the gettext function to do it.
2352         # Otherwise, it becomes a quick no-op.
2353         my $gettext_obj;
2354         my $getobj;
2355         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2356             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2357             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2358                 $getobj=sub {
2359                         $gettext_obj=eval q{
2360                                 use Locale::gettext q{textdomain};
2361                                 Locale::gettext->domain('ikiwiki')
2362                         };
2363                 };
2364         }
2366         no warnings 'redefine';
2367         *gettext=sub {
2368                 $getobj->() if $getobj;
2369                 if ($gettext_obj) {
2370                         $gettext_obj->get(shift);
2371                 }
2372                 else {
2373                         return shift;
2374                 }
2375         };
2376         *ngettext=sub {
2377                 $getobj->() if $getobj;
2378                 if ($gettext_obj) {
2379                         $gettext_obj->nget(@_);
2380                 }
2381                 else {
2382                         return ($_[2] == 1 ? $_[0] : $_[1])
2383                 }
2384         };
2387 sub gettext {
2388         define_gettext();
2389         gettext(@_);
2392 sub ngettext {
2393         define_gettext();
2394         ngettext(@_);
2397 sub yesno ($) {
2398         my $val=shift;
2400         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2403 sub inject {
2404         # Injects a new function into the symbol table to replace an
2405         # exported function.
2406         my %params=@_;
2408         # This is deep ugly perl foo, beware.
2409         no strict;
2410         no warnings;
2411         if (! defined $params{parent}) {
2412                 $params{parent}='::';
2413                 $params{old}=\&{$params{name}};
2414                 $params{name}=~s/.*:://;
2415         }
2416         my $parent=$params{parent};
2417         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2418                 $ns = $params{parent} . $ns;
2419                 inject(%params, parent => $ns) unless $ns eq '::main::';
2420                 *{$ns . $params{name}} = $params{call}
2421                         if exists ${$ns}{$params{name}} &&
2422                            \&{${$ns}{$params{name}}} == $params{old};
2423         }
2424         use strict;
2425         use warnings;
2428 sub add_link ($$;$) {
2429         my $page=shift;
2430         my $link=shift;
2431         my $type=shift;
2433         push @{$links{$page}}, $link
2434                 unless grep { $_ eq $link } @{$links{$page}};
2436         if (defined $type) {
2437                 $typedlinks{$page}{$type}{$link} = 1;
2438         }
2441 sub add_autofile ($$$) {
2442         my $file=shift;
2443         my $plugin=shift;
2444         my $generator=shift;
2445         
2446         $autofiles{$file}{plugin}=$plugin;
2447         $autofiles{$file}{generator}=$generator;
2450 sub useragent () {
2451         return LWP::UserAgent->new(
2452                 cookie_jar => $config{cookiejar},
2453                 env_proxy => 1,         # respect proxy env vars
2454                 agent => $config{useragent},
2455         );
2458 sub sortspec_translate ($$) {
2459         my $spec = shift;
2460         my $reverse = shift;
2462         my $code = "";
2463         my @data;
2464         while ($spec =~ m{
2465                 \s*
2466                 (-?)            # group 1: perhaps negated
2467                 \s*
2468                 (               # group 2: a word
2469                         \w+\([^\)]*\)   # command(params)
2470                         |
2471                         [^\s]+          # or anything else
2472                 )
2473                 \s*
2474         }gx) {
2475                 my $negated = $1;
2476                 my $word = $2;
2477                 my $params = undef;
2479                 if ($word =~ m/^(\w+)\((.*)\)$/) {
2480                         # command with parameters
2481                         $params = $2;
2482                         $word = $1;
2483                 }
2484                 elsif ($word !~ m/^\w+$/) {
2485                         error(sprintf(gettext("invalid sort type %s"), $word));
2486                 }
2488                 if (length $code) {
2489                         $code .= " || ";
2490                 }
2492                 if ($negated) {
2493                         $code .= "-";
2494                 }
2496                 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2497                         if (defined $params) {
2498                                 push @data, $params;
2499                                 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2500                         }
2501                         else {
2502                                 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2503                         }
2504                 }
2505                 else {
2506                         error(sprintf(gettext("unknown sort type %s"), $word));
2507                 }
2508         }
2510         if (! length $code) {
2511                 # undefined sorting method... sort arbitrarily
2512                 return sub { 0 };
2513         }
2515         if ($reverse) {
2516                 $code="-($code)";
2517         }
2519         no warnings;
2520         return eval 'sub { '.$code.' }';
2523 sub pagespec_translate ($) {
2524         my $spec=shift;
2526         # Convert spec to perl code.
2527         my $code="";
2528         my @data;
2529         while ($spec=~m{
2530                 \s*             # ignore whitespace
2531                 (               # 1: match a single word
2532                         \!              # !
2533                 |
2534                         \(              # (
2535                 |
2536                         \)              # )
2537                 |
2538                         \w+\([^\)]*\)   # command(params)
2539                 |
2540                         [^\s()]+        # any other text
2541                 )
2542                 \s*             # ignore whitespace
2543         }gx) {
2544                 my $word=$1;
2545                 if (lc $word eq 'and') {
2546                         $code.=' &';
2547                 }
2548                 elsif (lc $word eq 'or') {
2549                         $code.=' |';
2550                 }
2551                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2552                         $code.=' '.$word;
2553                 }
2554                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2555                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2556                                 push @data, $2;
2557                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2558                         }
2559                         else {
2560                                 push @data, qq{unknown function in pagespec "$word"};
2561                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2562                         }
2563                 }
2564                 else {
2565                         push @data, $word;
2566                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2567                 }
2568         }
2570         if (! length $code) {
2571                 $code="IkiWiki::FailReason->new('empty pagespec')";
2572         }
2574         no warnings;
2575         return eval 'sub { my $page=shift; '.$code.' }';
2578 sub pagespec_match ($$;@) {
2579         my $page=shift;
2580         my $spec=shift;
2581         my @params=@_;
2583         # Backwards compatability with old calling convention.
2584         if (@params == 1) {
2585                 unshift @params, 'location';
2586         }
2588         my $sub=pagespec_translate($spec);
2589         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2590                 if ! defined $sub;
2591         return $sub->($page, @params);
2594 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2596 # Not exported yet, but could be in future if it is generally useful.
2597 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2598 # which is "more internal".
2599 sub sort_pages ($$;@) {
2600         my $sort = shift;
2601         my $list = shift;
2602         my %params = @_;
2603         $sort = sortspec_translate($sort, $params{reverse});
2604         return IkiWiki::SortSpec::sort_pages($sort, @$list);
2607 sub pagespec_match_list ($$;@) {
2608         my $page=shift;
2609         my $pagespec=shift;
2610         my %params=@_;
2612         # Backwards compatability with old calling convention.
2613         if (ref $page) {
2614                 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2615                 $params{list}=$page;
2616                 $page=$params{location}; # ugh!
2617         }
2619         my $sub=pagespec_translate($pagespec);
2620         error "syntax error in pagespec \"$pagespec\""
2621                 if ! defined $sub;
2622         my $sort=sortspec_translate($params{sort}, $params{reverse})
2623                 if defined $params{sort};
2625         my @candidates;
2626         if (exists $params{list}) {
2627                 @candidates=exists $params{filter}
2628                         ? grep { ! $params{filter}->($_) } @{$params{list}}
2629                         : @{$params{list}};
2630         }
2631         else {
2632                 @candidates=exists $params{filter}
2633                         ? grep { ! $params{filter}->($_) } keys %pagesources
2634                         : keys %pagesources;
2635         }
2636         
2637         # clear params, remainder is passed to pagespec
2638         $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2639         my $num=$params{num};
2640         delete @params{qw{num deptype reverse sort filter list}};
2641         
2642         # when only the top matches will be returned, it's efficient to
2643         # sort before matching to pagespec,
2644         if (defined $num && defined $sort) {
2645                 @candidates=IkiWiki::SortSpec::sort_pages(
2646                         $sort, @candidates);
2647         }
2648         
2649         my @matches;
2650         my $firstfail;
2651         my $count=0;
2652         my $accum=IkiWiki::SuccessReason->new();
2653         foreach my $p (@candidates) {
2654                 my $r=$sub->($p, %params, location => $page);
2655                 error(sprintf(gettext("cannot match pages: %s"), $r))
2656                         if $r->isa("IkiWiki::ErrorReason");
2657                 unless ($r || $r->influences_static) {
2658                         $r->remove_influence($p);
2659                 }
2660                 $accum |= $r;
2661                 if ($r) {
2662                         push @matches, $p;
2663                         last if defined $num && ++$count == $num;
2664                 }
2665         }
2667         # Add simple dependencies for accumulated influences.
2668         my $i=$accum->influences;
2669         foreach my $k (keys %$i) {
2670                 $depends_simple{$page}{lc $k} |= $i->{$k};
2671         }
2673         # when all matches will be returned, it's efficient to
2674         # sort after matching
2675         if (! defined $num && defined $sort) {
2676                 return IkiWiki::SortSpec::sort_pages(
2677                         $sort, @matches);
2678         }
2679         else {
2680                 return @matches;
2681         }
2684 sub pagespec_valid ($) {
2685         my $spec=shift;
2687         return defined pagespec_translate($spec);
2690 sub glob2re ($) {
2691         my $re=quotemeta(shift);
2692         $re=~s/\\\*/.*/g;
2693         $re=~s/\\\?/./g;
2694         return qr/^$re$/i;
2697 package IkiWiki::FailReason;
2699 use overload (
2700         '""'    => sub { $_[0][0] },
2701         '0+'    => sub { 0 },
2702         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2703         '&'     => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2704         '|'     => sub { $_[1]->merge_influences($_[0]); $_[1] },
2705         fallback => 1,
2706 );
2708 our @ISA = 'IkiWiki::SuccessReason';
2710 package IkiWiki::SuccessReason;
2712 # A blessed array-ref:
2714 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2715 # [1]{""}:
2716 #      - if absent or false, the influences of this evaluation are "static",
2717 #        see the influences_static method
2718 #      - if true, they are dynamic (not static)
2719 # [1]{any other key}:
2720 #      the dependency types of influences, as returned by the influences method
2722 use overload (
2723         # in string context, it's the human-readable reason
2724         '""'    => sub { $_[0][0] },
2725         # in boolean context, SuccessReason is 1 and FailReason is 0
2726         '0+'    => sub { 1 },
2727         # negating a result gives the opposite result with the same influences
2728         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
2729         # A & B = (A ? B : A) with the influences of both
2730         '&'     => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2731         # A | B = (A ? A : B) with the influences of both
2732         '|'     => sub { $_[0]->merge_influences($_[1]); $_[0] },
2733         fallback => 1,
2734 );
2736 # SuccessReason->new("human-readable reason", page => deptype, ...)
2738 sub new {
2739         my $class = shift;
2740         my $value = shift;
2741         return bless [$value, {@_}], $class;
2744 # influences(): return a reference to a copy of the hash
2745 # { page => dependency type } describing the pages that indirectly influenced
2746 # this result, but would not cause a dependency through ikiwiki's core
2747 # dependency logic.
2749 # See [[todo/dependency_types]] for extensive discussion of what this means.
2751 # influences(page => deptype, ...): remove all influences, replace them
2752 # with the arguments, and return a reference to a copy of the new influences.
2754 sub influences {
2755         my $this=shift;
2756         $this->[1]={@_} if @_;
2757         my %i=%{$this->[1]};
2758         delete $i{""};
2759         return \%i;
2762 # True if this result has the same influences whichever page it matches,
2763 # For instance, whether bar matches backlink(foo) is influenced only by
2764 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2765 # which does not mention bar anywhere.
2767 # False if this result would have different influences when matching
2768 # different pages. For instance, when testing whether link(foo) matches bar,
2769 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2770 # bar's links could change the outcome; so its influences are not the same
2771 # as when testing whether link(foo) matches baz.
2773 # Static influences are one of the things that make pagespec_match_list
2774 # more efficient than repeated calls to pagespec_match.
2776 sub influences_static {
2777         return ! $_[0][1]->{""};
2780 # Change the influences of $this to be the influences of "$this & $other"
2781 # or "$this | $other".
2783 # If both $this and $other are either successful or have influences,
2784 # or this is an "or" operation, the result has all the influences from
2785 # either of the arguments. It has dynamic influences if either argument
2786 # has dynamic influences.
2788 # If this is an "and" operation, and at least one argument is a
2789 # FailReason with no influences, the result has no influences, and they
2790 # are not dynamic. For instance, link(foo) matching bar is influenced
2791 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2792 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2793 # bar, because it would be false however often you edit bar.
2795 sub merge_influences {
2796         my $this=shift;
2797         my $other=shift;
2798         my $anded=shift;
2800         # This "if" is odd because it needs to avoid negating $this
2801         # or $other, which would alter the objects in-place. Be careful.
2802         if (! $anded || (($this || %{$this->[1]}) &&
2803                          ($other || %{$other->[1]}))) {
2804                 foreach my $influence (keys %{$other->[1]}) {
2805                         $this->[1]{$influence} |= $other->[1]{$influence};
2806                 }
2807         }
2808         else {
2809                 # influence blocker
2810                 $this->[1]={};
2811         }
2814 # Change $this so it is not considered to be influenced by $torm.
2816 sub remove_influence {
2817         my $this=shift;
2818         my $torm=shift;
2820         delete $this->[1]{$torm};
2823 package IkiWiki::ErrorReason;
2825 our @ISA = 'IkiWiki::FailReason';
2827 package IkiWiki::PageSpec;
2829 sub derel ($$) {
2830         my $path=shift;
2831         my $from=shift;
2833         if ($path =~ m!^\.(/|$)!) {
2834                 if ($1) {
2835                         $from=~s#/?[^/]+$## if defined $from;
2836                         $path=~s#^\./##;
2837                         $path="$from/$path" if defined $from && length $from;
2838                 }
2839                 else {
2840                         $path = $from;
2841                         $path = "" unless defined $path;
2842                 }
2843         }
2845         return $path;
2848 my %glob_cache;
2850 sub match_glob ($$;@) {
2851         my $page=shift;
2852         my $glob=shift;
2853         my %params=@_;
2854         
2855         $glob=derel($glob, $params{location});
2857         # Instead of converting the glob to a regex every time,
2858         # cache the compiled regex to save time.
2859         my $re=$glob_cache{$glob};
2860         unless (defined $re) {
2861                 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2862         }
2863         if ($page =~ $re) {
2864                 if (! IkiWiki::isinternal($page) || $params{internal}) {
2865                         return IkiWiki::SuccessReason->new("$glob matches $page");
2866                 }
2867                 else {
2868                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2869                 }
2870         }
2871         else {
2872                 return IkiWiki::FailReason->new("$glob does not match $page");
2873         }
2876 sub match_internal ($$;@) {
2877         return match_glob(shift, shift, @_, internal => 1)
2880 sub match_page ($$;@) {
2881         my $page=shift;
2882         my $match=match_glob($page, shift, @_);
2883         if ($match) {
2884                 my $source=exists $IkiWiki::pagesources{$page} ?
2885                         $IkiWiki::pagesources{$page} :
2886                         $IkiWiki::delpagesources{$page};
2887                 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2888                 if (! defined $type) {  
2889                         return IkiWiki::FailReason->new("$page is not a page");
2890                 }
2891         }
2892         return $match;
2895 sub match_link ($$;@) {
2896         my $page=shift;
2897         my $link=lc(shift);
2898         my %params=@_;
2900         $link=derel($link, $params{location});
2901         my $from=exists $params{location} ? $params{location} : '';
2902         my $linktype=$params{linktype};
2903         my $qualifier='';
2904         if (defined $linktype) {
2905                 $qualifier=" with type $linktype";
2906         }
2908         my $links = $IkiWiki::links{$page};
2909         return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2910                 unless $links && @{$links};
2911         my $bestlink = IkiWiki::bestlink($from, $link);
2912         foreach my $p (@{$links}) {
2913                 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2915                 if (length $bestlink) {
2916                         if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2917                                 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2918                         }
2919                 }
2920                 else {
2921                         if (match_glob($p, $link, %params)) {
2922                                 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2923                         }
2924                         my ($p_rel)=$p=~/^\/?(.*)/;
2925                         $link=~s/^\///;
2926                         if (match_glob($p_rel, $link, %params)) {
2927                                 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2928                         }
2929                 }
2930         }
2931         return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2934 sub match_backlink ($$;@) {
2935         my $page=shift;
2936         my $testpage=shift;
2937         my %params=@_;
2938         if ($testpage eq '.') {
2939                 $testpage = $params{'location'}
2940         }
2941         my $ret=match_link($testpage, $page, @_);
2942         $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2943         return $ret;
2946 sub match_created_before ($$;@) {
2947         my $page=shift;
2948         my $testpage=shift;
2949         my %params=@_;
2950         
2951         $testpage=derel($testpage, $params{location});
2953         if (exists $IkiWiki::pagectime{$testpage}) {
2954                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2955                         return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2956                 }
2957                 else {
2958                         return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2959                 }
2960         }
2961         else {
2962                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2963         }
2966 sub match_created_after ($$;@) {
2967         my $page=shift;
2968         my $testpage=shift;
2969         my %params=@_;
2970         
2971         $testpage=derel($testpage, $params{location});
2973         if (exists $IkiWiki::pagectime{$testpage}) {
2974                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2975                         return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2976                 }
2977                 else {
2978                         return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2979                 }
2980         }
2981         else {
2982                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2983         }
2986 sub match_creation_day ($$;@) {
2987         my $page=shift;
2988         my $d=shift;
2989         if ($d !~ /^\d+$/) {
2990                 return IkiWiki::ErrorReason->new("invalid day $d");
2991         }
2992         if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2993                 return IkiWiki::SuccessReason->new('creation_day matched');
2994         }
2995         else {
2996                 return IkiWiki::FailReason->new('creation_day did not match');
2997         }
3000 sub match_creation_month ($$;@) {
3001         my $page=shift;
3002         my $m=shift;
3003         if ($m !~ /^\d+$/) {
3004                 return IkiWiki::ErrorReason->new("invalid month $m");
3005         }
3006         if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
3007                 return IkiWiki::SuccessReason->new('creation_month matched');
3008         }
3009         else {
3010                 return IkiWiki::FailReason->new('creation_month did not match');
3011         }
3014 sub match_creation_year ($$;@) {
3015         my $page=shift;
3016         my $y=shift;
3017         if ($y !~ /^\d+$/) {
3018                 return IkiWiki::ErrorReason->new("invalid year $y");
3019         }
3020         if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
3021                 return IkiWiki::SuccessReason->new('creation_year matched');
3022         }
3023         else {
3024                 return IkiWiki::FailReason->new('creation_year did not match');
3025         }
3028 sub match_user ($$;@) {
3029         shift;
3030         my $user=shift;
3031         my %params=@_;
3032         
3033         if (! exists $params{user}) {
3034                 return IkiWiki::ErrorReason->new("no user specified");
3035         }
3037         my $regexp=IkiWiki::glob2re($user);
3038         
3039         if (defined $params{user} && $params{user}=~$regexp) {
3040                 return IkiWiki::SuccessReason->new("user is $user");
3041         }
3042         elsif (! defined $params{user}) {
3043                 return IkiWiki::FailReason->new("not logged in");
3044         }
3045         else {
3046                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
3047         }
3050 sub match_admin ($$;@) {
3051         shift;
3052         shift;
3053         my %params=@_;
3054         
3055         if (! exists $params{user}) {
3056                 return IkiWiki::ErrorReason->new("no user specified");
3057         }
3059         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
3060                 return IkiWiki::SuccessReason->new("user is an admin");
3061         }
3062         elsif (! defined $params{user}) {
3063                 return IkiWiki::FailReason->new("not logged in");
3064         }
3065         else {
3066                 return IkiWiki::FailReason->new("user is not an admin");
3067         }
3070 sub match_ip ($$;@) {
3071         shift;
3072         my $ip=shift;
3073         my %params=@_;
3074         
3075         if (! exists $params{ip}) {
3076                 return IkiWiki::ErrorReason->new("no IP specified");
3077         }
3078         
3079         my $regexp=IkiWiki::glob2re(lc $ip);
3081         if (defined $params{ip} && lc $params{ip}=~$regexp) {
3082                 return IkiWiki::SuccessReason->new("IP is $ip");
3083         }
3084         else {
3085                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
3086         }
3089 package IkiWiki::SortSpec;
3091 # This is in the SortSpec namespace so that the $a and $b that sort() uses
3092 # are easily available in this namespace, for cmp functions to use them.
3093 sub sort_pages {
3094         my $f=shift;
3095         sort $f @_
3098 sub cmp_title {
3099         IkiWiki::pagetitle(IkiWiki::basename($a))
3100         cmp
3101         IkiWiki::pagetitle(IkiWiki::basename($b))
3104 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
3105 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
3106 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }