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