]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki.pm
Removed redundant "configure'
[git.ikiwiki.info.git] / IkiWiki.pm
1 #!/usr/bin/perl
3 package IkiWiki;
5 use warnings;
6 use strict;
7 use Encode;
8 use URI::Escape q{uri_escape_utf8};
9 use POSIX ();
10 use Storable;
11 use open qw{:utf8 :std};
13 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
14         %pagestate %wikistate %renderedfiles %oldrenderedfiles
15         %pagesources %delpagesources %destsources %depends %depends_simple
16         @mass_depends %hooks %forcerebuild %loaded_plugins %typedlinks
17         %oldtypedlinks %autofiles};
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error htmlpage template template_depends
21         deptype add_depends pagespec_match pagespec_match_list bestlink
22         htmllink readfile writefile pagetype srcfile pagename
23         displaytime will_render gettext ngettext urlto targetpage
24         add_underlay pagetitle titlepage linkpage newpagefile
25         inject add_link add_autofile
26         %config %links %pagestate %wikistate %renderedfiles
27         %pagesources %destsources %typedlinks);
28 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
29 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
30 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
32 # Page dependency types.
33 our $DEPEND_CONTENT=1;
34 our $DEPEND_PRESENCE=2;
35 our $DEPEND_LINKS=4;
37 # Optimisation.
38 use Memoize;
39 memoize("abs2rel");
40 memoize("sortspec_translate");
41 memoize("pagespec_translate");
42 memoize("template_file");
44 sub getsetup () {
45         wikiname => {
46                 type => "string",
47                 default => "wiki",
48                 description => "name of the wiki",
49                 safe => 1,
50                 rebuild => 1,
51         },
52         adminemail => {
53                 type => "string",
54                 default => undef,
55                 example => 'me@example.com',
56                 description => "contact email for wiki",
57                 safe => 1,
58                 rebuild => 0,
59         },
60         adminuser => {
61                 type => "string",
62                 default => [],
63                 description => "users who are wiki admins",
64                 safe => 1,
65                 rebuild => 0,
66         },
67         banned_users => {
68                 type => "string",
69                 default => [],
70                 description => "users who are banned from the wiki",
71                 safe => 1,
72                 rebuild => 0,
73         },
74         srcdir => {
75                 type => "string",
76                 default => undef,
77                 example => "$ENV{HOME}/wiki",
78                 description => "where the source of the wiki is located",
79                 safe => 0, # path
80                 rebuild => 1,
81         },
82         destdir => {
83                 type => "string",
84                 default => undef,
85                 example => "/var/www/wiki",
86                 description => "where to build the wiki",
87                 safe => 0, # path
88                 rebuild => 1,
89         },
90         url => {
91                 type => "string",
92                 default => '',
93                 example => "http://example.com/wiki",
94                 description => "base url to the wiki",
95                 safe => 1,
96                 rebuild => 1,
97         },
98         cgiurl => {
99                 type => "string",
100                 default => '',
101                 example => "http://example.com/wiki/ikiwiki.cgi",
102                 description => "url to the ikiwiki.cgi",
103                 safe => 1,
104                 rebuild => 1,
105         },
106         cgi_wrapper => {
107                 type => "string",
108                 default => '',
109                 example => "/var/www/wiki/ikiwiki.cgi",
110                 description => "filename of cgi wrapper to generate",
111                 safe => 0, # file
112                 rebuild => 0,
113         },
114         cgi_wrappermode => {
115                 type => "string",
116                 default => '06755',
117                 description => "mode for cgi_wrapper (can safely be made suid)",
118                 safe => 0,
119                 rebuild => 0,
120         },
121         rcs => {
122                 type => "string",
123                 default => '',
124                 description => "rcs backend to use",
125                 safe => 0, # don't allow overriding
126                 rebuild => 0,
127         },
128         default_plugins => {
129                 type => "internal",
130                 default => [qw{mdwn link inline meta htmlscrubber passwordauth
131                                 openid signinedit lockedit conditional
132                                 recentchanges parentlinks editpage}],
133                 description => "plugins to enable by default",
134                 safe => 0,
135                 rebuild => 1,
136         },
137         add_plugins => {
138                 type => "string",
139                 default => [],
140                 description => "plugins to add to the default configuration",
141                 safe => 1,
142                 rebuild => 1,
143         },
144         disable_plugins => {
145                 type => "string",
146                 default => [],
147                 description => "plugins to disable",
148                 safe => 1,
149                 rebuild => 1,
150         },
151         templatedir => {
152                 type => "string",
153                 default => "$installdir/share/ikiwiki/templates",
154                 description => "additional directory to search for template files",
155                 advanced => 1,
156                 safe => 0, # path
157                 rebuild => 1,
158         },
159         underlaydir => {
160                 type => "string",
161                 default => "$installdir/share/ikiwiki/basewiki",
162                 description => "base wiki source location",
163                 advanced => 1,
164                 safe => 0, # path
165                 rebuild => 0,
166         },
167         underlaydirbase => {
168                 type => "internal",
169                 default => "$installdir/share/ikiwiki",
170                 description => "parent directory containing additional underlays",
171                 safe => 0,
172                 rebuild => 0,
173         },
174         wrappers => {
175                 type => "internal",
176                 default => [],
177                 description => "wrappers to generate",
178                 safe => 0,
179                 rebuild => 0,
180         },
181         underlaydirs => {
182                 type => "internal",
183                 default => [],
184                 description => "additional underlays to use",
185                 safe => 0,
186                 rebuild => 0,
187         },
188         verbose => {
189                 type => "boolean",
190                 example => 1,
191                 description => "display verbose messages?",
192                 safe => 1,
193                 rebuild => 0,
194         },
195         syslog => {
196                 type => "boolean",
197                 example => 1,
198                 description => "log to syslog?",
199                 safe => 1,
200                 rebuild => 0,
201         },
202         usedirs => {
203                 type => "boolean",
204                 default => 1,
205                 description => "create output files named page/index.html?",
206                 safe => 0, # changing requires manual transition
207                 rebuild => 1,
208         },
209         prefix_directives => {
210                 type => "boolean",
211                 default => 1,
212                 description => "use '!'-prefixed preprocessor directives?",
213                 safe => 0, # changing requires manual transition
214                 rebuild => 1,
215         },
216         indexpages => {
217                 type => "boolean",
218                 default => 0,
219                 description => "use page/index.mdwn source files",
220                 safe => 1,
221                 rebuild => 1,
222         },
223         discussion => {
224                 type => "boolean",
225                 default => 1,
226                 description => "enable Discussion pages?",
227                 safe => 1,
228                 rebuild => 1,
229         },
230         discussionpage => {
231                 type => "string",
232                 default => gettext("Discussion"),
233                 description => "name of Discussion pages",
234                 safe => 1,
235                 rebuild => 1,
236         },
237         html5 => {
238                 type => "boolean",
239                 default => 0,
240                 description => "generate HTML5? (experimental)",
241                 advanced => 1,
242                 safe => 1,
243                 rebuild => 1,
244         },
245         sslcookie => {
246                 type => "boolean",
247                 default => 0,
248                 description => "only send cookies over SSL connections?",
249                 advanced => 1,
250                 safe => 1,
251                 rebuild => 0,
252         },
253         default_pageext => {
254                 type => "string",
255                 default => "mdwn",
256                 description => "extension to use for new pages",
257                 safe => 0, # not sanitized
258                 rebuild => 0,
259         },
260         htmlext => {
261                 type => "string",
262                 default => "html",
263                 description => "extension to use for html files",
264                 safe => 0, # not sanitized
265                 rebuild => 1,
266         },
267         timeformat => {
268                 type => "string",
269                 default => '%c',
270                 description => "strftime format string to display date",
271                 advanced => 1,
272                 safe => 1,
273                 rebuild => 1,
274         },
275         locale => {
276                 type => "string",
277                 default => undef,
278                 example => "en_US.UTF-8",
279                 description => "UTF-8 locale to use",
280                 advanced => 1,
281                 safe => 0,
282                 rebuild => 1,
283         },
284         userdir => {
285                 type => "string",
286                 default => "",
287                 example => "users",
288                 description => "put user pages below specified page",
289                 safe => 1,
290                 rebuild => 1,
291         },
292         numbacklinks => {
293                 type => "integer",
294                 default => 10,
295                 description => "how many backlinks to show before hiding excess (0 to show all)",
296                 safe => 1,
297                 rebuild => 1,
298         },
299         hardlink => {
300                 type => "boolean",
301                 default => 0,
302                 description => "attempt to hardlink source files? (optimisation for large files)",
303                 advanced => 1,
304                 safe => 0, # paranoia
305                 rebuild => 0,
306         },
307         umask => {
308                 type => "integer",
309                 example => "022",
310                 description => "force ikiwiki to use a particular umask",
311                 advanced => 1,
312                 safe => 0, # paranoia
313                 rebuild => 0,
314         },
315         wrappergroup => {
316                 type => "string",
317                 example => "ikiwiki",
318                 description => "group for wrappers to run in",
319                 advanced => 1,
320                 safe => 0, # paranoia
321                 rebuild => 0,
322         },
323         libdir => {
324                 type => "string",
325                 default => "",
326                 example => "$ENV{HOME}/.ikiwiki/",
327                 description => "extra library and plugin directory",
328                 advanced => 1,
329                 safe => 0, # directory
330                 rebuild => 0,
331         },
332         ENV => {
333                 type => "string", 
334                 default => {},
335                 description => "environment variables",
336                 safe => 0, # paranoia
337                 rebuild => 0,
338         },
339         include => {
340                 type => "string",
341                 default => undef,
342                 example => '^\.htaccess$',
343                 description => "regexp of normally excluded files to include",
344                 advanced => 1,
345                 safe => 0, # regexp
346                 rebuild => 1,
347         },
348         exclude => {
349                 type => "string",
350                 default => undef,
351                 example => '^(*\.private|Makefile)$',
352                 description => "regexp of files that should be skipped",
353                 advanced => 1,
354                 safe => 0, # regexp
355                 rebuild => 1,
356         },
357         wiki_file_prune_regexps => {
358                 type => "internal",
359                 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
360                         qr/\.x?html?$/, qr/\.ikiwiki-new$/,
361                         qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
362                         qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
363                         qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
364                 description => "regexps of source files to ignore",
365                 safe => 0,
366                 rebuild => 1,
367         },
368         wiki_file_chars => {
369                 type => "string",
370                 description => "specifies the characters that are allowed in source filenames",
371                 default => "-[:alnum:]+/.:_",
372                 safe => 0,
373                 rebuild => 1,
374         },
375         wiki_file_regexp => {
376                 type => "internal",
377                 description => "regexp of legal source files",
378                 safe => 0,
379                 rebuild => 1,
380         },
381         web_commit_regexp => {
382                 type => "internal",
383                 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
384                 description => "regexp to parse web commits from logs",
385                 safe => 0,
386                 rebuild => 0,
387         },
388         cgi => {
389                 type => "internal",
390                 default => 0,
391                 description => "run as a cgi",
392                 safe => 0,
393                 rebuild => 0,
394         },
395         cgi_disable_uploads => {
396                 type => "internal",
397                 default => 1,
398                 description => "whether CGI should accept file uploads",
399                 safe => 0,
400                 rebuild => 0,
401         },
402         post_commit => {
403                 type => "internal",
404                 default => 0,
405                 description => "run as a post-commit hook",
406                 safe => 0,
407                 rebuild => 0,
408         },
409         rebuild => {
410                 type => "internal",
411                 default => 0,
412                 description => "running in rebuild mode",
413                 safe => 0,
414                 rebuild => 0,
415         },
416         setup => {
417                 type => "internal",
418                 default => undef,
419                 description => "running in setup mode",
420                 safe => 0,
421                 rebuild => 0,
422         },
423         clean => {
424                 type => "internal",
425                 default => 0,
426                 description => "running in clean mode",
427                 safe => 0,
428                 rebuild => 0,
429         },
430         refresh => {
431                 type => "internal",
432                 default => 0,
433                 description => "running in refresh mode",
434                 safe => 0,
435                 rebuild => 0,
436         },
437         test_receive => {
438                 type => "internal",
439                 default => 0,
440                 description => "running in receive test mode",
441                 safe => 0,
442                 rebuild => 0,
443         },
444         gettime => {
445                 type => "internal",
446                 description => "running in gettime mode",
447                 safe => 0,
448                 rebuild => 0,
449         },
450         w3mmode => {
451                 type => "internal",
452                 default => 0,
453                 description => "running in w3mmode",
454                 safe => 0,
455                 rebuild => 0,
456         },
457         wikistatedir => {
458                 type => "internal",
459                 default => undef,
460                 description => "path to the .ikiwiki directory holding ikiwiki state",
461                 safe => 0,
462                 rebuild => 0,
463         },
464         setupfile => {
465                 type => "internal",
466                 default => undef,
467                 description => "path to setup file",
468                 safe => 0,
469                 rebuild => 0,
470         },
471         setuptype => {
472                 type => "internal",
473                 default => "Standard",
474                 description => "perl class to use to dump setup file",
475                 safe => 0,
476                 rebuild => 0,
477         },
478         allow_symlinks_before_srcdir => {
479                 type => "boolean",
480                 default => 0,
481                 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
482                 safe => 0,
483                 rebuild => 0,
484         },
487 sub defaultconfig () {
488         my %s=getsetup();
489         my @ret;
490         foreach my $key (keys %s) {
491                 push @ret, $key, $s{$key}->{default};
492         }
493         use Data::Dumper;
494         return @ret;
497 sub checkconfig () {
498         # locale stuff; avoid LC_ALL since it overrides everything
499         if (defined $ENV{LC_ALL}) {
500                 $ENV{LANG} = $ENV{LC_ALL};
501                 delete $ENV{LC_ALL};
502         }
503         if (defined $config{locale}) {
504                 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
505                         $ENV{LANG}=$config{locale};
506                         define_gettext();
507                 }
508         }
509                 
510         if (! defined $config{wiki_file_regexp}) {
511                 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
512         }
514         if (ref $config{ENV} eq 'HASH') {
515                 foreach my $val (keys %{$config{ENV}}) {
516                         $ENV{$val}=$config{ENV}{$val};
517                 }
518         }
520         if ($config{w3mmode}) {
521                 eval q{use Cwd q{abs_path}};
522                 error($@) if $@;
523                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
524                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
525                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
526                         unless $config{cgiurl} =~ m!file:///!;
527                 $config{url}="file://".$config{destdir};
528         }
530         if ($config{cgi} && ! length $config{url}) {
531                 error(gettext("Must specify url to wiki with --url when using --cgi"));
532         }
533         
534         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
535                 unless exists $config{wikistatedir} && defined $config{wikistatedir};
537         if (defined $config{umask}) {
538                 umask(possibly_foolish_untaint($config{umask}));
539         }
541         run_hooks(checkconfig => sub { shift->() });
543         return 1;
546 sub listplugins () {
547         my %ret;
549         foreach my $dir (@INC, $config{libdir}) {
550                 next unless defined $dir && length $dir;
551                 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
552                         my ($plugin)=$file=~/.*\/(.*)\.pm$/;
553                         $ret{$plugin}=1;
554                 }
555         }
556         foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
557                 next unless defined $dir && length $dir;
558                 foreach my $file (glob("$dir/plugins/*")) {
559                         $ret{basename($file)}=1 if -x $file;
560                 }
561         }
563         return keys %ret;
566 sub loadplugins () {
567         if (defined $config{libdir} && length $config{libdir}) {
568                 unshift @INC, possibly_foolish_untaint($config{libdir});
569         }
571         foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
572                 loadplugin($plugin);
573         }
574         
575         if ($config{rcs}) {
576                 if (exists $hooks{rcs}) {
577                         error(gettext("cannot use multiple rcs plugins"));
578                 }
579                 loadplugin($config{rcs});
580         }
581         if (! exists $hooks{rcs}) {
582                 loadplugin("norcs");
583         }
585         run_hooks(getopt => sub { shift->() });
586         if (grep /^-/, @ARGV) {
587                 print STDERR "Unknown option (or missing parameter): $_\n"
588                         foreach grep /^-/, @ARGV;
589                 usage();
590         }
592         return 1;
595 sub loadplugin ($) {
596         my $plugin=shift;
598         return if grep { $_ eq $plugin} @{$config{disable_plugins}};
600         foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
601                          "$installdir/lib/ikiwiki") {
602                 if (defined $dir && -x "$dir/plugins/$plugin") {
603                         eval { require IkiWiki::Plugin::external };
604                         if ($@) {
605                                 my $reason=$@;
606                                 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
607                         }
608                         import IkiWiki::Plugin::external "$dir/plugins/$plugin";
609                         $loaded_plugins{$plugin}=1;
610                         return 1;
611                 }
612         }
614         my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
615         eval qq{use $mod};
616         if ($@) {
617                 error("Failed to load plugin $mod: $@");
618         }
619         $loaded_plugins{$plugin}=1;
620         return 1;
623 sub error ($;$) {
624         my $message=shift;
625         my $cleaner=shift;
626         log_message('err' => $message) if $config{syslog};
627         if (defined $cleaner) {
628                 $cleaner->();
629         }
630         die $message."\n";
633 sub debug ($) {
634         return unless $config{verbose};
635         return log_message(debug => @_);
638 my $log_open=0;
639 sub log_message ($$) {
640         my $type=shift;
642         if ($config{syslog}) {
643                 require Sys::Syslog;
644                 if (! $log_open) {
645                         Sys::Syslog::setlogsock('unix');
646                         Sys::Syslog::openlog('ikiwiki', '', 'user');
647                         $log_open=1;
648                 }
649                 return eval {
650                         Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
651                 };
652         }
653         elsif (! $config{cgi}) {
654                 return print "@_\n";
655         }
656         else {
657                 return print STDERR "@_\n";
658         }
661 sub possibly_foolish_untaint ($) {
662         my $tainted=shift;
663         my ($untainted)=$tainted=~/(.*)/s;
664         return $untainted;
667 sub basename ($) {
668         my $file=shift;
670         $file=~s!.*/+!!;
671         return $file;
674 sub dirname ($) {
675         my $file=shift;
677         $file=~s!/*[^/]+$!!;
678         return $file;
681 sub isinternal ($) {
682         my $page=shift;
683         return exists $pagesources{$page} &&
684                 $pagesources{$page} =~ /\._([^.]+)$/;
687 sub pagetype ($) {
688         my $file=shift;
689         
690         if ($file =~ /\.([^.]+)$/) {
691                 return $1 if exists $hooks{htmlize}{$1};
692         }
693         my $base=basename($file);
694         if (exists $hooks{htmlize}{$base} &&
695             $hooks{htmlize}{$base}{noextension}) {
696                 return $base;
697         }
698         return;
701 my %pagename_cache;
703 sub pagename ($) {
704         my $file=shift;
706         if (exists $pagename_cache{$file}) {
707                 return $pagename_cache{$file};
708         }
710         my $type=pagetype($file);
711         my $page=$file;
712         $page=~s/\Q.$type\E*$//
713                 if defined $type && !$hooks{htmlize}{$type}{keepextension}
714                         && !$hooks{htmlize}{$type}{noextension};
715         if ($config{indexpages} && $page=~/(.*)\/index$/) {
716                 $page=$1;
717         }
719         $pagename_cache{$file} = $page;
720         return $page;
723 sub newpagefile ($$) {
724         my $page=shift;
725         my $type=shift;
727         if (! $config{indexpages} || $page eq 'index') {
728                 return $page.".".$type;
729         }
730         else {
731                 return $page."/index.".$type;
732         }
735 sub targetpage ($$;$) {
736         my $page=shift;
737         my $ext=shift;
738         my $filename=shift;
739         
740         if (defined $filename) {
741                 return $page."/".$filename.".".$ext;
742         }
743         elsif (! $config{usedirs} || $page eq 'index') {
744                 return $page.".".$ext;
745         }
746         else {
747                 return $page."/index.".$ext;
748         }
751 sub htmlpage ($) {
752         my $page=shift;
753         
754         return targetpage($page, $config{htmlext});
757 sub srcfile_stat {
758         my $file=shift;
759         my $nothrow=shift;
761         return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
762         foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
763                 return "$dir/$file", stat(_) if -e "$dir/$file";
764         }
765         error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
766         return;
769 sub srcfile ($;$) {
770         return (srcfile_stat(@_))[0];
773 sub add_underlay ($) {
774         my $dir=shift;
776         if ($dir !~ /^\//) {
777                 $dir="$config{underlaydirbase}/$dir";
778         }
780         if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
781                 unshift @{$config{underlaydirs}}, $dir;
782         }
784         return 1;
787 sub readfile ($;$$) {
788         my $file=shift;
789         my $binary=shift;
790         my $wantfd=shift;
792         if (-l $file) {
793                 error("cannot read a symlink ($file)");
794         }
795         
796         local $/=undef;
797         open (my $in, "<", $file) || error("failed to read $file: $!");
798         binmode($in) if ($binary);
799         return \*$in if $wantfd;
800         my $ret=<$in>;
801         # check for invalid utf-8, and toss it back to avoid crashes
802         if (! utf8::valid($ret)) {
803                 $ret=encode_utf8($ret);
804         }
805         close $in || error("failed to read $file: $!");
806         return $ret;
809 sub prep_writefile ($$) {
810         my $file=shift;
811         my $destdir=shift;
812         
813         my $test=$file;
814         while (length $test) {
815                 if (-l "$destdir/$test") {
816                         error("cannot write to a symlink ($test)");
817                 }
818                 $test=dirname($test);
819         }
821         my $dir=dirname("$destdir/$file");
822         if (! -d $dir) {
823                 my $d="";
824                 foreach my $s (split(m!/+!, $dir)) {
825                         $d.="$s/";
826                         if (! -d $d) {
827                                 mkdir($d) || error("failed to create directory $d: $!");
828                         }
829                 }
830         }
832         return 1;
835 sub writefile ($$$;$$) {
836         my $file=shift; # can include subdirs
837         my $destdir=shift; # directory to put file in
838         my $content=shift;
839         my $binary=shift;
840         my $writer=shift;
841         
842         prep_writefile($file, $destdir);
843         
844         my $newfile="$destdir/$file.ikiwiki-new";
845         if (-l $newfile) {
846                 error("cannot write to a symlink ($newfile)");
847         }
848         
849         my $cleanup = sub { unlink($newfile) };
850         open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
851         binmode($out) if ($binary);
852         if ($writer) {
853                 $writer->(\*$out, $cleanup);
854         }
855         else {
856                 print $out $content or error("failed writing to $newfile: $!", $cleanup);
857         }
858         close $out || error("failed saving $newfile: $!", $cleanup);
859         rename($newfile, "$destdir/$file") || 
860                 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
862         return 1;
865 my %cleared;
866 sub will_render ($$;$) {
867         my $page=shift;
868         my $dest=shift;
869         my $clear=shift;
871         # Important security check.
872         if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
873             ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
874                 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
875         }
877         if (! $clear || $cleared{$page}) {
878                 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
879         }
880         else {
881                 foreach my $old (@{$renderedfiles{$page}}) {
882                         delete $destsources{$old};
883                 }
884                 $renderedfiles{$page}=[$dest];
885                 $cleared{$page}=1;
886         }
887         $destsources{$dest}=$page;
889         return 1;
892 sub bestlink ($$) {
893         my $page=shift;
894         my $link=shift;
895         
896         my $cwd=$page;
897         if ($link=~s/^\/+//) {
898                 # absolute links
899                 $cwd="";
900         }
901         $link=~s/\/$//;
903         do {
904                 my $l=$cwd;
905                 $l.="/" if length $l;
906                 $l.=$link;
908                 if (exists $pagesources{$l}) {
909                         return $l;
910                 }
911                 elsif (exists $pagecase{lc $l}) {
912                         return $pagecase{lc $l};
913                 }
914         } while $cwd=~s{/?[^/]+$}{};
916         if (length $config{userdir}) {
917                 my $l = "$config{userdir}/".lc($link);
918                 if (exists $pagesources{$l}) {
919                         return $l;
920                 }
921                 elsif (exists $pagecase{lc $l}) {
922                         return $pagecase{lc $l};
923                 }
924         }
926         #print STDERR "warning: page $page, broken link: $link\n";
927         return "";
930 sub isinlinableimage ($) {
931         my $file=shift;
932         
933         return $file =~ /\.(png|gif|jpg|jpeg)$/i;
936 sub pagetitle ($;$) {
937         my $page=shift;
938         my $unescaped=shift;
940         if ($unescaped) {
941                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
942         }
943         else {
944                 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
945         }
947         return $page;
950 sub titlepage ($) {
951         my $title=shift;
952         # support use w/o %config set
953         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
954         $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
955         return $title;
958 sub linkpage ($) {
959         my $link=shift;
960         my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
961         $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
962         return $link;
965 sub cgiurl (@) {
966         my %params=@_;
968         my $cgiurl=$config{cgiurl};
969         if (exists $params{cgiurl}) {
970                 $cgiurl=$params{cgiurl};
971                 delete $params{cgiurl};
972         }
973         return $cgiurl."?".
974                 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
977 sub baseurl (;$) {
978         my $page=shift;
980         return "$config{url}/" if ! defined $page;
981         
982         $page=htmlpage($page);
983         $page=~s/[^\/]+$//;
984         $page=~s/[^\/]+\//..\//g;
985         return $page;
988 sub abs2rel ($$) {
989         # Work around very innefficient behavior in File::Spec if abs2rel
990         # is passed two relative paths. It's much faster if paths are
991         # absolute! (Debian bug #376658; fixed in debian unstable now)
992         my $path="/".shift;
993         my $base="/".shift;
995         require File::Spec;
996         my $ret=File::Spec->abs2rel($path, $base);
997         $ret=~s/^// if defined $ret;
998         return $ret;
1001 sub displaytime ($;$$) {
1002         # Plugins can override this function to mark up the time to
1003         # display.
1004         my $time=formattime($_[0], $_[1]);
1005         if ($config{html5}) {
1006                 return '<time datetime="'.date_3339($_[0]).'"'.
1007                         ($_[2] ? ' pubdate="pubdate"' : '').
1008                         '>'.$time.'</time>';
1009         }
1010         else {
1011                 return '<span class="date">'.$time.'</span>';
1012         }
1015 sub formattime ($;$) {
1016         # Plugins can override this function to format the time.
1017         my $time=shift;
1018         my $format=shift;
1019         if (! defined $format) {
1020                 $format=$config{timeformat};
1021         }
1023         # strftime doesn't know about encodings, so make sure
1024         # its output is properly treated as utf8
1025         return decode_utf8(POSIX::strftime($format, localtime($time)));
1028 sub date_3339 ($) {
1029         my $time=shift;
1031         my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1032         POSIX::setlocale(&POSIX::LC_TIME, "C");
1033         my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1034         POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1035         return $ret;
1038 sub beautify_urlpath ($) {
1039         my $url=shift;
1041         # Ensure url is not an empty link, and if necessary,
1042         # add ./ to avoid colon confusion.
1043         if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1044                 $url="./$url";
1045         }
1047         if ($config{usedirs}) {
1048                 $url =~ s!/index.$config{htmlext}$!/!;
1049         }
1051         return $url;
1054 sub urlto ($$;$) {
1055         my $to=shift;
1056         my $from=shift;
1057         my $absolute=shift;
1058         
1059         if (! length $to) {
1060                 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1061         }
1063         if (! $destsources{$to}) {
1064                 $to=htmlpage($to);
1065         }
1067         if ($absolute) {
1068                 return $config{url}.beautify_urlpath("/".$to);
1069         }
1071         my $link = abs2rel($to, dirname(htmlpage($from)));
1073         return beautify_urlpath($link);
1076 sub htmllink ($$$;@) {
1077         my $lpage=shift; # the page doing the linking
1078         my $page=shift; # the page that will contain the link (different for inline)
1079         my $link=shift;
1080         my %opts=@_;
1082         $link=~s/\/$//;
1084         my $bestlink;
1085         if (! $opts{forcesubpage}) {
1086                 $bestlink=bestlink($lpage, $link);
1087         }
1088         else {
1089                 $bestlink="$lpage/".lc($link);
1090         }
1092         my $linktext;
1093         if (defined $opts{linktext}) {
1094                 $linktext=$opts{linktext};
1095         }
1096         else {
1097                 $linktext=pagetitle(basename($link));
1098         }
1099         
1100         return "<span class=\"selflink\">$linktext</span>"
1101                 if length $bestlink && $page eq $bestlink &&
1102                    ! defined $opts{anchor};
1103         
1104         if (! $destsources{$bestlink}) {
1105                 $bestlink=htmlpage($bestlink);
1107                 if (! $destsources{$bestlink}) {
1108                         my $cgilink = "";
1109                         if (length $config{cgiurl}) {
1110                                 $cgilink = "<a href=\"".
1111                                         cgiurl(
1112                                                 do => "create",
1113                                                 page => lc($link),
1114                                                 from => $lpage
1115                                         )."\" rel=\"nofollow\">?</a>";
1116                         }
1117                         return "<span class=\"createlink\">$cgilink$linktext</span>"
1118                 }
1119         }
1120         
1121         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1122         $bestlink=beautify_urlpath($bestlink);
1123         
1124         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1125                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1126         }
1128         if (defined $opts{anchor}) {
1129                 $bestlink.="#".$opts{anchor};
1130         }
1132         my @attrs;
1133         foreach my $attr (qw{rel class title}) {
1134                 if (defined $opts{$attr}) {
1135                         push @attrs, " $attr=\"$opts{$attr}\"";
1136                 }
1137         }
1139         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1142 sub userpage ($) {
1143         my $user=shift;
1144         return length $config{userdir} ? "$config{userdir}/$user" : $user;
1147 sub openiduser ($) {
1148         my $user=shift;
1150         if ($user =~ m!^https?://! &&
1151             eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1152                 my $display;
1154                 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1155                         $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1156                 }
1157                 else {
1158                         # backcompat with old version
1159                         my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1160                         $display=$oid->display;
1161                 }
1163                 # Convert "user.somehost.com" to "user [somehost.com]"
1164                 # (also "user.somehost.co.uk")
1165                 if ($display !~ /\[/) {
1166                         $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1167                 }
1168                 # Convert "http://somehost.com/user" to "user [somehost.com]".
1169                 # (also "https://somehost.com/user/")
1170                 if ($display !~ /\[/) {
1171                         $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1172                 }
1173                 $display=~s!^https?://!!; # make sure this is removed
1174                 eval q{use CGI 'escapeHTML'};
1175                 error($@) if $@;
1176                 return escapeHTML($display);
1177         }
1178         return;
1181 sub htmlize ($$$$) {
1182         my $page=shift;
1183         my $destpage=shift;
1184         my $type=shift;
1185         my $content=shift;
1186         
1187         my $oneline = $content !~ /\n/;
1188         
1189         if (exists $hooks{htmlize}{$type}) {
1190                 $content=$hooks{htmlize}{$type}{call}->(
1191                         page => $page,
1192                         content => $content,
1193                 );
1194         }
1195         else {
1196                 error("htmlization of $type not supported");
1197         }
1199         run_hooks(sanitize => sub {
1200                 $content=shift->(
1201                         page => $page,
1202                         destpage => $destpage,
1203                         content => $content,
1204                 );
1205         });
1206         
1207         if ($oneline) {
1208                 # hack to get rid of enclosing junk added by markdown
1209                 # and other htmlizers/sanitizers
1210                 $content=~s/^<p>//i;
1211                 $content=~s/<\/p>\n*$//i;
1212         }
1214         return $content;
1217 sub linkify ($$$) {
1218         my $page=shift;
1219         my $destpage=shift;
1220         my $content=shift;
1222         run_hooks(linkify => sub {
1223                 $content=shift->(
1224                         page => $page,
1225                         destpage => $destpage,
1226                         content => $content,
1227                 );
1228         });
1229         
1230         return $content;
1233 our %preprocessing;
1234 our $preprocess_preview=0;
1235 sub preprocess ($$$;$$) {
1236         my $page=shift; # the page the data comes from
1237         my $destpage=shift; # the page the data will appear in (different for inline)
1238         my $content=shift;
1239         my $scan=shift;
1240         my $preview=shift;
1242         # Using local because it needs to be set within any nested calls
1243         # of this function.
1244         local $preprocess_preview=$preview if defined $preview;
1246         my $handle=sub {
1247                 my $escape=shift;
1248                 my $prefix=shift;
1249                 my $command=shift;
1250                 my $params=shift;
1251                 $params="" if ! defined $params;
1253                 if (length $escape) {
1254                         return "[[$prefix$command $params]]";
1255                 }
1256                 elsif (exists $hooks{preprocess}{$command}) {
1257                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1258                         # Note: preserve order of params, some plugins may
1259                         # consider it significant.
1260                         my @params;
1261                         while ($params =~ m{
1262                                 (?:([-\w]+)=)?          # 1: named parameter key?
1263                                 (?:
1264                                         """(.*?)"""     # 2: triple-quoted value
1265                                 |
1266                                         "([^"]*?)"      # 3: single-quoted value
1267                                 |
1268                                         (\S+)           # 4: unquoted value
1269                                 )
1270                                 (?:\s+|$)               # delimiter to next param
1271                         }sgx) {
1272                                 my $key=$1;
1273                                 my $val;
1274                                 if (defined $2) {
1275                                         $val=$2;
1276                                         $val=~s/\r\n/\n/mg;
1277                                         $val=~s/^\n+//g;
1278                                         $val=~s/\n+$//g;
1279                                 }
1280                                 elsif (defined $3) {
1281                                         $val=$3;
1282                                 }
1283                                 elsif (defined $4) {
1284                                         $val=$4;
1285                                 }
1287                                 if (defined $key) {
1288                                         push @params, $key, $val;
1289                                 }
1290                                 else {
1291                                         push @params, $val, '';
1292                                 }
1293                         }
1294                         if ($preprocessing{$page}++ > 3) {
1295                                 # Avoid loops of preprocessed pages preprocessing
1296                                 # other pages that preprocess them, etc.
1297                                 return "[[!$command <span class=\"error\">".
1298                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1299                                                 $page, $preprocessing{$page}).
1300                                         "</span>]]";
1301                         }
1302                         my $ret;
1303                         if (! $scan) {
1304                                 $ret=eval {
1305                                         $hooks{preprocess}{$command}{call}->(
1306                                                 @params,
1307                                                 page => $page,
1308                                                 destpage => $destpage,
1309                                                 preview => $preprocess_preview,
1310                                         );
1311                                 };
1312                                 if ($@) {
1313                                         my $error=$@;
1314                                         chomp $error;
1315                                         $ret="[[!$command <span class=\"error\">".
1316                                                 gettext("Error").": $error"."</span>]]";
1317                                 }
1318                         }
1319                         else {
1320                                 # use void context during scan pass
1321                                 eval {
1322                                         $hooks{preprocess}{$command}{call}->(
1323                                                 @params,
1324                                                 page => $page,
1325                                                 destpage => $destpage,
1326                                                 preview => $preprocess_preview,
1327                                         );
1328                                 };
1329                                 $ret="";
1330                         }
1331                         $preprocessing{$page}--;
1332                         return $ret;
1333                 }
1334                 else {
1335                         return "[[$prefix$command $params]]";
1336                 }
1337         };
1338         
1339         my $regex;
1340         if ($config{prefix_directives}) {
1341                 $regex = qr{
1342                         (\\?)           # 1: escape?
1343                         \[\[(!)         # directive open; 2: prefix
1344                         ([-\w]+)        # 3: command
1345                         (               # 4: the parameters..
1346                                 \s+     # Must have space if parameters present
1347                                 (?:
1348                                         (?:[-\w]+=)?            # named parameter key?
1349                                         (?:
1350                                                 """.*?"""       # triple-quoted value
1351                                                 |
1352                                                 "[^"]*?"        # single-quoted value
1353                                                 |
1354                                                 [^"\s\]]+       # unquoted value
1355                                         )
1356                                         \s*                     # whitespace or end
1357                                                                 # of directive
1358                                 )
1359                         *)?             # 0 or more parameters
1360                         \]\]            # directive closed
1361                 }sx;
1362         }
1363         else {
1364                 $regex = qr{
1365                         (\\?)           # 1: escape?
1366                         \[\[(!?)        # directive open; 2: optional prefix
1367                         ([-\w]+)        # 3: command
1368                         \s+
1369                         (               # 4: the parameters..
1370                                 (?:
1371                                         (?:[-\w]+=)?            # named parameter key?
1372                                         (?:
1373                                                 """.*?"""       # triple-quoted value
1374                                                 |
1375                                                 "[^"]*?"        # single-quoted value
1376                                                 |
1377                                                 [^"\s\]]+       # unquoted value
1378                                         )
1379                                         \s*                     # whitespace or end
1380                                                                 # of directive
1381                                 )
1382                         *)              # 0 or more parameters
1383                         \]\]            # directive closed
1384                 }sx;
1385         }
1387         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1388         return $content;
1391 sub filter ($$$) {
1392         my $page=shift;
1393         my $destpage=shift;
1394         my $content=shift;
1396         run_hooks(filter => sub {
1397                 $content=shift->(page => $page, destpage => $destpage, 
1398                         content => $content);
1399         });
1401         return $content;
1404 sub check_canedit ($$$;$) {
1405         my $page=shift;
1406         my $q=shift;
1407         my $session=shift;
1408         my $nonfatal=shift;
1409         
1410         my $canedit;
1411         run_hooks(canedit => sub {
1412                 return if defined $canedit;
1413                 my $ret=shift->($page, $q, $session);
1414                 if (defined $ret) {
1415                         if ($ret eq "") {
1416                                 $canedit=1;
1417                         }
1418                         elsif (ref $ret eq 'CODE') {
1419                                 $ret->() unless $nonfatal;
1420                                 $canedit=0;
1421                         }
1422                         elsif (defined $ret) {
1423                                 error($ret) unless $nonfatal;
1424                                 $canedit=0;
1425                         }
1426                 }
1427         });
1428         return defined $canedit ? $canedit : 1;
1431 sub check_content (@) {
1432         my %params=@_;
1433         
1434         return 1 if ! exists $hooks{checkcontent}; # optimisation
1436         if (exists $pagesources{$params{page}}) {
1437                 my @diff;
1438                 my %old=map { $_ => 1 }
1439                         split("\n", readfile(srcfile($pagesources{$params{page}})));
1440                 foreach my $line (split("\n", $params{content})) {
1441                         push @diff, $line if ! exists $old{$line};
1442                 }
1443                 $params{diff}=join("\n", @diff);
1444         }
1446         my $ok;
1447         run_hooks(checkcontent => sub {
1448                 return if defined $ok;
1449                 my $ret=shift->(%params);
1450                 if (defined $ret) {
1451                         if ($ret eq "") {
1452                                 $ok=1;
1453                         }
1454                         elsif (ref $ret eq 'CODE') {
1455                                 $ret->() unless $params{nonfatal};
1456                                 $ok=0;
1457                         }
1458                         elsif (defined $ret) {
1459                                 error($ret) unless $params{nonfatal};
1460                                 $ok=0;
1461                         }
1462                 }
1464         });
1465         return defined $ok ? $ok : 1;
1468 my $wikilock;
1470 sub lockwiki () {
1471         # Take an exclusive lock on the wiki to prevent multiple concurrent
1472         # run issues. The lock will be dropped on program exit.
1473         if (! -d $config{wikistatedir}) {
1474                 mkdir($config{wikistatedir});
1475         }
1476         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1477                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1478         if (! flock($wikilock, 2)) { # LOCK_EX
1479                 error("failed to get lock");
1480         }
1481         return 1;
1484 sub unlockwiki () {
1485         POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1486         return close($wikilock) if $wikilock;
1487         return;
1490 my $commitlock;
1492 sub commit_hook_enabled () {
1493         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1494                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1495         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1496                 close($commitlock) || error("failed closing commitlock: $!");
1497                 return 0;
1498         }
1499         close($commitlock) || error("failed closing commitlock: $!");
1500         return 1;
1503 sub disable_commit_hook () {
1504         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1505                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1506         if (! flock($commitlock, 2)) { # LOCK_EX
1507                 error("failed to get commit lock");
1508         }
1509         return 1;
1512 sub enable_commit_hook () {
1513         return close($commitlock) if $commitlock;
1514         return;
1517 sub loadindex () {
1518         %oldrenderedfiles=%pagectime=();
1519         if (! $config{rebuild}) {
1520                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1521                 %destsources=%renderedfiles=%pagecase=%pagestate=
1522                 %depends_simple=%typedlinks=%oldtypedlinks=();
1523         }
1524         my $in;
1525         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1526                 if (-e "$config{wikistatedir}/index") {
1527                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1528                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1529                 }
1530                 else {
1531                         $config{gettime}=1; # first build
1532                         return;
1533                 }
1534         }
1536         my $index=Storable::fd_retrieve($in);
1537         if (! defined $index) {
1538                 return 0;
1539         }
1541         my $pages;
1542         if (exists $index->{version} && ! ref $index->{version}) {
1543                 $pages=$index->{page};
1544                 %wikistate=%{$index->{state}};
1545         }
1546         else {
1547                 $pages=$index;
1548                 %wikistate=();
1549         }
1551         foreach my $src (keys %$pages) {
1552                 my $d=$pages->{$src};
1553                 my $page=pagename($src);
1554                 $pagectime{$page}=$d->{ctime};
1555                 $pagesources{$page}=$src;
1556                 if (! $config{rebuild}) {
1557                         $pagemtime{$page}=$d->{mtime};
1558                         $renderedfiles{$page}=$d->{dest};
1559                         if (exists $d->{links} && ref $d->{links}) {
1560                                 $links{$page}=$d->{links};
1561                                 $oldlinks{$page}=[@{$d->{links}}];
1562                         }
1563                         if (ref $d->{depends_simple} eq 'ARRAY') {
1564                                 # old format
1565                                 $depends_simple{$page}={
1566                                         map { $_ => 1 } @{$d->{depends_simple}}
1567                                 };
1568                         }
1569                         elsif (exists $d->{depends_simple}) {
1570                                 $depends_simple{$page}=$d->{depends_simple};
1571                         }
1572                         if (exists $d->{dependslist}) {
1573                                 # old format
1574                                 $depends{$page}={
1575                                         map { $_ => $DEPEND_CONTENT }
1576                                                 @{$d->{dependslist}}
1577                                 };
1578                         }
1579                         elsif (exists $d->{depends} && ! ref $d->{depends}) {
1580                                 # old format
1581                                 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1582                         }
1583                         elsif (exists $d->{depends}) {
1584                                 $depends{$page}=$d->{depends};
1585                         }
1586                         if (exists $d->{state}) {
1587                                 $pagestate{$page}=$d->{state};
1588                         }
1589                         if (exists $d->{typedlinks}) {
1590                                 $typedlinks{$page}=$d->{typedlinks};
1592                                 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1593                                         next unless %$links;
1594                                         $oldtypedlinks{$page}{$type} = {%$links};
1595                                 }
1596                         }
1597                 }
1598                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1599         }
1600         foreach my $page (keys %pagesources) {
1601                 $pagecase{lc $page}=$page;
1602         }
1603         foreach my $page (keys %renderedfiles) {
1604                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1605         }
1606         return close($in);
1609 sub saveindex () {
1610         run_hooks(savestate => sub { shift->() });
1612         my %hookids;
1613         foreach my $type (keys %hooks) {
1614                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1615         }
1616         my @hookids=keys %hookids;
1618         if (! -d $config{wikistatedir}) {
1619                 mkdir($config{wikistatedir});
1620         }
1621         my $newfile="$config{wikistatedir}/indexdb.new";
1622         my $cleanup = sub { unlink($newfile) };
1623         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1625         my %index;
1626         foreach my $page (keys %pagemtime) {
1627                 next unless $pagemtime{$page};
1628                 my $src=$pagesources{$page};
1630                 $index{page}{$src}={
1631                         ctime => $pagectime{$page},
1632                         mtime => $pagemtime{$page},
1633                         dest => $renderedfiles{$page},
1634                         links => $links{$page},
1635                 };
1637                 if (exists $depends{$page}) {
1638                         $index{page}{$src}{depends} = $depends{$page};
1639                 }
1641                 if (exists $depends_simple{$page}) {
1642                         $index{page}{$src}{depends_simple} = $depends_simple{$page};
1643                 }
1645                 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1646                         $index{page}{$src}{typedlinks} = $typedlinks{$page};
1647                 }
1649                 if (exists $pagestate{$page}) {
1650                         foreach my $id (@hookids) {
1651                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1652                                         $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1653                                 }
1654                         }
1655                 }
1656         }
1658         $index{state}={};
1659         foreach my $id (@hookids) {
1660                 foreach my $key (keys %{$wikistate{$id}}) {
1661                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
1662                 }
1663         }
1664         
1665         $index{version}="3";
1666         my $ret=Storable::nstore_fd(\%index, $out);
1667         return if ! defined $ret || ! $ret;
1668         close $out || error("failed saving to $newfile: $!", $cleanup);
1669         rename($newfile, "$config{wikistatedir}/indexdb") ||
1670                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1671         
1672         return 1;
1675 sub template_file ($) {
1676         my $name=shift;
1677         
1678         my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1679         if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1680                 $tpage=$pagesources{$tpage};
1681                 $name.=".tmpl";
1682         }
1684         my $template=srcfile($tpage, 1);
1685         if (defined $template) {
1686                 return $template, $tpage, 1 if wantarray;
1687                 return $template;
1688         }
1689         else {
1690                 $name=~s:/::; # avoid path traversal
1691                 foreach my $dir ($config{templatedir},
1692                                  "$installdir/share/ikiwiki/templates") {
1693                         if (-e "$dir/$name") {
1694                                 $template="$dir/$name";
1695                                 last;
1696                         }
1697                 }
1698                 if (defined $template) {        
1699                         return $template, $tpage if wantarray;
1700                         return $template;
1701                 }
1702         }
1704         return;
1707 sub template_depends ($$;@) {
1708         my $name=shift;
1709         my $page=shift;
1710         
1711         my ($filename, $tpage, $untrusted)=template_file($name);
1712         if (defined $page && defined $tpage) {
1713                 add_depends($page, $tpage);
1714         }
1716         return unless defined $filename;
1718         my @opts=(
1719                 filter => sub {
1720                         my $text_ref = shift;
1721                         ${$text_ref} = decode_utf8(${$text_ref});
1722                 },
1723                 loop_context_vars => 1,
1724                 die_on_bad_params => 0,
1725                 filename => $filename,
1726                 @_,
1727                 ($untrusted ? (no_includes => 1) : ()),
1728         );
1729         return @opts if wantarray;
1731         require HTML::Template;
1732         return HTML::Template->new(@opts);
1735 sub template ($;@) {
1736         template_depends(shift, undef, @_);
1739 sub misctemplate ($$;@) {
1740         my $title=shift;
1741         my $content=shift;
1742         
1743         my $template=template("page.tmpl");
1745         run_hooks(pagetemplate => sub {
1746                 shift->(page => "", destpage => "", template => $template);
1747         });
1748         templateactions($template, "");
1750         $template->param(
1751                 dynamic => 1,
1752                 title => $title,
1753                 wikiname => $config{wikiname},
1754                 content => $content,
1755                 baseurl => baseurl(),
1756                 html5 => $config{html5},
1757                 @_,
1758         );
1759         
1760         return $template->output;
1763 sub templateactions ($$) {
1764         my $template=shift;
1765         my $page=shift;
1767         my $have_actions=0;
1768         my @actions;
1769         run_hooks(pageactions => sub {
1770                 push @actions, map { { action => $_ } } 
1771                         grep { defined } shift->(page => $page);
1772         });
1773         $template->param(actions => \@actions);
1775         if ($config{cgiurl} && exists $hooks{auth}) {
1776                 $template->param(prefsurl => cgiurl(do => "prefs"));
1777                 $have_actions=1;
1778         }
1780         if ($have_actions || @actions) {
1781                 $template->param(have_actions => 1);
1782         }
1785 sub hook (@) {
1786         my %param=@_;
1787         
1788         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1789                 error 'hook requires type, call, and id parameters';
1790         }
1792         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1793         
1794         $hooks{$param{type}}{$param{id}}=\%param;
1795         return 1;
1798 sub run_hooks ($$) {
1799         # Calls the given sub for each hook of the given type,
1800         # passing it the hook function to call.
1801         my $type=shift;
1802         my $sub=shift;
1804         if (exists $hooks{$type}) {
1805                 my (@first, @middle, @last);
1806                 foreach my $id (keys %{$hooks{$type}}) {
1807                         if ($hooks{$type}{$id}{first}) {
1808                                 push @first, $id;
1809                         }
1810                         elsif ($hooks{$type}{$id}{last}) {
1811                                 push @last, $id;
1812                         }
1813                         else {
1814                                 push @middle, $id;
1815                         }
1816                 }
1817                 foreach my $id (@first, @middle, @last) {
1818                         $sub->($hooks{$type}{$id}{call});
1819                 }
1820         }
1822         return 1;
1825 sub rcs_update () {
1826         $hooks{rcs}{rcs_update}{call}->(@_);
1829 sub rcs_prepedit ($) {
1830         $hooks{rcs}{rcs_prepedit}{call}->(@_);
1833 sub rcs_commit ($$$;$$) {
1834         $hooks{rcs}{rcs_commit}{call}->(@_);
1837 sub rcs_commit_staged ($$$) {
1838         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1841 sub rcs_add ($) {
1842         $hooks{rcs}{rcs_add}{call}->(@_);
1845 sub rcs_remove ($) {
1846         $hooks{rcs}{rcs_remove}{call}->(@_);
1849 sub rcs_rename ($$) {
1850         $hooks{rcs}{rcs_rename}{call}->(@_);
1853 sub rcs_recentchanges ($) {
1854         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1857 sub rcs_diff ($) {
1858         $hooks{rcs}{rcs_diff}{call}->(@_);
1861 sub rcs_getctime ($) {
1862         $hooks{rcs}{rcs_getctime}{call}->(@_);
1865 sub rcs_getmtime ($) {
1866         $hooks{rcs}{rcs_getmtime}{call}->(@_);
1869 sub rcs_receive () {
1870         $hooks{rcs}{rcs_receive}{call}->();
1873 sub add_depends ($$;$) {
1874         my $page=shift;
1875         my $pagespec=shift;
1876         my $deptype=shift || $DEPEND_CONTENT;
1878         # Is the pagespec a simple page name?
1879         if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1880             $pagespec !~ /[\s*?()!]/) {
1881                 $depends_simple{$page}{lc $pagespec} |= $deptype;
1882                 return 1;
1883         }
1885         # Add explicit dependencies for influences.
1886         my $sub=pagespec_translate($pagespec);
1887         return unless defined $sub;
1888         foreach my $p (keys %pagesources) {
1889                 my $r=$sub->($p, location => $page);
1890                 my $i=$r->influences;
1891                 my $static=$r->influences_static;
1892                 foreach my $k (keys %$i) {
1893                         next unless $r || $static || $k eq $page;
1894                         $depends_simple{$page}{lc $k} |= $i->{$k};
1895                 }
1896                 last if $static;
1897         }
1899         $depends{$page}{$pagespec} |= $deptype;
1900         return 1;
1903 sub deptype (@) {
1904         my $deptype=0;
1905         foreach my $type (@_) {
1906                 if ($type eq 'presence') {
1907                         $deptype |= $DEPEND_PRESENCE;
1908                 }
1909                 elsif ($type eq 'links') { 
1910                         $deptype |= $DEPEND_LINKS;
1911                 }
1912                 elsif ($type eq 'content') {
1913                         $deptype |= $DEPEND_CONTENT;
1914                 }
1915         }
1916         return $deptype;
1919 my $file_prune_regexp;
1920 sub file_pruned ($) {
1921         my $file=shift;
1923         if (defined $config{include} && length $config{include}) {
1924                 return 0 if $file =~ m/$config{include}/;
1925         }
1927         if (! defined $file_prune_regexp) {
1928                 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1929                 $file_prune_regexp=qr/$file_prune_regexp/;
1930         }
1931         return $file =~ m/$file_prune_regexp/;
1934 sub define_gettext () {
1935         # If translation is needed, redefine the gettext function to do it.
1936         # Otherwise, it becomes a quick no-op.
1937         my $gettext_obj;
1938         my $getobj;
1939         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1940             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1941             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1942                 $getobj=sub {
1943                         $gettext_obj=eval q{
1944                                 use Locale::gettext q{textdomain};
1945                                 Locale::gettext->domain('ikiwiki')
1946                         };
1947                 };
1948         }
1950         no warnings 'redefine';
1951         *gettext=sub {
1952                 $getobj->() if $getobj;
1953                 if ($gettext_obj) {
1954                         $gettext_obj->get(shift);
1955                 }
1956                 else {
1957                         return shift;
1958                 }
1959         };
1960         *ngettext=sub {
1961                 $getobj->() if $getobj;
1962                 if ($gettext_obj) {
1963                         $gettext_obj->nget(@_);
1964                 }
1965                 else {
1966                         return ($_[2] == 1 ? $_[0] : $_[1])
1967                 }
1968         };
1971 sub gettext {
1972         define_gettext();
1973         gettext(@_);
1976 sub ngettext {
1977         define_gettext();
1978         ngettext(@_);
1981 sub yesno ($) {
1982         my $val=shift;
1984         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1987 sub inject {
1988         # Injects a new function into the symbol table to replace an
1989         # exported function.
1990         my %params=@_;
1992         # This is deep ugly perl foo, beware.
1993         no strict;
1994         no warnings;
1995         if (! defined $params{parent}) {
1996                 $params{parent}='::';
1997                 $params{old}=\&{$params{name}};
1998                 $params{name}=~s/.*:://;
1999         }
2000         my $parent=$params{parent};
2001         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2002                 $ns = $params{parent} . $ns;
2003                 inject(%params, parent => $ns) unless $ns eq '::main::';
2004                 *{$ns . $params{name}} = $params{call}
2005                         if exists ${$ns}{$params{name}} &&
2006                            \&{${$ns}{$params{name}}} == $params{old};
2007         }
2008         use strict;
2009         use warnings;
2012 sub add_link ($$;$) {
2013         my $page=shift;
2014         my $link=shift;
2015         my $type=shift;
2017         push @{$links{$page}}, $link
2018                 unless grep { $_ eq $link } @{$links{$page}};
2020         if (defined $type) {
2021                 $typedlinks{$page}{$type}{$link} = 1;
2022         }
2025 sub add_autofile ($$$) {
2026         my $file=shift;
2027         my $plugin=shift;
2028         my $generator=shift;
2029         
2030         $autofiles{$file}{plugin}=$plugin;
2031         $autofiles{$file}{generator}=$generator;
2034 sub sortspec_translate ($$) {
2035         my $spec = shift;
2036         my $reverse = shift;
2038         my $code = "";
2039         my @data;
2040         while ($spec =~ m{
2041                 \s*
2042                 (-?)            # group 1: perhaps negated
2043                 \s*
2044                 (               # group 2: a word
2045                         \w+\([^\)]*\)   # command(params)
2046                         |
2047                         [^\s]+          # or anything else
2048                 )
2049                 \s*
2050         }gx) {
2051                 my $negated = $1;
2052                 my $word = $2;
2053                 my $params = undef;
2055                 if ($word =~ m/^(\w+)\((.*)\)$/) {
2056                         # command with parameters
2057                         $params = $2;
2058                         $word = $1;
2059                 }
2060                 elsif ($word !~ m/^\w+$/) {
2061                         error(sprintf(gettext("invalid sort type %s"), $word));
2062                 }
2064                 if (length $code) {
2065                         $code .= " || ";
2066                 }
2068                 if ($negated) {
2069                         $code .= "-";
2070                 }
2072                 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2073                         if (defined $params) {
2074                                 push @data, $params;
2075                                 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2076                         }
2077                         else {
2078                                 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2079                         }
2080                 }
2081                 else {
2082                         error(sprintf(gettext("unknown sort type %s"), $word));
2083                 }
2084         }
2086         if (! length $code) {
2087                 # undefined sorting method... sort arbitrarily
2088                 return sub { 0 };
2089         }
2091         if ($reverse) {
2092                 $code="-($code)";
2093         }
2095         no warnings;
2096         return eval 'sub { '.$code.' }';
2099 sub pagespec_translate ($) {
2100         my $spec=shift;
2102         # Convert spec to perl code.
2103         my $code="";
2104         my @data;
2105         while ($spec=~m{
2106                 \s*             # ignore whitespace
2107                 (               # 1: match a single word
2108                         \!              # !
2109                 |
2110                         \(              # (
2111                 |
2112                         \)              # )
2113                 |
2114                         \w+\([^\)]*\)   # command(params)
2115                 |
2116                         [^\s()]+        # any other text
2117                 )
2118                 \s*             # ignore whitespace
2119         }gx) {
2120                 my $word=$1;
2121                 if (lc $word eq 'and') {
2122                         $code.=' &';
2123                 }
2124                 elsif (lc $word eq 'or') {
2125                         $code.=' |';
2126                 }
2127                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2128                         $code.=' '.$word;
2129                 }
2130                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2131                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2132                                 push @data, $2;
2133                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2134                         }
2135                         else {
2136                                 push @data, qq{unknown function in pagespec "$word"};
2137                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2138                         }
2139                 }
2140                 else {
2141                         push @data, $word;
2142                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2143                 }
2144         }
2146         if (! length $code) {
2147                 $code="IkiWiki::FailReason->new('empty pagespec')";
2148         }
2150         no warnings;
2151         return eval 'sub { my $page=shift; '.$code.' }';
2154 sub pagespec_match ($$;@) {
2155         my $page=shift;
2156         my $spec=shift;
2157         my @params=@_;
2159         # Backwards compatability with old calling convention.
2160         if (@params == 1) {
2161                 unshift @params, 'location';
2162         }
2164         my $sub=pagespec_translate($spec);
2165         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2166                 if ! defined $sub;
2167         return $sub->($page, @params);
2170 sub pagespec_match_list ($$;@) {
2171         my $page=shift;
2172         my $pagespec=shift;
2173         my %params=@_;
2175         # Backwards compatability with old calling convention.
2176         if (ref $page) {
2177                 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2178                 $params{list}=$page;
2179                 $page=$params{location}; # ugh!
2180         }
2182         my $sub=pagespec_translate($pagespec);
2183         error "syntax error in pagespec \"$pagespec\""
2184                 if ! defined $sub;
2185         my $sort=sortspec_translate($params{sort}, $params{reverse})
2186                 if defined $params{sort};
2188         my @candidates;
2189         if (exists $params{list}) {
2190                 @candidates=exists $params{filter}
2191                         ? grep { ! $params{filter}->($_) } @{$params{list}}
2192                         : @{$params{list}};
2193         }
2194         else {
2195                 @candidates=exists $params{filter}
2196                         ? grep { ! $params{filter}->($_) } keys %pagesources
2197                         : keys %pagesources;
2198         }
2199         
2200         # clear params, remainder is passed to pagespec
2201         $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2202         my $num=$params{num};
2203         delete @params{qw{num deptype reverse sort filter list}};
2204         
2205         # when only the top matches will be returned, it's efficient to
2206         # sort before matching to pagespec,
2207         if (defined $num && defined $sort) {
2208                 @candidates=IkiWiki::SortSpec::sort_pages(
2209                         $sort, @candidates);
2210         }
2211         
2212         my @matches;
2213         my $firstfail;
2214         my $count=0;
2215         my $accum=IkiWiki::SuccessReason->new();
2216         foreach my $p (@candidates) {
2217                 my $r=$sub->($p, %params, location => $page);
2218                 error(sprintf(gettext("cannot match pages: %s"), $r))
2219                         if $r->isa("IkiWiki::ErrorReason");
2220                 unless ($r || $r->influences_static) {
2221                         $r->remove_influence($p);
2222                 }
2223                 $accum |= $r;
2224                 if ($r) {
2225                         push @matches, $p;
2226                         last if defined $num && ++$count == $num;
2227                 }
2228         }
2230         # Add simple dependencies for accumulated influences.
2231         my $i=$accum->influences;
2232         foreach my $k (keys %$i) {
2233                 $depends_simple{$page}{lc $k} |= $i->{$k};
2234         }
2236         # when all matches will be returned, it's efficient to
2237         # sort after matching
2238         if (! defined $num && defined $sort) {
2239                 return IkiWiki::SortSpec::sort_pages(
2240                         $sort, @matches);
2241         }
2242         else {
2243                 return @matches;
2244         }
2247 sub pagespec_valid ($) {
2248         my $spec=shift;
2250         return defined pagespec_translate($spec);
2253 sub glob2re ($) {
2254         my $re=quotemeta(shift);
2255         $re=~s/\\\*/.*/g;
2256         $re=~s/\\\?/./g;
2257         return $re;
2260 package IkiWiki::FailReason;
2262 use overload (
2263         '""'    => sub { $_[0][0] },
2264         '0+'    => sub { 0 },
2265         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2266         '&'     => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2267         '|'     => sub { $_[1]->merge_influences($_[0]); $_[1] },
2268         fallback => 1,
2269 );
2271 our @ISA = 'IkiWiki::SuccessReason';
2273 package IkiWiki::SuccessReason;
2275 use overload (
2276         '""'    => sub { $_[0][0] },
2277         '0+'    => sub { 1 },
2278         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
2279         '&'     => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2280         '|'     => sub { $_[0]->merge_influences($_[1]); $_[0] },
2281         fallback => 1,
2282 );
2284 sub new {
2285         my $class = shift;
2286         my $value = shift;
2287         return bless [$value, {@_}], $class;
2290 sub influences {
2291         my $this=shift;
2292         $this->[1]={@_} if @_;
2293         my %i=%{$this->[1]};
2294         delete $i{""};
2295         return \%i;
2298 sub influences_static {
2299         return ! $_[0][1]->{""};
2302 sub merge_influences {
2303         my $this=shift;
2304         my $other=shift;
2305         my $anded=shift;
2307         if (! $anded || (($this || %{$this->[1]}) &&
2308                          ($other || %{$other->[1]}))) {
2309                 foreach my $influence (keys %{$other->[1]}) {
2310                         $this->[1]{$influence} |= $other->[1]{$influence};
2311                 }
2312         }
2313         else {
2314                 # influence blocker
2315                 $this->[1]={};
2316         }
2319 sub remove_influence {
2320         my $this=shift;
2321         my $torm=shift;
2323         delete $this->[1]{$torm};
2326 package IkiWiki::ErrorReason;
2328 our @ISA = 'IkiWiki::FailReason';
2330 package IkiWiki::PageSpec;
2332 sub derel ($$) {
2333         my $path=shift;
2334         my $from=shift;
2336         if ($path =~ m!^\./!) {
2337                 $from=~s#/?[^/]+$## if defined $from;
2338                 $path=~s#^\./##;
2339                 $path="$from/$path" if defined $from && length $from;
2340         }
2342         return $path;
2345 sub match_glob ($$;@) {
2346         my $page=shift;
2347         my $glob=shift;
2348         my %params=@_;
2349         
2350         $glob=derel($glob, $params{location});
2352         my $regexp=IkiWiki::glob2re($glob);
2353         if ($page=~/^$regexp$/i) {
2354                 if (! IkiWiki::isinternal($page) || $params{internal}) {
2355                         return IkiWiki::SuccessReason->new("$glob matches $page");
2356                 }
2357                 else {
2358                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2359                 }
2360         }
2361         else {
2362                 return IkiWiki::FailReason->new("$glob does not match $page");
2363         }
2366 sub match_internal ($$;@) {
2367         return match_glob(shift, shift, @_, internal => 1)
2370 sub match_page ($$;@) {
2371         my $page=shift;
2372         my $match=match_glob($page, shift, @_);
2373         if ($match && ! (exists $IkiWiki::pagesources{$page}
2374             && defined IkiWiki::pagetype($IkiWiki::pagesources{$page}))) {
2375                 return IkiWiki::FailReason->new("$page is not a page");
2376         }
2377         else {
2378                 return $match;
2379         }
2382 sub match_link ($$;@) {
2383         my $page=shift;
2384         my $link=lc(shift);
2385         my %params=@_;
2387         $link=derel($link, $params{location});
2388         my $from=exists $params{location} ? $params{location} : '';
2389         my $linktype=$params{linktype};
2390         my $qualifier='';
2391         if (defined $linktype) {
2392                 $qualifier=" with type $linktype";
2393         }
2395         my $links = $IkiWiki::links{$page};
2396         return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2397                 unless $links && @{$links};
2398         my $bestlink = IkiWiki::bestlink($from, $link);
2399         foreach my $p (@{$links}) {
2400                 if (length $bestlink) {
2401                         if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p}) && $bestlink eq IkiWiki::bestlink($page, $p)) {
2402                                 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2403                         }
2404                 }
2405                 else {
2406                         if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p}) && match_glob($p, $link, %params)) {
2407                                 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2408                         }
2409                         my ($p_rel)=$p=~/^\/?(.*)/;
2410                         $link=~s/^\///;
2411                         if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p_rel}) && match_glob($p_rel, $link, %params)) {
2412                                 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2413                         }
2414                 }
2415         }
2416         return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2419 sub match_backlink ($$;@) {
2420         my $ret=match_link($_[1], $_[0], @_);
2421         $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2422         return $ret;
2425 sub match_created_before ($$;@) {
2426         my $page=shift;
2427         my $testpage=shift;
2428         my %params=@_;
2429         
2430         $testpage=derel($testpage, $params{location});
2432         if (exists $IkiWiki::pagectime{$testpage}) {
2433                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2434                         return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2435                 }
2436                 else {
2437                         return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2438                 }
2439         }
2440         else {
2441                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2442         }
2445 sub match_created_after ($$;@) {
2446         my $page=shift;
2447         my $testpage=shift;
2448         my %params=@_;
2449         
2450         $testpage=derel($testpage, $params{location});
2452         if (exists $IkiWiki::pagectime{$testpage}) {
2453                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2454                         return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2455                 }
2456                 else {
2457                         return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2458                 }
2459         }
2460         else {
2461                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2462         }
2465 sub match_creation_day ($$;@) {
2466         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2467                 return IkiWiki::SuccessReason->new('creation_day matched');
2468         }
2469         else {
2470                 return IkiWiki::FailReason->new('creation_day did not match');
2471         }
2474 sub match_creation_month ($$;@) {
2475         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2476                 return IkiWiki::SuccessReason->new('creation_month matched');
2477         }
2478         else {
2479                 return IkiWiki::FailReason->new('creation_month did not match');
2480         }
2483 sub match_creation_year ($$;@) {
2484         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2485                 return IkiWiki::SuccessReason->new('creation_year matched');
2486         }
2487         else {
2488                 return IkiWiki::FailReason->new('creation_year did not match');
2489         }
2492 sub match_user ($$;@) {
2493         shift;
2494         my $user=shift;
2495         my %params=@_;
2496         
2497         my $regexp=IkiWiki::glob2re($user);
2498         
2499         if (! exists $params{user}) {
2500                 return IkiWiki::ErrorReason->new("no user specified");
2501         }
2503         if (defined $params{user} && $params{user}=~/^$regexp$/i) {
2504                 return IkiWiki::SuccessReason->new("user is $user");
2505         }
2506         elsif (! defined $params{user}) {
2507                 return IkiWiki::FailReason->new("not logged in");
2508         }
2509         else {
2510                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2511         }
2514 sub match_admin ($$;@) {
2515         shift;
2516         shift;
2517         my %params=@_;
2518         
2519         if (! exists $params{user}) {
2520                 return IkiWiki::ErrorReason->new("no user specified");
2521         }
2523         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2524                 return IkiWiki::SuccessReason->new("user is an admin");
2525         }
2526         elsif (! defined $params{user}) {
2527                 return IkiWiki::FailReason->new("not logged in");
2528         }
2529         else {
2530                 return IkiWiki::FailReason->new("user is not an admin");
2531         }
2534 sub match_ip ($$;@) {
2535         shift;
2536         my $ip=shift;
2537         my %params=@_;
2538         
2539         if (! exists $params{ip}) {
2540                 return IkiWiki::ErrorReason->new("no IP specified");
2541         }
2543         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2544                 return IkiWiki::SuccessReason->new("IP is $ip");
2545         }
2546         else {
2547                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2548         }
2551 package IkiWiki::SortSpec;
2553 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2554 # are easily available in this namespace, for cmp functions to use them.
2555 sub sort_pages {
2556         my $f=shift;
2557         sort $f @_
2560 sub cmp_title {
2561         IkiWiki::pagetitle(IkiWiki::basename($a))
2562         cmp
2563         IkiWiki::pagetitle(IkiWiki::basename($b))
2566 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2567 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }