]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki.pm
img: stop ImageMagick trying to be clever if filenames contain a colon
[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                         # keep a copy to avoid editing the original config repeatedly
847                         my $wikiname = $config{wikiname};
848                         utf8::encode($wikiname);
849                         Sys::Syslog::syslog($type, "[$wikiname] %s", join(" ", @_));
850                 };
851                 if ($@) {
852                     print STDERR "failed to syslog: $@" unless $log_failed;
853                     $log_failed=1;
854                     print STDERR "@_\n";
855                 }
856                 return $@;
857         }
858         elsif (! $config{cgi}) {
859                 return print "@_\n";
860         }
861         else {
862                 return print STDERR "@_\n";
863         }
866 sub possibly_foolish_untaint ($) {
867         my $tainted=shift;
868         my ($untainted)=$tainted=~/(.*)/s;
869         return $untainted;
872 sub basename ($) {
873         my $file=shift;
875         $file=~s!.*/+!!;
876         return $file;
879 sub dirname ($) {
880         my $file=shift;
882         $file=~s!/*[^/]+$!!;
883         return $file;
886 sub isinternal ($) {
887         my $page=shift;
888         return exists $pagesources{$page} &&
889                 $pagesources{$page} =~ /\._([^.]+)$/;
892 sub pagetype ($) {
893         my $file=shift;
894         
895         if ($file =~ /\.([^.]+)$/) {
896                 return $1 if exists $hooks{htmlize}{$1};
897         }
898         my $base=basename($file);
899         if (exists $hooks{htmlize}{$base} &&
900             $hooks{htmlize}{$base}{noextension}) {
901                 return $base;
902         }
903         return;
906 my %pagename_cache;
908 sub pagename ($) {
909         my $file=shift;
911         if (exists $pagename_cache{$file}) {
912                 return $pagename_cache{$file};
913         }
915         my $type=pagetype($file);
916         my $page=$file;
917         $page=~s/\Q.$type\E*$//
918                 if defined $type && !$hooks{htmlize}{$type}{keepextension}
919                         && !$hooks{htmlize}{$type}{noextension};
920         if ($config{indexpages} && $page=~/(.*)\/index$/) {
921                 $page=$1;
922         }
924         $pagename_cache{$file} = $page;
925         return $page;
928 sub newpagefile ($$) {
929         my $page=shift;
930         my $type=shift;
932         if (! $config{indexpages} || $page eq 'index') {
933                 return $page.".".$type;
934         }
935         else {
936                 return $page."/index.".$type;
937         }
940 sub targetpage ($$;$) {
941         my $page=shift;
942         my $ext=shift;
943         my $filename=shift;
944         
945         if (defined $filename) {
946                 return $page."/".$filename.".".$ext;
947         }
948         elsif (! $config{usedirs} || $page eq 'index') {
949                 return $page.".".$ext;
950         }
951         else {
952                 return $page."/index.".$ext;
953         }
956 sub htmlpage ($) {
957         my $page=shift;
958         
959         return targetpage($page, $config{htmlext});
962 sub srcfile_stat {
963         my $file=shift;
964         my $nothrow=shift;
966         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
967         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
968                 return "$dir/$file", stat(_) if -e "$dir/$file";
969         }
970         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
971         return;
974 sub srcfile ($;$) {
975         return (srcfile_stat(@_))[0];
978 sub add_literal_underlay ($) {
979         my $dir=shift;
981         if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
982                 unshift @{$config{underlaydirs}}, $dir;
983         }
986 sub add_underlay ($) {
987         my $dir = shift;
989         if ($dir !~ /^\//) {
990                 $dir="$config{underlaydirbase}/$dir";
991         }
993         add_literal_underlay($dir);
994         # why does it return 1? we just don't know
995         return 1;
998 sub readfile ($;$$) {
999         my $file=shift;
1000         my $binary=shift;
1001         my $wantfd=shift;
1003         if (-l $file) {
1004                 error("cannot read a symlink ($file)");
1005         }
1006         
1007         local $/=undef;
1008         open (my $in, "<", $file) || error("failed to read $file: $!");
1009         binmode($in) if ($binary);
1010         return \*$in if $wantfd;
1011         my $ret=<$in>;
1012         # check for invalid utf-8, and toss it back to avoid crashes
1013         if (! utf8::valid($ret)) {
1014                 $ret=encode_utf8($ret);
1015         }
1016         close $in || error("failed to read $file: $!");
1017         return $ret;
1020 sub prep_writefile ($$) {
1021         my $file=shift;
1022         my $destdir=shift;
1023         
1024         my $test=$file;
1025         while (length $test) {
1026                 if (-l "$destdir/$test") {
1027                         error("cannot write to a symlink ($test)");
1028                 }
1029                 if (-f _ && $test ne $file) {
1030                         # Remove conflicting file.
1031                         foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1032                                 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1033                                         if ($f eq $test) {
1034                                                 unlink("$destdir/$test");
1035                                                 last;
1036                                         }
1037                                 }
1038                         }
1039                 }
1040                 $test=dirname($test);
1041         }
1043         my $dir=dirname("$destdir/$file");
1044         if (! -d $dir) {
1045                 my $d="";
1046                 foreach my $s (split(m!/+!, $dir)) {
1047                         $d.="$s/";
1048                         if (! -d $d) {
1049                                 mkdir($d) || error("failed to create directory $d: $!");
1050                         }
1051                 }
1052         }
1054         return 1;
1057 sub writefile ($$$;$$) {
1058         my $file=shift; # can include subdirs
1059         my $destdir=shift; # directory to put file in
1060         my $content=shift;
1061         my $binary=shift;
1062         my $writer=shift;
1063         
1064         prep_writefile($file, $destdir);
1065         
1066         my $newfile="$destdir/$file.ikiwiki-new";
1067         if (-l $newfile) {
1068                 error("cannot write to a symlink ($newfile)");
1069         }
1070         
1071         my $cleanup = sub { unlink($newfile) };
1072         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
1073         binmode($out) if ($binary);
1074         if ($writer) {
1075                 $writer->(\*$out, $cleanup);
1076         }
1077         else {
1078                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
1079         }
1080         close $out || error("failed saving $newfile: $!", $cleanup);
1081         rename($newfile, "$destdir/$file") || 
1082                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
1084         return 1;
1087 my %cleared;
1088 sub will_render ($$;$) {
1089         my $page=shift;
1090         my $dest=shift;
1091         my $clear=shift;
1093         # Important security check for independently created files.
1094         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
1095             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
1096                 my $from_other_page=0;
1097                 # Expensive, but rarely runs.
1098                 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1099                         if (grep {
1100                                 $_ eq $dest ||
1101                                 dirname($_) eq $dest
1102                             } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1103                                 $from_other_page=1;
1104                                 last;
1105                         }
1106                 }
1108                 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
1109                         unless $from_other_page;
1110         }
1112         # If $dest exists as a directory, remove conflicting files in it
1113         # rendered from other pages.
1114         if (-d _) {
1115                 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
1116                         foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
1117                                 if (dirname($f) eq $dest) {
1118                                         unlink("$config{destdir}/$f");
1119                                         rmdir(dirname("$config{destdir}/$f"));
1120                                 }
1121                         }
1122                 }
1123         }
1125         if (! $clear || $cleared{$page}) {
1126                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
1127         }
1128         else {
1129                 foreach my $old (@{$renderedfiles{$page}}) {
1130                         delete $destsources{$old};
1131                 }
1132                 $renderedfiles{$page}=[$dest];
1133                 $cleared{$page}=1;
1134         }
1135         $destsources{$dest}=$page;
1137         return 1;
1140 sub bestlink ($$) {
1141         my $page=shift;
1142         my $link=shift;
1143         
1144         my $cwd=$page;
1145         if ($link=~s/^\/+//) {
1146                 # absolute links
1147                 $cwd="";
1148         }
1149         $link=~s/\/$//;
1151         do {
1152                 my $l=$cwd;
1153                 $l.="/" if length $l;
1154                 $l.=$link;
1156                 if (exists $pagesources{$l}) {
1157                         return $l;
1158                 }
1159                 elsif (exists $pagecase{lc $l}) {
1160                         return $pagecase{lc $l};
1161                 }
1162         } while $cwd=~s{/?[^/]+$}{};
1164         if (length $config{userdir}) {
1165                 my $l = "$config{userdir}/".lc($link);
1166                 if (exists $pagesources{$l}) {
1167                         return $l;
1168                 }
1169                 elsif (exists $pagecase{lc $l}) {
1170                         return $pagecase{lc $l};
1171                 }
1172         }
1174         #print STDERR "warning: page $page, broken link: $link\n";
1175         return "";
1178 sub isinlinableimage ($) {
1179         my $file=shift;
1180         
1181         return $file =~ /\.(png|gif|jpg|jpeg|svg)$/i;
1184 sub pagetitle ($;$) {
1185         my $page=shift;
1186         my $unescaped=shift;
1188         if ($unescaped) {
1189                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1190         }
1191         else {
1192                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1193         }
1195         return $page;
1198 sub titlepage ($) {
1199         my $title=shift;
1200         # support use w/o %config set
1201         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1202         $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1203         return $title;
1206 sub linkpage ($) {
1207         my $link=shift;
1208         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1209         $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1210         return $link;
1213 sub cgiurl (@) {
1214         my %params=@_;
1216         my $cgiurl=$local_cgiurl;
1218         if (exists $params{cgiurl}) {
1219                 $cgiurl=$params{cgiurl};
1220                 delete $params{cgiurl};
1221         }
1223         unless (%params) {
1224                 return $cgiurl;
1225         }
1227         return $cgiurl."?".
1228                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), sort(keys %params));
1231 sub cgiurl_abs (@) {
1232         eval q{use URI};
1233         URI->new_abs(cgiurl(@_), $config{cgiurl});
1236 sub baseurl (;$) {
1237         my $page=shift;
1239         return $local_url if ! defined $page;
1240         
1241         $page=htmlpage($page);
1242         $page=~s/[^\/]+$//;
1243         $page=~s/[^\/]+\//..\//g;
1244         return $page;
1247 sub urlabs ($$) {
1248         my $url=shift;
1249         my $urlbase=shift;
1251         return $url unless defined $urlbase && length $urlbase;
1253         eval q{use URI};
1254         URI->new_abs($url, $urlbase)->as_string;
1257 sub abs2rel ($$) {
1258         # Work around very innefficient behavior in File::Spec if abs2rel
1259         # is passed two relative paths. It's much faster if paths are
1260         # absolute! (Debian bug #376658; fixed in debian unstable now)
1261         my $path="/".shift;
1262         my $base="/".shift;
1264         require File::Spec;
1265         my $ret=File::Spec->abs2rel($path, $base);
1266         $ret=~s/^// if defined $ret;
1267         return $ret;
1270 sub displaytime ($;$$) {
1271         # Plugins can override this function to mark up the time to
1272         # display.
1273         my $time=formattime($_[0], $_[1]);
1274         if ($config{html5}) {
1275                 return '<time datetime="'.date_3339($_[0]).'"'.
1276                         ($_[2] ? ' pubdate="pubdate"' : '').
1277                         '>'.$time.'</time>';
1278         }
1279         else {
1280                 return '<span class="date">'.$time.'</span>';
1281         }
1284 sub formattime ($;$) {
1285         # Plugins can override this function to format the time.
1286         my $time=shift;
1287         my $format=shift;
1288         if (! defined $format) {
1289                 $format=$config{timeformat};
1290         }
1292         return strftime_utf8($format, localtime($time));
1295 my $strftime_encoding;
1296 sub strftime_utf8 {
1297         # strftime doesn't know about encodings, so make sure
1298         # its output is properly treated as utf8.
1299         # Note that this does not handle utf-8 in the format string.
1300         ($strftime_encoding) = POSIX::setlocale(&POSIX::LC_TIME) =~ m#\.([^@]+)#
1301                 unless defined $strftime_encoding;
1302         $strftime_encoding
1303                 ? Encode::decode($strftime_encoding, POSIX::strftime(@_))
1304                 : POSIX::strftime(@_);
1307 sub date_3339 ($) {
1308         my $time=shift;
1310         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1311         POSIX::setlocale(&POSIX::LC_TIME, "C");
1312         my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1313         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1314         return $ret;
1317 sub beautify_urlpath ($) {
1318         my $url=shift;
1320         # Ensure url is not an empty link, and if necessary,
1321         # add ./ to avoid colon confusion.
1322         if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1323                 $url="./$url";
1324         }
1326         if ($config{usedirs}) {
1327                 $url =~ s!/index.$config{htmlext}$!/!;
1328         }
1330         return $url;
1333 sub urlto ($;$$) {
1334         my $to=shift;
1335         my $from=shift;
1336         my $absolute=shift;
1337         
1338         if (! length $to) {
1339                 $to = 'index';
1340         }
1342         if (! $destsources{$to}) {
1343                 $to=htmlpage($to);
1344         }
1346         if ($absolute) {
1347                 return $config{url}.beautify_urlpath("/".$to);
1348         }
1350         if (! defined $from) {
1351                 my $u = $local_url || '';
1352                 $u =~ s{/$}{};
1353                 return $u.beautify_urlpath("/".$to);
1354         }
1356         my $link = abs2rel($to, dirname(htmlpage($from)));
1358         return beautify_urlpath($link);
1361 sub isselflink ($$) {
1362         # Plugins can override this function to support special types
1363         # of selflinks.
1364         my $page=shift;
1365         my $link=shift;
1367         return $page eq $link;
1370 sub htmllink ($$$;@) {
1371         my $lpage=shift; # the page doing the linking
1372         my $page=shift; # the page that will contain the link (different for inline)
1373         my $link=shift;
1374         my %opts=@_;
1376         $link=~s/\/$//;
1378         my $bestlink;
1379         if (! $opts{forcesubpage}) {
1380                 $bestlink=bestlink($lpage, $link);
1381         }
1382         else {
1383                 $bestlink="$lpage/".lc($link);
1384         }
1386         my $linktext;
1387         if (defined $opts{linktext}) {
1388                 $linktext=$opts{linktext};
1389         }
1390         else {
1391                 $linktext=pagetitle(basename($link));
1392         }
1393         
1394         return "<span class=\"selflink\">$linktext</span>"
1395                 if length $bestlink && isselflink($page, $bestlink) &&
1396                    ! defined $opts{anchor};
1397         
1398         if (! $destsources{$bestlink}) {
1399                 $bestlink=htmlpage($bestlink);
1401                 if (! $destsources{$bestlink}) {
1402                         my $cgilink = "";
1403                         if (length $config{cgiurl}) {
1404                                 $cgilink = "<a href=\"".
1405                                         cgiurl(
1406                                                 do => "create",
1407                                                 page => $link,
1408                                                 from => $lpage
1409                                         )."\" rel=\"nofollow\">?</a>";
1410                         }
1411                         return "<span class=\"createlink\">$cgilink$linktext</span>"
1412                 }
1413         }
1414         
1415         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1416         $bestlink=beautify_urlpath($bestlink);
1417         
1418         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1419                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1420         }
1422         if (defined $opts{anchor}) {
1423                 $bestlink.="#".$opts{anchor};
1424         }
1426         my @attrs;
1427         foreach my $attr (qw{rel class title}) {
1428                 if (defined $opts{$attr}) {
1429                         push @attrs, " $attr=\"$opts{$attr}\"";
1430                 }
1431         }
1433         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1436 sub userpage ($) {
1437         my $user=shift;
1438         return length $config{userdir} ? "$config{userdir}/$user" : $user;
1441 # Username to display for openid accounts.
1442 sub openiduser ($) {
1443         my $user=shift;
1445         if (defined $user && $user =~ m!^https?://! &&
1446             eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1447                 my $display;
1449                 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1450                         $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1451                 }
1452                 else {
1453                         # backcompat with old version
1454                         my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1455                         $display=$oid->display;
1456                 }
1458                 # Convert "user.somehost.com" to "user [somehost.com]"
1459                 # (also "user.somehost.co.uk")
1460                 if ($display !~ /\[/) {
1461                         $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1462                 }
1463                 # Convert "http://somehost.com/user" to "user [somehost.com]".
1464                 # (also "https://somehost.com/user/")
1465                 if ($display !~ /\[/) {
1466                         $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1467                 }
1468                 $display=~s!^https?://!!; # make sure this is removed
1469                 eval q{use CGI 'escapeHTML'};
1470                 error($@) if $@;
1471                 return escapeHTML($display);
1472         }
1473         return;
1476 # Username to display for emailauth accounts. 
1477 sub emailuser ($) {
1478         my $user=shift;
1479         if (defined $user && $user =~ m/(.+)@/) {
1480                 my $nick=$1;
1481                 # remove any characters from not allowed in wiki files
1482                 # support use w/o %config set
1483                 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1484                 $nick=~s/[^$chars]/_/g;
1485                 return $nick;
1486         }
1487         return;
1490 # Some user information should not be exposed in commit metadata, etc.
1491 # This generates a cloaked form of such information.
1492 sub cloak ($) {
1493         my $user=shift;
1494         # cloak email address using http://xmlns.com/foaf/spec/#term_mbox_sha1sum
1495         if ($user=~m/(.+)@/) {
1496                 my $nick=$1;
1497                 eval q{use Digest::SHA};
1498                 return $user if $@;
1499                 return $nick.'@'.Digest::SHA::sha1_hex("mailto:$user");
1500         }
1501         else {
1502                 return $user;
1503         }
1506 sub htmlize ($$$$) {
1507         my $page=shift;
1508         my $destpage=shift;
1509         my $type=shift;
1510         my $content=shift;
1511         
1512         my $oneline = $content !~ /\n/;
1513         
1514         if (exists $hooks{htmlize}{$type}) {
1515                 $content=$hooks{htmlize}{$type}{call}->(
1516                         page => $page,
1517                         content => $content,
1518                 );
1519         }
1520         else {
1521                 error("htmlization of $type not supported");
1522         }
1524         run_hooks(sanitize => sub {
1525                 $content=shift->(
1526                         page => $page,
1527                         destpage => $destpage,
1528                         content => $content,
1529                 );
1530         });
1531         
1532         if ($oneline) {
1533                 # hack to get rid of enclosing junk added by markdown
1534                 # and other htmlizers/sanitizers
1535                 $content=~s/^<p>//i;
1536                 $content=~s/<\/p>\n*$//i;
1537         }
1539         return $content;
1542 sub linkify ($$$) {
1543         my $page=shift;
1544         my $destpage=shift;
1545         my $content=shift;
1547         run_hooks(linkify => sub {
1548                 $content=shift->(
1549                         page => $page,
1550                         destpage => $destpage,
1551                         content => $content,
1552                 );
1553         });
1554         
1555         return $content;
1558 our %preprocessing;
1559 our $preprocess_preview=0;
1560 sub preprocess ($$$;$$) {
1561         my $page=shift; # the page the data comes from
1562         my $destpage=shift; # the page the data will appear in (different for inline)
1563         my $content=shift;
1564         my $scan=shift;
1565         my $preview=shift;
1567         # Using local because it needs to be set within any nested calls
1568         # of this function.
1569         local $preprocess_preview=$preview if defined $preview;
1571         my $handle=sub {
1572                 my $escape=shift;
1573                 my $prefix=shift;
1574                 my $command=shift;
1575                 my $params=shift;
1576                 $params="" if ! defined $params;
1578                 if (length $escape) {
1579                         return "[[$prefix$command $params]]";
1580                 }
1581                 elsif (exists $hooks{preprocess}{$command}) {
1582                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1583                         # Note: preserve order of params, some plugins may
1584                         # consider it significant.
1585                         my @params;
1586                         while ($params =~ m{
1587                                 (?:([-.\w]+)=)?         # 1: named parameter key?
1588                                 (?:
1589                                         """(.*?)"""     # 2: triple-quoted value
1590                                 |
1591                                         "([^"]*?)"      # 3: single-quoted value
1592                                 |
1593                                         '''(.*?)'''     # 4: triple-single-quote
1594                                 |
1595                                         <<([a-zA-Z]+)\n # 5: heredoc start
1596                                         (.*?)\n\5       # 6: heredoc value
1597                                 |
1598                                         (\S+)           # 7: unquoted value
1599                                 )
1600                                 (?:\s+|$)               # delimiter to next param
1601                         }msgx) {
1602                                 my $key=$1;
1603                                 my $val;
1604                                 if (defined $2) {
1605                                         $val=$2;
1606                                         $val=~s/\r\n/\n/mg;
1607                                         $val=~s/^\n+//g;
1608                                         $val=~s/\n+$//g;
1609                                 }
1610                                 elsif (defined $3) {
1611                                         $val=$3;
1612                                 }
1613                                 elsif (defined $4) {
1614                                         $val=$4;
1615                                 }
1616                                 elsif (defined $7) {
1617                                         $val=$7;
1618                                 }
1619                                 elsif (defined $6) {
1620                                         $val=$6;
1621                                 }
1623                                 if (defined $key) {
1624                                         push @params, $key, $val;
1625                                 }
1626                                 else {
1627                                         push @params, $val, '';
1628                                 }
1629                         }
1630                         if ($preprocessing{$page}++ > 8) {
1631                                 # Avoid loops of preprocessed pages preprocessing
1632                                 # other pages that preprocess them, etc.
1633                                 return "[[!$command <span class=\"error\">".
1634                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1635                                                 $page, $preprocessing{$page}).
1636                                         "</span>]]";
1637                         }
1638                         my $ret;
1639                         if (! $scan) {
1640                                 $ret=eval {
1641                                         $hooks{preprocess}{$command}{call}->(
1642                                                 @params,
1643                                                 page => $page,
1644                                                 destpage => $destpage,
1645                                                 preview => $preprocess_preview,
1646                                         );
1647                                 };
1648                                 if ($@) {
1649                                         my $error=$@;
1650                                         chomp $error;
1651                                         $ret="[[!$command <span class=\"error\">".
1652                                                 gettext("Error").": $error"."</span>]]";
1653                                 }
1654                         }
1655                         else {
1656                                 # use void context during scan pass
1657                                 eval {
1658                                         $hooks{preprocess}{$command}{call}->(
1659                                                 @params,
1660                                                 page => $page,
1661                                                 destpage => $destpage,
1662                                                 preview => $preprocess_preview,
1663                                         );
1664                                 };
1665                                 $ret="";
1666                         }
1667                         $preprocessing{$page}--;
1668                         return $ret;
1669                 }
1670                 else {
1671                         return "[[$prefix$command $params]]";
1672                 }
1673         };
1674         
1675         my $regex;
1676         if ($config{prefix_directives}) {
1677                 $regex = qr{
1678                         (\\?)           # 1: escape?
1679                         \[\[(!)         # directive open; 2: prefix
1680                         ([-\w]+)        # 3: command
1681                         (               # 4: the parameters..
1682                                 \s+     # Must have space if parameters present
1683                                 (?:
1684                                         (?:[-.\w]+=)?           # named parameter key?
1685                                         (?:
1686                                                 """.*?"""       # triple-quoted value
1687                                                 |
1688                                                 "[^"]*?"        # single-quoted value
1689                                                 |
1690                                                 '''.*?'''       # triple-single-quote
1691                                                 |
1692                                                 <<([a-zA-Z]+)\n # 5: heredoc start
1693                                                 (?:.*?)\n\5     # heredoc value
1694                                                 |
1695                                                 [^"\s\]]+       # unquoted value
1696                                         )
1697                                         \s*                     # whitespace or end
1698                                                                 # of directive
1699                                 )
1700                         *)?             # 0 or more parameters
1701                         \]\]            # directive closed
1702                 }sx;
1703         }
1704         else {
1705                 $regex = qr{
1706                         (\\?)           # 1: escape?
1707                         \[\[(!?)        # directive open; 2: optional prefix
1708                         ([-\w]+)        # 3: command
1709                         \s+
1710                         (               # 4: the parameters..
1711                                 (?:
1712                                         (?:[-.\w]+=)?           # named parameter key?
1713                                         (?:
1714                                                 """.*?"""       # triple-quoted value
1715                                                 |
1716                                                 "[^"]*?"        # single-quoted value
1717                                                 |
1718                                                 '''.*?'''       # triple-single-quote
1719                                                 |
1720                                                 <<([a-zA-Z]+)\n # 5: heredoc start
1721                                                 (?:.*?)\n\5     # heredoc value
1722                                                 |
1723                                                 [^"\s\]]+       # unquoted value
1724                                         )
1725                                         \s*                     # whitespace or end
1726                                                                 # of directive
1727                                 )
1728                         *)              # 0 or more parameters
1729                         \]\]            # directive closed
1730                 }sx;
1731         }
1733         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1734         return $content;
1737 sub filter ($$$) {
1738         my $page=shift;
1739         my $destpage=shift;
1740         my $content=shift;
1742         run_hooks(filter => sub {
1743                 $content=shift->(page => $page, destpage => $destpage, 
1744                         content => $content);
1745         });
1747         return $content;
1750 sub check_canedit ($$$;$) {
1751         my $page=shift;
1752         my $q=shift;
1753         my $session=shift;
1754         my $nonfatal=shift;
1755         
1756         my $canedit;
1757         run_hooks(canedit => sub {
1758                 return if defined $canedit;
1759                 my $ret=shift->($page, $q, $session);
1760                 if (defined $ret) {
1761                         if ($ret eq "") {
1762                                 $canedit=1;
1763                         }
1764                         elsif (ref $ret eq 'CODE') {
1765                                 $ret->() unless $nonfatal;
1766                                 $canedit=0;
1767                         }
1768                         elsif (defined $ret) {
1769                                 error($ret) unless $nonfatal;
1770                                 $canedit=0;
1771                         }
1772                 }
1773         });
1774         return defined $canedit ? $canedit : 1;
1777 sub check_content (@) {
1778         my %params=@_;
1779         
1780         return 1 if ! exists $hooks{checkcontent}; # optimisation
1782         if (exists $pagesources{$params{page}}) {
1783                 my @diff;
1784                 my %old=map { $_ => 1 }
1785                         split("\n", readfile(srcfile($pagesources{$params{page}})));
1786                 foreach my $line (split("\n", $params{content})) {
1787                         push @diff, $line if ! exists $old{$line};
1788                 }
1789                 $params{diff}=join("\n", @diff);
1790         }
1792         my $ok;
1793         run_hooks(checkcontent => sub {
1794                 return if defined $ok;
1795                 my $ret=shift->(%params);
1796                 if (defined $ret) {
1797                         if ($ret eq "") {
1798                                 $ok=1;
1799                         }
1800                         elsif (ref $ret eq 'CODE') {
1801                                 $ret->() unless $params{nonfatal};
1802                                 $ok=0;
1803                         }
1804                         elsif (defined $ret) {
1805                                 error($ret) unless $params{nonfatal};
1806                                 $ok=0;
1807                         }
1808                 }
1810         });
1811         return defined $ok ? $ok : 1;
1814 sub check_canchange (@) {
1815         my %params = @_;
1816         my $cgi = $params{cgi};
1817         my $session = $params{session};
1818         my @changes = @{$params{changes}};
1820         my %newfiles;
1821         foreach my $change (@changes) {
1822                 # This untaint is safe because we check file_pruned and
1823                 # wiki_file_regexp.
1824                 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1825                 $file=possibly_foolish_untaint($file);
1826                 if (! defined $file || ! length $file ||
1827                     file_pruned($file)) {
1828                         error(gettext("bad file name %s"), $file);
1829                 }
1831                 my $type=pagetype($file);
1832                 my $page=pagename($file) if defined $type;
1834                 if ($change->{action} eq 'add') {
1835                         $newfiles{$file}=1;
1836                 }
1838                 if ($change->{action} eq 'change' ||
1839                     $change->{action} eq 'add') {
1840                         if (defined $page) {
1841                                 check_canedit($page, $cgi, $session);
1842                                 next;
1843                         }
1844                         else {
1845                                 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1846                                         IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1847                                         check_canedit($file, $cgi, $session);
1848                                         next;
1849                                 }
1850                         }
1851                 }
1852                 elsif ($change->{action} eq 'remove') {
1853                         # check_canremove tests to see if the file is present
1854                         # on disk. This will fail when a single commit adds a
1855                         # file and then removes it again. Avoid the problem
1856                         # by not testing the removal in such pairs of changes.
1857                         # (The add is still tested, just to make sure that
1858                         # no data is added to the repo that a web edit
1859                         # could not add.)
1860                         next if $newfiles{$file};
1862                         if (IkiWiki::Plugin::remove->can("check_canremove")) {
1863                                 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1864                                 check_canedit(defined $page ? $page : $file, $cgi, $session);
1865                                 next;
1866                         }
1867                 }
1868                 else {
1869                         error "unknown action ".$change->{action};
1870                 }
1872                 error sprintf(gettext("you are not allowed to change %s"), $file);
1873         }
1877 my $wikilock;
1879 sub lockwiki () {
1880         # Take an exclusive lock on the wiki to prevent multiple concurrent
1881         # run issues. The lock will be dropped on program exit.
1882         if (! -d $config{wikistatedir}) {
1883                 mkdir($config{wikistatedir});
1884         }
1885         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1886                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1887         if (! flock($wikilock, LOCK_EX | LOCK_NB)) {
1888                 debug("failed to get lock; waiting...");
1889                 if (! flock($wikilock, LOCK_EX)) {
1890                         error("failed to get lock");
1891                 }
1892         }
1893         return 1;
1896 sub unlockwiki () {
1897         POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1898         return close($wikilock) if $wikilock;
1899         return;
1902 my $commitlock;
1904 sub commit_hook_enabled () {
1905         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1906                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1907         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1908                 close($commitlock) || error("failed closing commitlock: $!");
1909                 return 0;
1910         }
1911         close($commitlock) || error("failed closing commitlock: $!");
1912         return 1;
1915 sub disable_commit_hook () {
1916         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1917                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1918         if (! flock($commitlock, 2)) { # LOCK_EX
1919                 error("failed to get commit lock");
1920         }
1921         return 1;
1924 sub enable_commit_hook () {
1925         return close($commitlock) if $commitlock;
1926         return;
1929 sub loadindex () {
1930         %oldrenderedfiles=%pagectime=();
1931         my $rebuild=$config{rebuild};
1932         if (! $rebuild) {
1933                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1934                 %destsources=%renderedfiles=%pagecase=%pagestate=
1935                 %depends_simple=%typedlinks=%oldtypedlinks=();
1936         }
1937         my $in;
1938         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1939                 if (-e "$config{wikistatedir}/index") {
1940                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1941                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1942                 }
1943                 else {
1944                         # gettime on first build
1945                         $config{gettime}=1 unless defined $config{gettime};
1946                         return;
1947                 }
1948         }
1950         my $index=Storable::fd_retrieve($in);
1951         if (! defined $index) {
1952                 return 0;
1953         }
1955         my $pages;
1956         if (exists $index->{version} && ! ref $index->{version}) {
1957                 $pages=$index->{page};
1958                 %wikistate=%{$index->{state}};
1959                 # Handle plugins that got disabled by loading a new setup.
1960                 if (exists $config{setupfile}) {
1961                         require IkiWiki::Setup;
1962                         IkiWiki::Setup::disabled_plugins(
1963                                 grep { ! $loaded_plugins{$_} } keys %wikistate);
1964                 }
1965         }
1966         else {
1967                 $pages=$index;
1968                 %wikistate=();
1969         }
1971         foreach my $src (keys %$pages) {
1972                 my $d=$pages->{$src};
1973                 my $page;
1974                 if (exists $d->{page} && ! $rebuild) {
1975                         $page=$d->{page};
1976                 }
1977                 else {
1978                         $page=pagename($src);
1979                 }
1980                 $pagectime{$page}=$d->{ctime};
1981                 $pagesources{$page}=$src;
1982                 if (! $rebuild) {
1983                         $pagemtime{$page}=$d->{mtime};
1984                         $renderedfiles{$page}=$d->{dest};
1985                         if (exists $d->{links} && ref $d->{links}) {
1986                                 $links{$page}=$d->{links};
1987                                 $oldlinks{$page}=[@{$d->{links}}];
1988                         }
1989                         if (ref $d->{depends_simple} eq 'ARRAY') {
1990                                 # old format
1991                                 $depends_simple{$page}={
1992                                         map { $_ => 1 } @{$d->{depends_simple}}
1993                                 };
1994                         }
1995                         elsif (exists $d->{depends_simple}) {
1996                                 $depends_simple{$page}=$d->{depends_simple};
1997                         }
1998                         if (exists $d->{dependslist}) {
1999                                 # old format
2000                                 $depends{$page}={
2001                                         map { $_ => $DEPEND_CONTENT }
2002                                                 @{$d->{dependslist}}
2003                                 };
2004                         }
2005                         elsif (exists $d->{depends} && ! ref $d->{depends}) {
2006                                 # old format
2007                                 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
2008                         }
2009                         elsif (exists $d->{depends}) {
2010                                 $depends{$page}=$d->{depends};
2011                         }
2012                         if (exists $d->{state}) {
2013                                 $pagestate{$page}=$d->{state};
2014                         }
2015                         if (exists $d->{typedlinks}) {
2016                                 $typedlinks{$page}=$d->{typedlinks};
2018                                 while (my ($type, $links) = each %{$typedlinks{$page}}) {
2019                                         next unless %$links;
2020                                         $oldtypedlinks{$page}{$type} = {%$links};
2021                                 }
2022                         }
2023                 }
2024                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
2025         }
2026         foreach my $page (keys %pagesources) {
2027                 $pagecase{lc $page}=$page;
2028         }
2029         foreach my $page (keys %renderedfiles) {
2030                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
2031         }
2032         $lastrev=$index->{lastrev};
2033         @underlayfiles=@{$index->{underlayfiles}} if ref $index->{underlayfiles};
2034         return close($in);
2037 sub saveindex () {
2038         run_hooks(savestate => sub { shift->() });
2040         my @plugins=keys %loaded_plugins;
2042         if (! -d $config{wikistatedir}) {
2043                 mkdir($config{wikistatedir});
2044         }
2045         my $newfile="$config{wikistatedir}/indexdb.new";
2046         my $cleanup = sub { unlink($newfile) };
2047         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
2049         my %index;
2050         foreach my $page (keys %pagemtime) {
2051                 next unless $pagemtime{$page};
2052                 my $src=$pagesources{$page};
2054                 $index{page}{$src}={
2055                         page => $page,
2056                         ctime => $pagectime{$page},
2057                         mtime => $pagemtime{$page},
2058                         dest => $renderedfiles{$page},
2059                         links => $links{$page},
2060                 };
2062                 if (exists $depends{$page}) {
2063                         $index{page}{$src}{depends} = $depends{$page};
2064                 }
2066                 if (exists $depends_simple{$page}) {
2067                         $index{page}{$src}{depends_simple} = $depends_simple{$page};
2068                 }
2070                 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
2071                         $index{page}{$src}{typedlinks} = $typedlinks{$page};
2072                 }
2074                 if (exists $pagestate{$page}) {
2075                         $index{page}{$src}{state}=$pagestate{$page};
2076                 }
2077         }
2079         $index{state}={};
2080         foreach my $id (@plugins) {
2081                 $index{state}{$id}={}; # used to detect disabled plugins
2082                 foreach my $key (keys %{$wikistate{$id}}) {
2083                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
2084                 }
2085         }
2086         
2087         $index{lastrev}=$lastrev;
2088         $index{underlayfiles}=\@underlayfiles;
2090         $index{version}="3";
2091         my $ret=Storable::nstore_fd(\%index, $out);
2092         return if ! defined $ret || ! $ret;
2093         close $out || error("failed saving to $newfile: $!", $cleanup);
2094         rename($newfile, "$config{wikistatedir}/indexdb") ||
2095                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
2096         
2097         return 1;
2100 sub template_file ($) {
2101         my $name=shift;
2102         
2103         my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
2104         my $template;
2105         if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
2106                 $template=srcfile($pagesources{$tpage}, 1);
2107                 $name.=".tmpl";
2108         }
2109         else {
2110                 $template=srcfile($tpage, 1);
2111         }
2113         if (defined $template) {
2114                 return $template, $tpage, 1 if wantarray;
2115                 return $template;
2116         }
2117         else {
2118                 $name=~s:/::; # avoid path traversal
2119                 foreach my $dir ($config{templatedir},
2120                                  "$installdir/share/ikiwiki/templates") {
2121                         if (-e "$dir/$name") {
2122                                 $template="$dir/$name";
2123                                 last;
2124                         }
2125                 }
2126                 if (defined $template) {        
2127                         return $template, $tpage if wantarray;
2128                         return $template;
2129                 }
2130         }
2132         return;
2135 sub template_depends ($$;@) {
2136         my $name=shift;
2137         my $page=shift;
2138         
2139         my ($filename, $tpage, $untrusted)=template_file($name);
2140         if (! defined $filename) {
2141                 error(sprintf(gettext("template %s not found"), $name))
2142         }
2144         if (defined $page && defined $tpage) {
2145                 add_depends($page, $tpage);
2146         }
2148         my @opts=(
2149                 filter => sub {
2150                         my $text_ref = shift;
2151                         ${$text_ref} = decode_utf8(${$text_ref});
2152                         run_hooks(readtemplate => sub {
2153                                 ${$text_ref} = shift->(
2154                                         id => $name,
2155                                         page => $tpage,
2156                                         content => ${$text_ref},
2157                                         untrusted => $untrusted,
2158                                 );
2159                         });
2160                 },
2161                 loop_context_vars => 1,
2162                 die_on_bad_params => 0,
2163                 parent_global_vars => 1,
2164                 filename => $filename,
2165                 @_,
2166                 ($untrusted ? (no_includes => 1) : ()),
2167         );
2168         return @opts if wantarray;
2170         require HTML::Template;
2171         return HTML::Template->new(@opts);
2174 sub template ($;@) {
2175         template_depends(shift, undef, @_);
2178 sub templateactions ($$) {
2179         my $template=shift;
2180         my $page=shift;
2182         my $have_actions=0;
2183         my @actions;
2184         run_hooks(pageactions => sub {
2185                 push @actions, map { { action => $_ } } 
2186                         grep { defined } shift->(page => $page);
2187         });
2188         $template->param(actions => \@actions);
2190         if ($config{cgiurl} && exists $hooks{auth}) {
2191                 $template->param(prefsurl => cgiurl(do => "prefs"));
2192                 $have_actions=1;
2193         }
2195         if ($have_actions || @actions) {
2196                 $template->param(have_actions => 1);
2197         }
2200 sub hook (@) {
2201         my %param=@_;
2202         
2203         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
2204                 error 'hook requires type, call, and id parameters';
2205         }
2207         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
2208         
2209         $hooks{$param{type}}{$param{id}}=\%param;
2210         return 1;
2213 sub run_hooks ($$) {
2214         # Calls the given sub for each hook of the given type,
2215         # passing it the hook function to call.
2216         my $type=shift;
2217         my $sub=shift;
2219         if (exists $hooks{$type}) {
2220                 my (@first, @middle, @last);
2221                 foreach my $id (keys %{$hooks{$type}}) {
2222                         if ($hooks{$type}{$id}{first}) {
2223                                 push @first, $id;
2224                         }
2225                         elsif ($hooks{$type}{$id}{last}) {
2226                                 push @last, $id;
2227                         }
2228                         else {
2229                                 push @middle, $id;
2230                         }
2231                 }
2232                 foreach my $id (@first, @middle, @last) {
2233                         $sub->($hooks{$type}{$id}{call});
2234                 }
2235         }
2237         return 1;
2240 sub rcs_update () {
2241         $hooks{rcs}{rcs_update}{call}->(@_);
2244 sub rcs_prepedit ($) {
2245         $hooks{rcs}{rcs_prepedit}{call}->(@_);
2248 sub rcs_commit (@) {
2249         $hooks{rcs}{rcs_commit}{call}->(@_);
2252 sub rcs_commit_staged (@) {
2253         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2256 sub rcs_add ($) {
2257         $hooks{rcs}{rcs_add}{call}->(@_);
2260 sub rcs_remove ($) {
2261         $hooks{rcs}{rcs_remove}{call}->(@_);
2264 sub rcs_rename ($$) {
2265         $hooks{rcs}{rcs_rename}{call}->(@_);
2268 sub rcs_recentchanges ($) {
2269         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2272 sub rcs_diff ($;$) {
2273         $hooks{rcs}{rcs_diff}{call}->(@_);
2276 sub rcs_getctime ($) {
2277         $hooks{rcs}{rcs_getctime}{call}->(@_);
2280 sub rcs_getmtime ($) {
2281         $hooks{rcs}{rcs_getmtime}{call}->(@_);
2284 sub rcs_receive () {
2285         $hooks{rcs}{rcs_receive}{call}->();
2288 sub add_depends ($$;$) {
2289         my $page=shift;
2290         my $pagespec=shift;
2291         my $deptype=shift || $DEPEND_CONTENT;
2293         # Is the pagespec a simple page name?
2294         if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2295             $pagespec !~ /[\s*?()!]/) {
2296                 $depends_simple{$page}{lc $pagespec} |= $deptype;
2297                 return 1;
2298         }
2300         # Add explicit dependencies for influences.
2301         my $sub=pagespec_translate($pagespec);
2302         return unless defined $sub;
2303         foreach my $p (keys %pagesources) {
2304                 my $r=$sub->($p, location => $page);
2305                 my $i=$r->influences;
2306                 my $static=$r->influences_static;
2307                 foreach my $k (keys %$i) {
2308                         next unless $r || $static || $k eq $page;
2309                         $depends_simple{$page}{lc $k} |= $i->{$k};
2310                 }
2311                 last if $static;
2312         }
2314         $depends{$page}{$pagespec} |= $deptype;
2315         return 1;
2318 sub deptype (@) {
2319         my $deptype=0;
2320         foreach my $type (@_) {
2321                 if ($type eq 'presence') {
2322                         $deptype |= $DEPEND_PRESENCE;
2323                 }
2324                 elsif ($type eq 'links') { 
2325                         $deptype |= $DEPEND_LINKS;
2326                 }
2327                 elsif ($type eq 'content') {
2328                         $deptype |= $DEPEND_CONTENT;
2329                 }
2330         }
2331         return $deptype;
2334 my $file_prune_regexp;
2335 sub file_pruned ($) {
2336         my $file=shift;
2338         if (defined $config{include} && length $config{include}) {
2339                 return 0 if $file =~ m/$config{include}/;
2340         }
2342         if (! defined $file_prune_regexp) {
2343                 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2344                 $file_prune_regexp=qr/$file_prune_regexp/;
2345         }
2346         return $file =~ m/$file_prune_regexp/;
2349 sub define_gettext () {
2350         # If translation is needed, redefine the gettext function to do it.
2351         # Otherwise, it becomes a quick no-op.
2352         my $gettext_obj;
2353         my $getobj;
2354         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2355             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2356             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2357                 $getobj=sub {
2358                         $gettext_obj=eval q{
2359                                 use Locale::gettext q{textdomain};
2360                                 Locale::gettext->domain('ikiwiki')
2361                         };
2362                 };
2363         }
2365         no warnings 'redefine';
2366         *gettext=sub {
2367                 $getobj->() if $getobj;
2368                 if ($gettext_obj) {
2369                         $gettext_obj->get(shift);
2370                 }
2371                 else {
2372                         return shift;
2373                 }
2374         };
2375         *ngettext=sub {
2376                 $getobj->() if $getobj;
2377                 if ($gettext_obj) {
2378                         $gettext_obj->nget(@_);
2379                 }
2380                 else {
2381                         return ($_[2] == 1 ? $_[0] : $_[1])
2382                 }
2383         };
2386 sub gettext {
2387         define_gettext();
2388         gettext(@_);
2391 sub ngettext {
2392         define_gettext();
2393         ngettext(@_);
2396 sub yesno ($) {
2397         my $val=shift;
2399         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2402 sub inject {
2403         # Injects a new function into the symbol table to replace an
2404         # exported function.
2405         my %params=@_;
2407         # This is deep ugly perl foo, beware.
2408         no strict;
2409         no warnings;
2410         if (! defined $params{parent}) {
2411                 $params{parent}='::';
2412                 $params{old}=\&{$params{name}};
2413                 $params{name}=~s/.*:://;
2414         }
2415         my $parent=$params{parent};
2416         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2417                 $ns = $params{parent} . $ns;
2418                 inject(%params, parent => $ns) unless $ns eq '::main::';
2419                 *{$ns . $params{name}} = $params{call}
2420                         if exists ${$ns}{$params{name}} &&
2421                            \&{${$ns}{$params{name}}} == $params{old};
2422         }
2423         use strict;
2424         use warnings;
2427 sub add_link ($$;$) {
2428         my $page=shift;
2429         my $link=shift;
2430         my $type=shift;
2432         push @{$links{$page}}, $link
2433                 unless grep { $_ eq $link } @{$links{$page}};
2435         if (defined $type) {
2436                 $typedlinks{$page}{$type}{$link} = 1;
2437         }
2440 sub add_autofile ($$$) {
2441         my $file=shift;
2442         my $plugin=shift;
2443         my $generator=shift;
2444         
2445         $autofiles{$file}{plugin}=$plugin;
2446         $autofiles{$file}{generator}=$generator;
2449 sub useragent () {
2450         return LWP::UserAgent->new(
2451                 cookie_jar => $config{cookiejar},
2452                 env_proxy => 1,         # respect proxy env vars
2453                 agent => $config{useragent},
2454         );
2457 sub sortspec_translate ($$) {
2458         my $spec = shift;
2459         my $reverse = shift;
2461         my $code = "";
2462         my @data;
2463         while ($spec =~ m{
2464                 \s*
2465                 (-?)            # group 1: perhaps negated
2466                 \s*
2467                 (               # group 2: a word
2468                         \w+\([^\)]*\)   # command(params)
2469                         |
2470                         [^\s]+          # or anything else
2471                 )
2472                 \s*
2473         }gx) {
2474                 my $negated = $1;
2475                 my $word = $2;
2476                 my $params = undef;
2478                 if ($word =~ m/^(\w+)\((.*)\)$/) {
2479                         # command with parameters
2480                         $params = $2;
2481                         $word = $1;
2482                 }
2483                 elsif ($word !~ m/^\w+$/) {
2484                         error(sprintf(gettext("invalid sort type %s"), $word));
2485                 }
2487                 if (length $code) {
2488                         $code .= " || ";
2489                 }
2491                 if ($negated) {
2492                         $code .= "-";
2493                 }
2495                 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2496                         if (defined $params) {
2497                                 push @data, $params;
2498                                 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2499                         }
2500                         else {
2501                                 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2502                         }
2503                 }
2504                 else {
2505                         error(sprintf(gettext("unknown sort type %s"), $word));
2506                 }
2507         }
2509         if (! length $code) {
2510                 # undefined sorting method... sort arbitrarily
2511                 return sub { 0 };
2512         }
2514         if ($reverse) {
2515                 $code="-($code)";
2516         }
2518         no warnings;
2519         return eval 'sub { '.$code.' }';
2522 sub pagespec_translate ($) {
2523         my $spec=shift;
2525         # Convert spec to perl code.
2526         my $code="";
2527         my @data;
2528         while ($spec=~m{
2529                 \s*             # ignore whitespace
2530                 (               # 1: match a single word
2531                         \!              # !
2532                 |
2533                         \(              # (
2534                 |
2535                         \)              # )
2536                 |
2537                         \w+\([^\)]*\)   # command(params)
2538                 |
2539                         [^\s()]+        # any other text
2540                 )
2541                 \s*             # ignore whitespace
2542         }gx) {
2543                 my $word=$1;
2544                 if (lc $word eq 'and') {
2545                         $code.=' &';
2546                 }
2547                 elsif (lc $word eq 'or') {
2548                         $code.=' |';
2549                 }
2550                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2551                         $code.=' '.$word;
2552                 }
2553                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2554                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2555                                 push @data, $2;
2556                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2557                         }
2558                         else {
2559                                 push @data, qq{unknown function in pagespec "$word"};
2560                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2561                         }
2562                 }
2563                 else {
2564                         push @data, $word;
2565                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2566                 }
2567         }
2569         if (! length $code) {
2570                 $code="IkiWiki::FailReason->new('empty pagespec')";
2571         }
2573         no warnings;
2574         return eval 'sub { my $page=shift; '.$code.' }';
2577 sub pagespec_match ($$;@) {
2578         my $page=shift;
2579         my $spec=shift;
2580         my @params=@_;
2582         # Backwards compatability with old calling convention.
2583         if (@params == 1) {
2584                 unshift @params, 'location';
2585         }
2587         my $sub=pagespec_translate($spec);
2588         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2589                 if ! defined $sub;
2590         return $sub->($page, @params);
2593 # e.g. @pages = sort_pages("title", \@pages, reverse => "yes")
2595 # Not exported yet, but could be in future if it is generally useful.
2596 # Note that this signature is not the same as IkiWiki::SortSpec::sort_pages,
2597 # which is "more internal".
2598 sub sort_pages ($$;@) {
2599         my $sort = shift;
2600         my $list = shift;
2601         my %params = @_;
2602         $sort = sortspec_translate($sort, $params{reverse});
2603         return IkiWiki::SortSpec::sort_pages($sort, @$list);
2606 sub pagespec_match_list ($$;@) {
2607         my $page=shift;
2608         my $pagespec=shift;
2609         my %params=@_;
2611         # Backwards compatability with old calling convention.
2612         if (ref $page) {
2613                 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2614                 $params{list}=$page;
2615                 $page=$params{location}; # ugh!
2616         }
2618         my $sub=pagespec_translate($pagespec);
2619         error "syntax error in pagespec \"$pagespec\""
2620                 if ! defined $sub;
2621         my $sort=sortspec_translate($params{sort}, $params{reverse})
2622                 if defined $params{sort};
2624         my @candidates;
2625         if (exists $params{list}) {
2626                 @candidates=exists $params{filter}
2627                         ? grep { ! $params{filter}->($_) } @{$params{list}}
2628                         : @{$params{list}};
2629         }
2630         else {
2631                 @candidates=exists $params{filter}
2632                         ? grep { ! $params{filter}->($_) } keys %pagesources
2633                         : keys %pagesources;
2634         }
2635         
2636         # clear params, remainder is passed to pagespec
2637         $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2638         my $num=$params{num};
2639         delete @params{qw{num deptype reverse sort filter list}};
2640         
2641         # when only the top matches will be returned, it's efficient to
2642         # sort before matching to pagespec,
2643         if (defined $num && defined $sort) {
2644                 @candidates=IkiWiki::SortSpec::sort_pages(
2645                         $sort, @candidates);
2646         }
2647         
2648         my @matches;
2649         my $firstfail;
2650         my $count=0;
2651         my $accum=IkiWiki::SuccessReason->new();
2652         foreach my $p (@candidates) {
2653                 my $r=$sub->($p, %params, location => $page);
2654                 error(sprintf(gettext("cannot match pages: %s"), $r))
2655                         if $r->isa("IkiWiki::ErrorReason");
2656                 unless ($r || $r->influences_static) {
2657                         $r->remove_influence($p);
2658                 }
2659                 $accum |= $r;
2660                 if ($r) {
2661                         push @matches, $p;
2662                         last if defined $num && ++$count == $num;
2663                 }
2664         }
2666         # Add simple dependencies for accumulated influences.
2667         my $i=$accum->influences;
2668         foreach my $k (keys %$i) {
2669                 $depends_simple{$page}{lc $k} |= $i->{$k};
2670         }
2672         # when all matches will be returned, it's efficient to
2673         # sort after matching
2674         if (! defined $num && defined $sort) {
2675                 return IkiWiki::SortSpec::sort_pages(
2676                         $sort, @matches);
2677         }
2678         else {
2679                 return @matches;
2680         }
2683 sub pagespec_valid ($) {
2684         my $spec=shift;
2686         return defined pagespec_translate($spec);
2689 sub glob2re ($) {
2690         my $re=quotemeta(shift);
2691         $re=~s/\\\*/.*/g;
2692         $re=~s/\\\?/./g;
2693         return qr/^$re$/i;
2696 package IkiWiki::FailReason;
2698 use overload (
2699         '""'    => sub { $_[0][0] },
2700         '0+'    => sub { 0 },
2701         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2702         '&'     => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2703         '|'     => sub { $_[1]->merge_influences($_[0]); $_[1] },
2704         fallback => 1,
2705 );
2707 our @ISA = 'IkiWiki::SuccessReason';
2709 package IkiWiki::SuccessReason;
2711 # A blessed array-ref:
2713 # [0]: human-readable reason for success (or, in FailReason subclass, failure)
2714 # [1]{""}:
2715 #      - if absent or false, the influences of this evaluation are "static",
2716 #        see the influences_static method
2717 #      - if true, they are dynamic (not static)
2718 # [1]{any other key}:
2719 #      the dependency types of influences, as returned by the influences method
2721 use overload (
2722         # in string context, it's the human-readable reason
2723         '""'    => sub { $_[0][0] },
2724         # in boolean context, SuccessReason is 1 and FailReason is 0
2725         '0+'    => sub { 1 },
2726         # negating a result gives the opposite result with the same influences
2727         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
2728         # A & B = (A ? B : A) with the influences of both
2729         '&'     => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2730         # A | B = (A ? A : B) with the influences of both
2731         '|'     => sub { $_[0]->merge_influences($_[1]); $_[0] },
2732         fallback => 1,
2733 );
2735 # SuccessReason->new("human-readable reason", page => deptype, ...)
2737 sub new {
2738         my $class = shift;
2739         my $value = shift;
2740         return bless [$value, {@_}], $class;
2743 # influences(): return a reference to a copy of the hash
2744 # { page => dependency type } describing the pages that indirectly influenced
2745 # this result, but would not cause a dependency through ikiwiki's core
2746 # dependency logic.
2748 # See [[todo/dependency_types]] for extensive discussion of what this means.
2750 # influences(page => deptype, ...): remove all influences, replace them
2751 # with the arguments, and return a reference to a copy of the new influences.
2753 sub influences {
2754         my $this=shift;
2755         $this->[1]={@_} if @_;
2756         my %i=%{$this->[1]};
2757         delete $i{""};
2758         return \%i;
2761 # True if this result has the same influences whichever page it matches,
2762 # For instance, whether bar matches backlink(foo) is influenced only by
2763 # the set of links in foo, so its only influence is { foo => DEPEND_LINKS },
2764 # which does not mention bar anywhere.
2766 # False if this result would have different influences when matching
2767 # different pages. For instance, when testing whether link(foo) matches bar,
2768 # { bar => DEPEND_LINKS } is an influence on that result, because changing
2769 # bar's links could change the outcome; so its influences are not the same
2770 # as when testing whether link(foo) matches baz.
2772 # Static influences are one of the things that make pagespec_match_list
2773 # more efficient than repeated calls to pagespec_match.
2775 sub influences_static {
2776         return ! $_[0][1]->{""};
2779 # Change the influences of $this to be the influences of "$this & $other"
2780 # or "$this | $other".
2782 # If both $this and $other are either successful or have influences,
2783 # or this is an "or" operation, the result has all the influences from
2784 # either of the arguments. It has dynamic influences if either argument
2785 # has dynamic influences.
2787 # If this is an "and" operation, and at least one argument is a
2788 # FailReason with no influences, the result has no influences, and they
2789 # are not dynamic. For instance, link(foo) matching bar is influenced
2790 # by bar, but enabled(ddate) has no influences. Suppose ddate is disabled;
2791 # then (link(foo) and enabled(ddate)) not matching bar is not influenced by
2792 # bar, because it would be false however often you edit bar.
2794 sub merge_influences {
2795         my $this=shift;
2796         my $other=shift;
2797         my $anded=shift;
2799         # This "if" is odd because it needs to avoid negating $this
2800         # or $other, which would alter the objects in-place. Be careful.
2801         if (! $anded || (($this || %{$this->[1]}) &&
2802                          ($other || %{$other->[1]}))) {
2803                 foreach my $influence (keys %{$other->[1]}) {
2804                         $this->[1]{$influence} |= $other->[1]{$influence};
2805                 }
2806         }
2807         else {
2808                 # influence blocker
2809                 $this->[1]={};
2810         }
2813 # Change $this so it is not considered to be influenced by $torm.
2815 sub remove_influence {
2816         my $this=shift;
2817         my $torm=shift;
2819         delete $this->[1]{$torm};
2822 package IkiWiki::ErrorReason;
2824 our @ISA = 'IkiWiki::FailReason';
2826 package IkiWiki::PageSpec;
2828 sub derel ($$) {
2829         my $path=shift;
2830         my $from=shift;
2832         if ($path =~ m!^\.(/|$)!) {
2833                 if ($1) {
2834                         $from=~s#/?[^/]+$## if defined $from;
2835                         $path=~s#^\./##;
2836                         $path="$from/$path" if defined $from && length $from;
2837                 }
2838                 else {
2839                         $path = $from;
2840                         $path = "" unless defined $path;
2841                 }
2842         }
2844         return $path;
2847 my %glob_cache;
2849 sub match_glob ($$;@) {
2850         my $page=shift;
2851         my $glob=shift;
2852         my %params=@_;
2853         
2854         $glob=derel($glob, $params{location});
2856         # Instead of converting the glob to a regex every time,
2857         # cache the compiled regex to save time.
2858         my $re=$glob_cache{$glob};
2859         unless (defined $re) {
2860                 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2861         }
2862         if ($page =~ $re) {
2863                 if (! IkiWiki::isinternal($page) || $params{internal}) {
2864                         return IkiWiki::SuccessReason->new("$glob matches $page");
2865                 }
2866                 else {
2867                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2868                 }
2869         }
2870         else {
2871                 return IkiWiki::FailReason->new("$glob does not match $page");
2872         }
2875 sub match_internal ($$;@) {
2876         return match_glob(shift, shift, @_, internal => 1)
2879 sub match_page ($$;@) {
2880         my $page=shift;
2881         my $match=match_glob($page, shift, @_);
2882         if ($match) {
2883                 my $source=exists $IkiWiki::pagesources{$page} ?
2884                         $IkiWiki::pagesources{$page} :
2885                         $IkiWiki::delpagesources{$page};
2886                 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2887                 if (! defined $type) {  
2888                         return IkiWiki::FailReason->new("$page is not a page");
2889                 }
2890         }
2891         return $match;
2894 sub match_link ($$;@) {
2895         my $page=shift;
2896         my $link=lc(shift);
2897         my %params=@_;
2899         $link=derel($link, $params{location});
2900         my $from=exists $params{location} ? $params{location} : '';
2901         my $linktype=$params{linktype};
2902         my $qualifier='';
2903         if (defined $linktype) {
2904                 $qualifier=" with type $linktype";
2905         }
2907         my $links = $IkiWiki::links{$page};
2908         return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2909                 unless $links && @{$links};
2910         my $bestlink = IkiWiki::bestlink($from, $link);
2911         foreach my $p (@{$links}) {
2912                 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2914                 if (length $bestlink) {
2915                         if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2916                                 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2917                         }
2918                 }
2919                 else {
2920                         if (match_glob($p, $link, %params)) {
2921                                 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2922                         }
2923                         my ($p_rel)=$p=~/^\/?(.*)/;
2924                         $link=~s/^\///;
2925                         if (match_glob($p_rel, $link, %params)) {
2926                                 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2927                         }
2928                 }
2929         }
2930         return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2933 sub match_backlink ($$;@) {
2934         my $page=shift;
2935         my $testpage=shift;
2936         my %params=@_;
2937         if ($testpage eq '.') {
2938                 $testpage = $params{'location'}
2939         }
2940         my $ret=match_link($testpage, $page, @_);
2941         $ret->influences($testpage => $IkiWiki::DEPEND_LINKS);
2942         return $ret;
2945 sub match_created_before ($$;@) {
2946         my $page=shift;
2947         my $testpage=shift;
2948         my %params=@_;
2949         
2950         $testpage=derel($testpage, $params{location});
2952         if (exists $IkiWiki::pagectime{$testpage}) {
2953                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2954                         return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2955                 }
2956                 else {
2957                         return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2958                 }
2959         }
2960         else {
2961                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2962         }
2965 sub match_created_after ($$;@) {
2966         my $page=shift;
2967         my $testpage=shift;
2968         my %params=@_;
2969         
2970         $testpage=derel($testpage, $params{location});
2972         if (exists $IkiWiki::pagectime{$testpage}) {
2973                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2974                         return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2975                 }
2976                 else {
2977                         return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2978                 }
2979         }
2980         else {
2981                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2982         }
2985 sub match_creation_day ($$;@) {
2986         my $page=shift;
2987         my $d=shift;
2988         if ($d !~ /^\d+$/) {
2989                 return IkiWiki::ErrorReason->new("invalid day $d");
2990         }
2991         if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2992                 return IkiWiki::SuccessReason->new('creation_day matched');
2993         }
2994         else {
2995                 return IkiWiki::FailReason->new('creation_day did not match');
2996         }
2999 sub match_creation_month ($$;@) {
3000         my $page=shift;
3001         my $m=shift;
3002         if ($m !~ /^\d+$/) {
3003                 return IkiWiki::ErrorReason->new("invalid month $m");
3004         }
3005         if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
3006                 return IkiWiki::SuccessReason->new('creation_month matched');
3007         }
3008         else {
3009                 return IkiWiki::FailReason->new('creation_month did not match');
3010         }
3013 sub match_creation_year ($$;@) {
3014         my $page=shift;
3015         my $y=shift;
3016         if ($y !~ /^\d+$/) {
3017                 return IkiWiki::ErrorReason->new("invalid year $y");
3018         }
3019         if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
3020                 return IkiWiki::SuccessReason->new('creation_year matched');
3021         }
3022         else {
3023                 return IkiWiki::FailReason->new('creation_year did not match');
3024         }
3027 sub match_user ($$;@) {
3028         shift;
3029         my $user=shift;
3030         my %params=@_;
3031         
3032         if (! exists $params{user}) {
3033                 return IkiWiki::ErrorReason->new("no user specified");
3034         }
3036         my $regexp=IkiWiki::glob2re($user);
3037         
3038         if (defined $params{user} && $params{user}=~$regexp) {
3039                 return IkiWiki::SuccessReason->new("user is $user");
3040         }
3041         elsif (! defined $params{user}) {
3042                 return IkiWiki::FailReason->new("not logged in");
3043         }
3044         else {
3045                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
3046         }
3049 sub match_admin ($$;@) {
3050         shift;
3051         shift;
3052         my %params=@_;
3053         
3054         if (! exists $params{user}) {
3055                 return IkiWiki::ErrorReason->new("no user specified");
3056         }
3058         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
3059                 return IkiWiki::SuccessReason->new("user is an admin");
3060         }
3061         elsif (! defined $params{user}) {
3062                 return IkiWiki::FailReason->new("not logged in");
3063         }
3064         else {
3065                 return IkiWiki::FailReason->new("user is not an admin");
3066         }
3069 sub match_ip ($$;@) {
3070         shift;
3071         my $ip=shift;
3072         my %params=@_;
3073         
3074         if (! exists $params{ip}) {
3075                 return IkiWiki::ErrorReason->new("no IP specified");
3076         }
3077         
3078         my $regexp=IkiWiki::glob2re(lc $ip);
3080         if (defined $params{ip} && lc $params{ip}=~$regexp) {
3081                 return IkiWiki::SuccessReason->new("IP is $ip");
3082         }
3083         else {
3084                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
3085         }
3088 package IkiWiki::SortSpec;
3090 # This is in the SortSpec namespace so that the $a and $b that sort() uses
3091 # are easily available in this namespace, for cmp functions to use them.
3092 sub sort_pages {
3093         my $f=shift;
3094         sort $f @_
3097 sub cmp_title {
3098         IkiWiki::pagetitle(IkiWiki::basename($a))
3099         cmp
3100         IkiWiki::pagetitle(IkiWiki::basename($b))
3103 sub cmp_path { IkiWiki::pagetitle($a) cmp IkiWiki::pagetitle($b) }
3104 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
3105 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }