]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki.pm
Rename sort parameter to meta title/author to sortas=bar
[git.ikiwiki.info.git] / IkiWiki.pm
1 #!/usr/bin/perl
3 package IkiWiki;
5 use warnings;
6 use strict;
7 use Encode;
8 use HTML::Entities;
9 use URI::Escape q{uri_escape_utf8};
10 use POSIX ();
11 use Storable;
12 use open qw{:utf8 :std};
14 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
15             %pagestate %wikistate %renderedfiles %oldrenderedfiles
16             %pagesources %destsources %depends %depends_simple %hooks
17             %forcerebuild %loaded_plugins};
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error template htmlpage deptype
21                  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
26                  %config %links %pagestate %wikistate %renderedfiles
27                  %pagesources %destsources);
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 => "location of template files",
155                 advanced => 1,
156                 safe => 0, # path
157                 rebuild => 1,
158         },
159         templatedirs => {
160                 type => "internal",
161                 default => [],
162                 description => "additional directories containing template files",
163                 safe => 0,
164                 rebuild => 0,
165         },
166         underlaydir => {
167                 type => "string",
168                 default => "$installdir/share/ikiwiki/basewiki",
169                 description => "base wiki source location",
170                 advanced => 1,
171                 safe => 0, # path
172                 rebuild => 0,
173         },
174         underlaydirbase => {
175                 type => "internal",
176                 default => "$installdir/share/ikiwiki",
177                 description => "parent directory containing additional underlays",
178                 safe => 0,
179                 rebuild => 0,
180         },
181         wrappers => {
182                 type => "internal",
183                 default => [],
184                 description => "wrappers to generate",
185                 safe => 0,
186                 rebuild => 0,
187         },
188         underlaydirs => {
189                 type => "internal",
190                 default => [],
191                 description => "additional underlays to use",
192                 safe => 0,
193                 rebuild => 0,
194         },
195         verbose => {
196                 type => "boolean",
197                 example => 1,
198                 description => "display verbose messages?",
199                 safe => 1,
200                 rebuild => 0,
201         },
202         syslog => {
203                 type => "boolean",
204                 example => 1,
205                 description => "log to syslog?",
206                 safe => 1,
207                 rebuild => 0,
208         },
209         usedirs => {
210                 type => "boolean",
211                 default => 1,
212                 description => "create output files named page/index.html?",
213                 safe => 0, # changing requires manual transition
214                 rebuild => 1,
215         },
216         prefix_directives => {
217                 type => "boolean",
218                 default => 1,
219                 description => "use '!'-prefixed preprocessor directives?",
220                 safe => 0, # changing requires manual transition
221                 rebuild => 1,
222         },
223         indexpages => {
224                 type => "boolean",
225                 default => 0,
226                 description => "use page/index.mdwn source files",
227                 safe => 1,
228                 rebuild => 1,
229         },
230         discussion => {
231                 type => "boolean",
232                 default => 1,
233                 description => "enable Discussion pages?",
234                 safe => 1,
235                 rebuild => 1,
236         },
237         discussionpage => {
238                 type => "string",
239                 default => gettext("Discussion"),
240                 description => "name of Discussion pages",
241                 safe => 1,
242                 rebuild => 1,
243         },
244         sslcookie => {
245                 type => "boolean",
246                 default => 0,
247                 description => "only send cookies over SSL connections?",
248                 advanced => 1,
249                 safe => 1,
250                 rebuild => 0,
251         },
252         default_pageext => {
253                 type => "string",
254                 default => "mdwn",
255                 description => "extension to use for new pages",
256                 safe => 0, # not sanitized
257                 rebuild => 0,
258         },
259         htmlext => {
260                 type => "string",
261                 default => "html",
262                 description => "extension to use for html files",
263                 safe => 0, # not sanitized
264                 rebuild => 1,
265         },
266         timeformat => {
267                 type => "string",
268                 default => '%c',
269                 description => "strftime format string to display date",
270                 advanced => 1,
271                 safe => 1,
272                 rebuild => 1,
273         },
274         locale => {
275                 type => "string",
276                 default => undef,
277                 example => "en_US.UTF-8",
278                 description => "UTF-8 locale to use",
279                 advanced => 1,
280                 safe => 0,
281                 rebuild => 1,
282         },
283         userdir => {
284                 type => "string",
285                 default => "",
286                 example => "users",
287                 description => "put user pages below specified page",
288                 safe => 1,
289                 rebuild => 1,
290         },
291         numbacklinks => {
292                 type => "integer",
293                 default => 10,
294                 description => "how many backlinks to show before hiding excess (0 to show all)",
295                 safe => 1,
296                 rebuild => 1,
297         },
298         hardlink => {
299                 type => "boolean",
300                 default => 0,
301                 description => "attempt to hardlink source files? (optimisation for large files)",
302                 advanced => 1,
303                 safe => 0, # paranoia
304                 rebuild => 0,
305         },
306         umask => {
307                 type => "integer",
308                 example => "022",
309                 description => "force ikiwiki to use a particular umask",
310                 advanced => 1,
311                 safe => 0, # paranoia
312                 rebuild => 0,
313         },
314         wrappergroup => {
315                 type => "string",
316                 example => "ikiwiki",
317                 description => "group for wrappers to run in",
318                 advanced => 1,
319                 safe => 0, # paranoia
320                 rebuild => 0,
321         },
322         libdir => {
323                 type => "string",
324                 default => "",
325                 example => "$ENV{HOME}/.ikiwiki/",
326                 description => "extra library and plugin directory",
327                 advanced => 1,
328                 safe => 0, # directory
329                 rebuild => 0,
330         },
331         ENV => {
332                 type => "string", 
333                 default => {},
334                 description => "environment variables",
335                 safe => 0, # paranoia
336                 rebuild => 0,
337         },
338         include => {
339                 type => "string",
340                 default => undef,
341                 example => '^\.htaccess$',
342                 description => "regexp of normally excluded files to include",
343                 advanced => 1,
344                 safe => 0, # regexp
345                 rebuild => 1,
346         },
347         exclude => {
348                 type => "string",
349                 default => undef,
350                 example => '^(*\.private|Makefile)$',
351                 description => "regexp of files that should be skipped",
352                 advanced => 1,
353                 safe => 0, # regexp
354                 rebuild => 1,
355         },
356         wiki_file_prune_regexps => {
357                 type => "internal",
358                 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
359                         qr/\.x?html?$/, qr/\.ikiwiki-new$/,
360                         qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
361                         qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
362                         qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
363                 description => "regexps of source files to ignore",
364                 safe => 0,
365                 rebuild => 1,
366         },
367         wiki_file_chars => {
368                 type => "string",
369                 description => "specifies the characters that are allowed in source filenames",
370                 default => "-[:alnum:]+/.:_",
371                 safe => 0,
372                 rebuild => 1,
373         },
374         wiki_file_regexp => {
375                 type => "internal",
376                 description => "regexp of legal source files",
377                 safe => 0,
378                 rebuild => 1,
379         },
380         web_commit_regexp => {
381                 type => "internal",
382                 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
383                 description => "regexp to parse web commits from logs",
384                 safe => 0,
385                 rebuild => 0,
386         },
387         cgi => {
388                 type => "internal",
389                 default => 0,
390                 description => "run as a cgi",
391                 safe => 0,
392                 rebuild => 0,
393         },
394         cgi_disable_uploads => {
395                 type => "internal",
396                 default => 1,
397                 description => "whether CGI should accept file uploads",
398                 safe => 0,
399                 rebuild => 0,
400         },
401         post_commit => {
402                 type => "internal",
403                 default => 0,
404                 description => "run as a post-commit hook",
405                 safe => 0,
406                 rebuild => 0,
407         },
408         rebuild => {
409                 type => "internal",
410                 default => 0,
411                 description => "running in rebuild mode",
412                 safe => 0,
413                 rebuild => 0,
414         },
415         setup => {
416                 type => "internal",
417                 default => undef,
418                 description => "running in setup mode",
419                 safe => 0,
420                 rebuild => 0,
421         },
422         clean => {
423                 type => "internal",
424                 default => 0,
425                 description => "running in clean mode",
426                 safe => 0,
427                 rebuild => 0,
428         },
429         refresh => {
430                 type => "internal",
431                 default => 0,
432                 description => "running in refresh mode",
433                 safe => 0,
434                 rebuild => 0,
435         },
436         test_receive => {
437                 type => "internal",
438                 default => 0,
439                 description => "running in receive test mode",
440                 safe => 0,
441                 rebuild => 0,
442         },
443         getctime => {
444                 type => "internal",
445                 default => 0,
446                 description => "running in getctime 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         return '<span class="date">'.formattime(@_).'</span>';
1007 sub formattime ($;$) {
1008         # Plugins can override this function to format the time.
1009         my $time=shift;
1010         my $format=shift;
1011         if (! defined $format) {
1012                 $format=$config{timeformat};
1013         }
1015         # strftime doesn't know about encodings, so make sure
1016         # its output is properly treated as utf8
1017         return decode_utf8(POSIX::strftime($format, localtime($time)));
1020 sub beautify_urlpath ($) {
1021         my $url=shift;
1023         # Ensure url is not an empty link, and if necessary,
1024         # add ./ to avoid colon confusion.
1025         if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1026                 $url="./$url";
1027         }
1029         if ($config{usedirs}) {
1030                 $url =~ s!/index.$config{htmlext}$!/!;
1031         }
1033         return $url;
1036 sub urlto ($$;$) {
1037         my $to=shift;
1038         my $from=shift;
1039         my $absolute=shift;
1040         
1041         if (! length $to) {
1042                 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1043         }
1045         if (! $destsources{$to}) {
1046                 $to=htmlpage($to);
1047         }
1049         if ($absolute) {
1050                 return $config{url}.beautify_urlpath("/".$to);
1051         }
1053         my $link = abs2rel($to, dirname(htmlpage($from)));
1055         return beautify_urlpath($link);
1058 sub htmllink ($$$;@) {
1059         my $lpage=shift; # the page doing the linking
1060         my $page=shift; # the page that will contain the link (different for inline)
1061         my $link=shift;
1062         my %opts=@_;
1064         $link=~s/\/$//;
1066         my $bestlink;
1067         if (! $opts{forcesubpage}) {
1068                 $bestlink=bestlink($lpage, $link);
1069         }
1070         else {
1071                 $bestlink="$lpage/".lc($link);
1072         }
1074         my $linktext;
1075         if (defined $opts{linktext}) {
1076                 $linktext=$opts{linktext};
1077         }
1078         else {
1079                 $linktext=pagetitle(basename($link));
1080         }
1081         
1082         return "<span class=\"selflink\">$linktext</span>"
1083                 if length $bestlink && $page eq $bestlink &&
1084                    ! defined $opts{anchor};
1085         
1086         if (! $destsources{$bestlink}) {
1087                 $bestlink=htmlpage($bestlink);
1089                 if (! $destsources{$bestlink}) {
1090                         return $linktext unless length $config{cgiurl};
1091                         return "<span class=\"createlink\"><a href=\"".
1092                                 cgiurl(
1093                                         do => "create",
1094                                         page => lc($link),
1095                                         from => $lpage
1096                                 ).
1097                                 "\" rel=\"nofollow\">?</a>$linktext</span>"
1098                 }
1099         }
1100         
1101         $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1102         $bestlink=beautify_urlpath($bestlink);
1103         
1104         if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1105                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1106         }
1108         if (defined $opts{anchor}) {
1109                 $bestlink.="#".$opts{anchor};
1110         }
1112         my @attrs;
1113         foreach my $attr (qw{rel class title}) {
1114                 if (defined $opts{$attr}) {
1115                         push @attrs, " $attr=\"$opts{$attr}\"";
1116                 }
1117         }
1119         return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1122 sub userpage ($) {
1123         my $user=shift;
1124         return length $config{userdir} ? "$config{userdir}/$user" : $user;
1127 sub openiduser ($) {
1128         my $user=shift;
1130         if ($user =~ m!^https?://! &&
1131             eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1132                 my $display;
1134                 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1135                         $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1136                 }
1137                 else {
1138                         # backcompat with old version
1139                         my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1140                         $display=$oid->display;
1141                 }
1143                 # Convert "user.somehost.com" to "user [somehost.com]"
1144                 # (also "user.somehost.co.uk")
1145                 if ($display !~ /\[/) {
1146                         $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1147                 }
1148                 # Convert "http://somehost.com/user" to "user [somehost.com]".
1149                 # (also "https://somehost.com/user/")
1150                 if ($display !~ /\[/) {
1151                         $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1152                 }
1153                 $display=~s!^https?://!!; # make sure this is removed
1154                 eval q{use CGI 'escapeHTML'};
1155                 error($@) if $@;
1156                 return escapeHTML($display);
1157         }
1158         return;
1161 sub htmlize ($$$$) {
1162         my $page=shift;
1163         my $destpage=shift;
1164         my $type=shift;
1165         my $content=shift;
1166         
1167         my $oneline = $content !~ /\n/;
1169         if (exists $hooks{htmlize}{$type}) {
1170                 $content=$hooks{htmlize}{$type}{call}->(
1171                         page => $page,
1172                         content => $content,
1173                 );
1174         }
1175         else {
1176                 error("htmlization of $type not supported");
1177         }
1179         run_hooks(sanitize => sub {
1180                 $content=shift->(
1181                         page => $page,
1182                         destpage => $destpage,
1183                         content => $content,
1184                 );
1185         });
1186         
1187         if ($oneline) {
1188                 # hack to get rid of enclosing junk added by markdown
1189                 # and other htmlizers
1190                 $content=~s/^<p>//i;
1191                 $content=~s/<\/p>$//i;
1192                 chomp $content;
1193         }
1195         return $content;
1198 sub linkify ($$$) {
1199         my $page=shift;
1200         my $destpage=shift;
1201         my $content=shift;
1203         run_hooks(linkify => sub {
1204                 $content=shift->(
1205                         page => $page,
1206                         destpage => $destpage,
1207                         content => $content,
1208                 );
1209         });
1210         
1211         return $content;
1214 our %preprocessing;
1215 our $preprocess_preview=0;
1216 sub preprocess ($$$;$$) {
1217         my $page=shift; # the page the data comes from
1218         my $destpage=shift; # the page the data will appear in (different for inline)
1219         my $content=shift;
1220         my $scan=shift;
1221         my $preview=shift;
1223         # Using local because it needs to be set within any nested calls
1224         # of this function.
1225         local $preprocess_preview=$preview if defined $preview;
1227         my $handle=sub {
1228                 my $escape=shift;
1229                 my $prefix=shift;
1230                 my $command=shift;
1231                 my $params=shift;
1232                 $params="" if ! defined $params;
1234                 if (length $escape) {
1235                         return "[[$prefix$command $params]]";
1236                 }
1237                 elsif (exists $hooks{preprocess}{$command}) {
1238                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1239                         # Note: preserve order of params, some plugins may
1240                         # consider it significant.
1241                         my @params;
1242                         while ($params =~ m{
1243                                 (?:([-\w]+)=)?          # 1: named parameter key?
1244                                 (?:
1245                                         """(.*?)"""     # 2: triple-quoted value
1246                                 |
1247                                         "([^"]*?)"      # 3: single-quoted value
1248                                 |
1249                                         (\S+)           # 4: unquoted value
1250                                 )
1251                                 (?:\s+|$)               # delimiter to next param
1252                         }sgx) {
1253                                 my $key=$1;
1254                                 my $val;
1255                                 if (defined $2) {
1256                                         $val=$2;
1257                                         $val=~s/\r\n/\n/mg;
1258                                         $val=~s/^\n+//g;
1259                                         $val=~s/\n+$//g;
1260                                 }
1261                                 elsif (defined $3) {
1262                                         $val=$3;
1263                                 }
1264                                 elsif (defined $4) {
1265                                         $val=$4;
1266                                 }
1268                                 if (defined $key) {
1269                                         push @params, $key, $val;
1270                                 }
1271                                 else {
1272                                         push @params, $val, '';
1273                                 }
1274                         }
1275                         if ($preprocessing{$page}++ > 3) {
1276                                 # Avoid loops of preprocessed pages preprocessing
1277                                 # other pages that preprocess them, etc.
1278                                 return "[[!$command <span class=\"error\">".
1279                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1280                                                 $page, $preprocessing{$page}).
1281                                         "</span>]]";
1282                         }
1283                         my $ret;
1284                         if (! $scan) {
1285                                 $ret=eval {
1286                                         $hooks{preprocess}{$command}{call}->(
1287                                                 @params,
1288                                                 page => $page,
1289                                                 destpage => $destpage,
1290                                                 preview => $preprocess_preview,
1291                                         );
1292                                 };
1293                                 if ($@) {
1294                                         my $error=$@;
1295                                         chomp $error;
1296                                         $ret="[[!$command <span class=\"error\">".
1297                                                 gettext("Error").": $error"."</span>]]";
1298                                 }
1299                         }
1300                         else {
1301                                 # use void context during scan pass
1302                                 eval {
1303                                         $hooks{preprocess}{$command}{call}->(
1304                                                 @params,
1305                                                 page => $page,
1306                                                 destpage => $destpage,
1307                                                 preview => $preprocess_preview,
1308                                         );
1309                                 };
1310                                 $ret="";
1311                         }
1312                         $preprocessing{$page}--;
1313                         return $ret;
1314                 }
1315                 else {
1316                         return "[[$prefix$command $params]]";
1317                 }
1318         };
1319         
1320         my $regex;
1321         if ($config{prefix_directives}) {
1322                 $regex = qr{
1323                         (\\?)           # 1: escape?
1324                         \[\[(!)         # directive open; 2: prefix
1325                         ([-\w]+)        # 3: command
1326                         (               # 4: the parameters..
1327                                 \s+     # Must have space if parameters present
1328                                 (?:
1329                                         (?:[-\w]+=)?            # named parameter key?
1330                                         (?:
1331                                                 """.*?"""       # triple-quoted value
1332                                                 |
1333                                                 "[^"]*?"        # single-quoted value
1334                                                 |
1335                                                 [^"\s\]]+       # unquoted value
1336                                         )
1337                                         \s*                     # whitespace or end
1338                                                                 # of directive
1339                                 )
1340                         *)?             # 0 or more parameters
1341                         \]\]            # directive closed
1342                 }sx;
1343         }
1344         else {
1345                 $regex = qr{
1346                         (\\?)           # 1: escape?
1347                         \[\[(!?)        # directive open; 2: optional prefix
1348                         ([-\w]+)        # 3: command
1349                         \s+
1350                         (               # 4: the parameters..
1351                                 (?:
1352                                         (?:[-\w]+=)?            # named parameter key?
1353                                         (?:
1354                                                 """.*?"""       # triple-quoted value
1355                                                 |
1356                                                 "[^"]*?"        # single-quoted value
1357                                                 |
1358                                                 [^"\s\]]+       # unquoted value
1359                                         )
1360                                         \s*                     # whitespace or end
1361                                                                 # of directive
1362                                 )
1363                         *)              # 0 or more parameters
1364                         \]\]            # directive closed
1365                 }sx;
1366         }
1368         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1369         return $content;
1372 sub filter ($$$) {
1373         my $page=shift;
1374         my $destpage=shift;
1375         my $content=shift;
1377         run_hooks(filter => sub {
1378                 $content=shift->(page => $page, destpage => $destpage, 
1379                         content => $content);
1380         });
1382         return $content;
1385 sub indexlink () {
1386         return "<a href=\"$config{url}\">$config{wikiname}</a>";
1389 sub check_canedit ($$$;$) {
1390         my $page=shift;
1391         my $q=shift;
1392         my $session=shift;
1393         my $nonfatal=shift;
1394         
1395         my $canedit;
1396         run_hooks(canedit => sub {
1397                 return if defined $canedit;
1398                 my $ret=shift->($page, $q, $session);
1399                 if (defined $ret) {
1400                         if ($ret eq "") {
1401                                 $canedit=1;
1402                         }
1403                         elsif (ref $ret eq 'CODE') {
1404                                 $ret->() unless $nonfatal;
1405                                 $canedit=0;
1406                         }
1407                         elsif (defined $ret) {
1408                                 error($ret) unless $nonfatal;
1409                                 $canedit=0;
1410                         }
1411                 }
1412         });
1413         return defined $canedit ? $canedit : 1;
1416 sub check_content (@) {
1417         my %params=@_;
1418         
1419         return 1 if ! exists $hooks{checkcontent}; # optimisation
1421         if (exists $pagesources{$params{page}}) {
1422                 my @diff;
1423                 my %old=map { $_ => 1 }
1424                         split("\n", readfile(srcfile($pagesources{$params{page}})));
1425                 foreach my $line (split("\n", $params{content})) {
1426                         push @diff, $line if ! exists $old{$line};
1427                 }
1428                 $params{diff}=join("\n", @diff);
1429         }
1431         my $ok;
1432         run_hooks(checkcontent => sub {
1433                 return if defined $ok;
1434                 my $ret=shift->(%params);
1435                 if (defined $ret) {
1436                         if ($ret eq "") {
1437                                 $ok=1;
1438                         }
1439                         elsif (ref $ret eq 'CODE') {
1440                                 $ret->() unless $params{nonfatal};
1441                                 $ok=0;
1442                         }
1443                         elsif (defined $ret) {
1444                                 error($ret) unless $params{nonfatal};
1445                                 $ok=0;
1446                         }
1447                 }
1449         });
1450         return defined $ok ? $ok : 1;
1453 my $wikilock;
1455 sub lockwiki () {
1456         # Take an exclusive lock on the wiki to prevent multiple concurrent
1457         # run issues. The lock will be dropped on program exit.
1458         if (! -d $config{wikistatedir}) {
1459                 mkdir($config{wikistatedir});
1460         }
1461         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1462                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1463         if (! flock($wikilock, 2)) { # LOCK_EX
1464                 error("failed to get lock");
1465         }
1466         return 1;
1469 sub unlockwiki () {
1470         POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1471         return close($wikilock) if $wikilock;
1472         return;
1475 my $commitlock;
1477 sub commit_hook_enabled () {
1478         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1479                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1480         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1481                 close($commitlock) || error("failed closing commitlock: $!");
1482                 return 0;
1483         }
1484         close($commitlock) || error("failed closing commitlock: $!");
1485         return 1;
1488 sub disable_commit_hook () {
1489         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1490                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1491         if (! flock($commitlock, 2)) { # LOCK_EX
1492                 error("failed to get commit lock");
1493         }
1494         return 1;
1497 sub enable_commit_hook () {
1498         return close($commitlock) if $commitlock;
1499         return;
1502 sub loadindex () {
1503         %oldrenderedfiles=%pagectime=();
1504         if (! $config{rebuild}) {
1505                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1506                 %destsources=%renderedfiles=%pagecase=%pagestate=
1507                 %depends_simple=();
1508         }
1509         my $in;
1510         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1511                 if (-e "$config{wikistatedir}/index") {
1512                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1513                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1514                 }
1515                 else {
1516                         return;
1517                 }
1518         }
1520         my $index=Storable::fd_retrieve($in);
1521         if (! defined $index) {
1522                 return 0;
1523         }
1525         my $pages;
1526         if (exists $index->{version} && ! ref $index->{version}) {
1527                 $pages=$index->{page};
1528                 %wikistate=%{$index->{state}};
1529         }
1530         else {
1531                 $pages=$index;
1532                 %wikistate=();
1533         }
1535         foreach my $src (keys %$pages) {
1536                 my $d=$pages->{$src};
1537                 my $page=pagename($src);
1538                 $pagectime{$page}=$d->{ctime};
1539                 if (! $config{rebuild}) {
1540                         $pagesources{$page}=$src;
1541                         $pagemtime{$page}=$d->{mtime};
1542                         $renderedfiles{$page}=$d->{dest};
1543                         if (exists $d->{links} && ref $d->{links}) {
1544                                 $links{$page}=$d->{links};
1545                                 $oldlinks{$page}=[@{$d->{links}}];
1546                         }
1547                         if (ref $d->{depends_simple} eq 'ARRAY') {
1548                                 # old format
1549                                 $depends_simple{$page}={
1550                                         map { $_ => 1 } @{$d->{depends_simple}}
1551                                 };
1552                         }
1553                         elsif (exists $d->{depends_simple}) {
1554                                 $depends_simple{$page}=$d->{depends_simple};
1555                         }
1556                         if (exists $d->{dependslist}) {
1557                                 # old format
1558                                 $depends{$page}={
1559                                         map { $_ => $DEPEND_CONTENT }
1560                                                 @{$d->{dependslist}}
1561                                 };
1562                         }
1563                         elsif (exists $d->{depends} && ! ref $d->{depends}) {
1564                                 # old format
1565                                 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1566                         }
1567                         elsif (exists $d->{depends}) {
1568                                 $depends{$page}=$d->{depends};
1569                         }
1570                         if (exists $d->{state}) {
1571                                 $pagestate{$page}=$d->{state};
1572                         }
1573                 }
1574                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1575         }
1576         foreach my $page (keys %pagesources) {
1577                 $pagecase{lc $page}=$page;
1578         }
1579         foreach my $page (keys %renderedfiles) {
1580                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1581         }
1582         return close($in);
1585 sub saveindex () {
1586         run_hooks(savestate => sub { shift->() });
1588         my %hookids;
1589         foreach my $type (keys %hooks) {
1590                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1591         }
1592         my @hookids=keys %hookids;
1594         if (! -d $config{wikistatedir}) {
1595                 mkdir($config{wikistatedir});
1596         }
1597         my $newfile="$config{wikistatedir}/indexdb.new";
1598         my $cleanup = sub { unlink($newfile) };
1599         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1601         my %index;
1602         foreach my $page (keys %pagemtime) {
1603                 next unless $pagemtime{$page};
1604                 my $src=$pagesources{$page};
1606                 $index{page}{$src}={
1607                         ctime => $pagectime{$page},
1608                         mtime => $pagemtime{$page},
1609                         dest => $renderedfiles{$page},
1610                         links => $links{$page},
1611                 };
1613                 if (exists $depends{$page}) {
1614                         $index{page}{$src}{depends} = $depends{$page};
1615                 }
1617                 if (exists $depends_simple{$page}) {
1618                         $index{page}{$src}{depends_simple} = $depends_simple{$page};
1619                 }
1621                 if (exists $pagestate{$page}) {
1622                         foreach my $id (@hookids) {
1623                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1624                                         $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1625                                 }
1626                         }
1627                 }
1628         }
1630         $index{state}={};
1631         foreach my $id (@hookids) {
1632                 foreach my $key (keys %{$wikistate{$id}}) {
1633                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
1634                 }
1635         }
1636         
1637         $index{version}="3";
1638         my $ret=Storable::nstore_fd(\%index, $out);
1639         return if ! defined $ret || ! $ret;
1640         close $out || error("failed saving to $newfile: $!", $cleanup);
1641         rename($newfile, "$config{wikistatedir}/indexdb") ||
1642                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1643         
1644         return 1;
1647 sub template_file ($) {
1648         my $template=shift;
1650         foreach my $dir ($config{templatedir}, @{$config{templatedirs}},
1651                          "$installdir/share/ikiwiki/templates") {
1652                 return "$dir/$template" if -e "$dir/$template";
1653         }
1654         return;
1657 sub template_params (@) {
1658         my $filename=template_file(shift);
1660         if (! defined $filename) {
1661                 return if wantarray;
1662                 return "";
1663         }
1665         my @ret=(
1666                 filter => sub {
1667                         my $text_ref = shift;
1668                         ${$text_ref} = decode_utf8(${$text_ref});
1669                 },
1670                 filename => $filename,
1671                 loop_context_vars => 1,
1672                 die_on_bad_params => 0,
1673                 @_
1674         );
1675         return wantarray ? @ret : {@ret};
1678 sub template ($;@) {
1679         require HTML::Template;
1680         return HTML::Template->new(template_params(@_));
1683 sub misctemplate ($$;@) {
1684         my $title=shift;
1685         my $pagebody=shift;
1686         
1687         my $template=template("misc.tmpl");
1688         $template->param(
1689                 title => $title,
1690                 indexlink => indexlink(),
1691                 wikiname => $config{wikiname},
1692                 pagebody => $pagebody,
1693                 baseurl => baseurl(),
1694                 @_,
1695         );
1696         run_hooks(pagetemplate => sub {
1697                 shift->(page => "", destpage => "", template => $template);
1698         });
1699         return $template->output;
1702 sub hook (@) {
1703         my %param=@_;
1704         
1705         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1706                 error 'hook requires type, call, and id parameters';
1707         }
1709         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1710         
1711         $hooks{$param{type}}{$param{id}}=\%param;
1712         return 1;
1715 sub run_hooks ($$) {
1716         # Calls the given sub for each hook of the given type,
1717         # passing it the hook function to call.
1718         my $type=shift;
1719         my $sub=shift;
1721         if (exists $hooks{$type}) {
1722                 my (@first, @middle, @last);
1723                 foreach my $id (keys %{$hooks{$type}}) {
1724                         if ($hooks{$type}{$id}{first}) {
1725                                 push @first, $id;
1726                         }
1727                         elsif ($hooks{$type}{$id}{last}) {
1728                                 push @last, $id;
1729                         }
1730                         else {
1731                                 push @middle, $id;
1732                         }
1733                 }
1734                 foreach my $id (@first, @middle, @last) {
1735                         $sub->($hooks{$type}{$id}{call});
1736                 }
1737         }
1739         return 1;
1742 sub rcs_update () {
1743         $hooks{rcs}{rcs_update}{call}->(@_);
1746 sub rcs_prepedit ($) {
1747         $hooks{rcs}{rcs_prepedit}{call}->(@_);
1750 sub rcs_commit ($$$;$$) {
1751         $hooks{rcs}{rcs_commit}{call}->(@_);
1754 sub rcs_commit_staged ($$$) {
1755         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1758 sub rcs_add ($) {
1759         $hooks{rcs}{rcs_add}{call}->(@_);
1762 sub rcs_remove ($) {
1763         $hooks{rcs}{rcs_remove}{call}->(@_);
1766 sub rcs_rename ($$) {
1767         $hooks{rcs}{rcs_rename}{call}->(@_);
1770 sub rcs_recentchanges ($) {
1771         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1774 sub rcs_diff ($) {
1775         $hooks{rcs}{rcs_diff}{call}->(@_);
1778 sub rcs_getctime ($) {
1779         $hooks{rcs}{rcs_getctime}{call}->(@_);
1782 sub rcs_receive () {
1783         $hooks{rcs}{rcs_receive}{call}->();
1786 sub add_depends ($$;$) {
1787         my $page=shift;
1788         my $pagespec=shift;
1789         my $deptype=shift || $DEPEND_CONTENT;
1791         # Is the pagespec a simple page name?
1792         if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1793             $pagespec !~ /[\s*?()!]/) {
1794                 $depends_simple{$page}{lc $pagespec} |= $deptype;
1795                 return 1;
1796         }
1798         # Add explicit dependencies for influences.
1799         my $sub=pagespec_translate($pagespec);
1800         return if $@;
1801         foreach my $p (keys %pagesources) {
1802                 my $r=$sub->($p, location => $page);
1803                 my $i=$r->influences;
1804                 foreach my $k (keys %$i) {
1805                         $depends_simple{$page}{lc $k} |= $i->{$k};
1806                 }
1807                 last if $r->influences_static;
1808         }
1810         $depends{$page}{$pagespec} |= $deptype;
1811         return 1;
1814 sub deptype (@) {
1815         my $deptype=0;
1816         foreach my $type (@_) {
1817                 if ($type eq 'presence') {
1818                         $deptype |= $DEPEND_PRESENCE;
1819                 }
1820                 elsif ($type eq 'links') { 
1821                         $deptype |= $DEPEND_LINKS;
1822                 }
1823                 elsif ($type eq 'content') {
1824                         $deptype |= $DEPEND_CONTENT;
1825                 }
1826         }
1827         return $deptype;
1830 my $file_prune_regexp;
1831 sub file_pruned ($;$) {
1832         my $file=shift;
1833         if (@_) {
1834                 require File::Spec;
1835                 $file=File::Spec->canonpath($file);
1836                 my $base=File::Spec->canonpath(shift);
1837                 return if $file eq $base;
1838                 $file =~ s#^\Q$base\E/+##;
1839         }
1841         if (defined $config{include} && length $config{include}) {
1842                 return 0 if $file =~ m/$config{include}/;
1843         }
1845         if (! defined $file_prune_regexp) {
1846                 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1847                 $file_prune_regexp=qr/$file_prune_regexp/;
1848         }
1849         return $file =~ m/$file_prune_regexp/;
1852 sub define_gettext () {
1853         # If translation is needed, redefine the gettext function to do it.
1854         # Otherwise, it becomes a quick no-op.
1855         my $gettext_obj;
1856         my $getobj;
1857         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1858             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1859             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1860                 $getobj=sub {
1861                         $gettext_obj=eval q{
1862                                 use Locale::gettext q{textdomain};
1863                                 Locale::gettext->domain('ikiwiki')
1864                         };
1865                 };
1866         }
1868         no warnings 'redefine';
1869         *gettext=sub {
1870                 $getobj->() if $getobj;
1871                 if ($gettext_obj) {
1872                         $gettext_obj->get(shift);
1873                 }
1874                 else {
1875                         return shift;
1876                 }
1877         };
1878         *ngettext=sub {
1879                 $getobj->() if $getobj;
1880                 if ($gettext_obj) {
1881                         $gettext_obj->nget(@_);
1882                 }
1883                 else {
1884                         return ($_[2] == 1 ? $_[0] : $_[1])
1885                 }
1886         };
1889 sub gettext {
1890         define_gettext();
1891         gettext(@_);
1894 sub ngettext {
1895         define_gettext();
1896         ngettext(@_);
1899 sub yesno ($) {
1900         my $val=shift;
1902         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1905 sub inject {
1906         # Injects a new function into the symbol table to replace an
1907         # exported function.
1908         my %params=@_;
1910         # This is deep ugly perl foo, beware.
1911         no strict;
1912         no warnings;
1913         if (! defined $params{parent}) {
1914                 $params{parent}='::';
1915                 $params{old}=\&{$params{name}};
1916                 $params{name}=~s/.*:://;
1917         }
1918         my $parent=$params{parent};
1919         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1920                 $ns = $params{parent} . $ns;
1921                 inject(%params, parent => $ns) unless $ns eq '::main::';
1922                 *{$ns . $params{name}} = $params{call}
1923                         if exists ${$ns}{$params{name}} &&
1924                            \&{${$ns}{$params{name}}} == $params{old};
1925         }
1926         use strict;
1927         use warnings;
1930 sub add_link ($$) {
1931         my $page=shift;
1932         my $link=shift;
1934         push @{$links{$page}}, $link
1935                 unless grep { $_ eq $link } @{$links{$page}};
1938 sub sortspec_translate ($) {
1939         my $spec = shift;
1941         my $code = "";
1942         my @data;
1943         while ($spec =~ m{
1944                 \s*
1945                 (-?)            # group 1: perhaps negated
1946                 \s*
1947                 (               # group 2: a word
1948                         \w+\([^\)]*\)   # command(params)
1949                         |
1950                         [^\s]+          # or anything else
1951                 )
1952                 \s*
1953         }gx) {
1954                 my $negated = $1;
1955                 my $word = $2;
1956                 my $params = undef;
1958                 if ($word =~ m/^(\w+)\((.*)\)$/) {
1959                         # command with parameters
1960                         $params = $2;
1961                         $word = $1;
1962                 }
1963                 elsif ($word !~ m/^\w+$/) {
1964                         error(sprintf(gettext("invalid sort type %s"), $word));
1965                 }
1967                 if (length $code) {
1968                         $code .= " || ";
1969                 }
1971                 if ($negated) {
1972                         $code .= "-";
1973                 }
1975                 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
1976                         if (defined $params) {
1977                                 push @data, $params;
1978                                 $code .= "IkiWiki::SortSpec::cmp_$word(\@_, \$data[$#data])";
1979                         }
1980                         else {
1981                                 $code .= "IkiWiki::SortSpec::cmp_$word(\@_, undef)";
1982                         }
1983                 }
1984                 else {
1985                         error(sprintf(gettext("unknown sort type %s"), $word));
1986                 }
1987         }
1989         if (! length $code) {
1990                 # undefined sorting method... sort arbitrarily
1991                 return sub { 0 };
1992         }
1994         no warnings;
1995         return eval 'sub { '.$code.' }';
1998 sub pagespec_translate ($) {
1999         my $spec=shift;
2001         # Convert spec to perl code.
2002         my $code="";
2003         my @data;
2004         while ($spec=~m{
2005                 \s*             # ignore whitespace
2006                 (               # 1: match a single word
2007                         \!              # !
2008                 |
2009                         \(              # (
2010                 |
2011                         \)              # )
2012                 |
2013                         \w+\([^\)]*\)   # command(params)
2014                 |
2015                         [^\s()]+        # any other text
2016                 )
2017                 \s*             # ignore whitespace
2018         }gx) {
2019                 my $word=$1;
2020                 if (lc $word eq 'and') {
2021                         $code.=' &';
2022                 }
2023                 elsif (lc $word eq 'or') {
2024                         $code.=' |';
2025                 }
2026                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2027                         $code.=' '.$word;
2028                 }
2029                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2030                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2031                                 push @data, $2;
2032                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2033                         }
2034                         else {
2035                                 push @data, qq{unknown function in pagespec "$word"};
2036                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2037                         }
2038                 }
2039                 else {
2040                         push @data, $word;
2041                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2042                 }
2043         }
2045         if (! length $code) {
2046                 $code="IkiWiki::FailReason->new('empty pagespec')";
2047         }
2049         no warnings;
2050         return eval 'sub { my $page=shift; '.$code.' }';
2053 sub pagespec_match ($$;@) {
2054         my $page=shift;
2055         my $spec=shift;
2056         my @params=@_;
2058         # Backwards compatability with old calling convention.
2059         if (@params == 1) {
2060                 unshift @params, 'location';
2061         }
2063         my $sub=pagespec_translate($spec);
2064         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2065                 if $@ || ! defined $sub;
2066         return $sub->($page, @params);
2069 sub pagespec_match_list ($$;@) {
2070         my $page=shift;
2071         my $pagespec=shift;
2072         my %params=@_;
2074         # Backwards compatability with old calling convention.
2075         if (ref $page) {
2076                 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2077                 $params{list}=$page;
2078                 $page=$params{location}; # ugh!
2079         }
2081         my $sub=pagespec_translate($pagespec);
2082         error "syntax error in pagespec \"$pagespec\""
2083                 if $@ || ! defined $sub;
2085         my @candidates;
2086         if (exists $params{list}) {
2087                 @candidates=exists $params{filter}
2088                         ? grep { ! $params{filter}->($_) } @{$params{list}}
2089                         : @{$params{list}};
2090         }
2091         else {
2092                 @candidates=exists $params{filter}
2093                         ? grep { ! $params{filter}->($_) } keys %pagesources
2094                         : keys %pagesources;
2095         }
2097         if (defined $params{sort}) {
2098                 my $f = sortspec_translate($params{sort});
2100                 @candidates = sort { $f->($a, $b) } @candidates;
2101         }
2103         @candidates=reverse(@candidates) if $params{reverse};
2104         
2105         $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2106         
2107         # clear params, remainder is passed to pagespec
2108         my $num=$params{num};
2109         delete @params{qw{num deptype reverse sort filter list}};
2110         
2111         my @matches;
2112         my $firstfail;
2113         my $count=0;
2114         my $accum=IkiWiki::SuccessReason->new();
2115         foreach my $p (@candidates) {
2116                 my $r=$sub->($p, %params, location => $page);
2117                 error(sprintf(gettext("cannot match pages: %s"), $r))
2118                         if $r->isa("IkiWiki::ErrorReason");
2119                 $accum |= $r;
2120                 if ($r) {
2121                         push @matches, $p;
2122                         last if defined $num && ++$count == $num;
2123                 }
2124         }
2126         # Add simple dependencies for accumulated influences.
2127         my $i=$accum->influences;
2128         foreach my $k (keys %$i) {
2129                 $depends_simple{$page}{lc $k} |= $i->{$k};
2130         }
2132         return @matches;
2135 sub pagespec_valid ($) {
2136         my $spec=shift;
2138         my $sub=pagespec_translate($spec);
2139         return ! $@;
2142 sub glob2re ($) {
2143         my $re=quotemeta(shift);
2144         $re=~s/\\\*/.*/g;
2145         $re=~s/\\\?/./g;
2146         return $re;
2149 package IkiWiki::FailReason;
2151 use overload (
2152         '""'    => sub { $_[0][0] },
2153         '0+'    => sub { 0 },
2154         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2155         '&'     => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2156         '|'     => sub { $_[1]->merge_influences($_[0]); $_[1] },
2157         fallback => 1,
2158 );
2160 our @ISA = 'IkiWiki::SuccessReason';
2162 package IkiWiki::SuccessReason;
2164 use overload (
2165         '""'    => sub { $_[0][0] },
2166         '0+'    => sub { 1 },
2167         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
2168         '&'     => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2169         '|'     => sub { $_[0]->merge_influences($_[1]); $_[0] },
2170         fallback => 1,
2171 );
2173 sub new {
2174         my $class = shift;
2175         my $value = shift;
2176         return bless [$value, {@_}], $class;
2179 sub influences {
2180         my $this=shift;
2181         $this->[1]={@_} if @_;
2182         my %i=%{$this->[1]};
2183         delete $i{""};
2184         return \%i;
2187 sub influences_static {
2188         return ! $_[0][1]->{""};
2191 sub merge_influences {
2192         my $this=shift;
2193         my $other=shift;
2194         my $anded=shift;
2196         if (! $anded || (($this || %{$this->[1]}) &&
2197                         ($other || %{$other->[1]}))) {
2198                 foreach my $influence (keys %{$other->[1]}) {
2199                         $this->[1]{$influence} |= $other->[1]{$influence};
2200                 }
2201         }
2202         else {
2203                 # influence blocker
2204                 $this->[1]={};
2205         }
2208 package IkiWiki::ErrorReason;
2210 our @ISA = 'IkiWiki::FailReason';
2212 package IkiWiki::PageSpec;
2214 sub derel ($$) {
2215         my $path=shift;
2216         my $from=shift;
2218         if ($path =~ m!^\./!) {
2219                 $from=~s#/?[^/]+$## if defined $from;
2220                 $path=~s#^\./##;
2221                 $path="$from/$path" if length $from;
2222         }
2224         return $path;
2227 sub match_glob ($$;@) {
2228         my $page=shift;
2229         my $glob=shift;
2230         my %params=@_;
2231         
2232         $glob=derel($glob, $params{location});
2234         my $regexp=IkiWiki::glob2re($glob);
2235         if ($page=~/^$regexp$/i) {
2236                 if (! IkiWiki::isinternal($page) || $params{internal}) {
2237                         return IkiWiki::SuccessReason->new("$glob matches $page");
2238                 }
2239                 else {
2240                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2241                 }
2242         }
2243         else {
2244                 return IkiWiki::FailReason->new("$glob does not match $page");
2245         }
2248 sub match_internal ($$;@) {
2249         return match_glob($_[0], $_[1], @_, internal => 1)
2252 sub match_link ($$;@) {
2253         my $page=shift;
2254         my $link=lc(shift);
2255         my %params=@_;
2257         $link=derel($link, $params{location});
2258         my $from=exists $params{location} ? $params{location} : '';
2260         my $links = $IkiWiki::links{$page};
2261         return IkiWiki::FailReason->new("$page has no links", "" => 1)
2262                 unless $links && @{$links};
2263         my $bestlink = IkiWiki::bestlink($from, $link);
2264         foreach my $p (@{$links}) {
2265                 if (length $bestlink) {
2266                         return IkiWiki::SuccessReason->new("$page links to $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2267                                 if $bestlink eq IkiWiki::bestlink($page, $p);
2268                 }
2269                 else {
2270                         return IkiWiki::SuccessReason->new("$page links to page $p matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2271                                 if match_glob($p, $link, %params);
2272                         my ($p_rel)=$p=~/^\/?(.*)/;
2273                         $link=~s/^\///;
2274                         return IkiWiki::SuccessReason->new("$page links to page $p_rel matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2275                                 if match_glob($p_rel, $link, %params);
2276                 }
2277         }
2278         return IkiWiki::FailReason->new("$page does not link to $link", "" => 1);
2281 sub match_backlink ($$;@) {
2282         my $ret=match_link($_[1], $_[0], @_);
2283         $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2284         return $ret;
2287 sub match_created_before ($$;@) {
2288         my $page=shift;
2289         my $testpage=shift;
2290         my %params=@_;
2291         
2292         $testpage=derel($testpage, $params{location});
2294         if (exists $IkiWiki::pagectime{$testpage}) {
2295                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2296                         return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2297                 }
2298                 else {
2299                         return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2300                 }
2301         }
2302         else {
2303                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2304         }
2307 sub match_created_after ($$;@) {
2308         my $page=shift;
2309         my $testpage=shift;
2310         my %params=@_;
2311         
2312         $testpage=derel($testpage, $params{location});
2314         if (exists $IkiWiki::pagectime{$testpage}) {
2315                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2316                         return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2317                 }
2318                 else {
2319                         return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2320                 }
2321         }
2322         else {
2323                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2324         }
2327 sub match_creation_day ($$;@) {
2328         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2329                 return IkiWiki::SuccessReason->new('creation_day matched');
2330         }
2331         else {
2332                 return IkiWiki::FailReason->new('creation_day did not match');
2333         }
2336 sub match_creation_month ($$;@) {
2337         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2338                 return IkiWiki::SuccessReason->new('creation_month matched');
2339         }
2340         else {
2341                 return IkiWiki::FailReason->new('creation_month did not match');
2342         }
2345 sub match_creation_year ($$;@) {
2346         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2347                 return IkiWiki::SuccessReason->new('creation_year matched');
2348         }
2349         else {
2350                 return IkiWiki::FailReason->new('creation_year did not match');
2351         }
2354 sub match_user ($$;@) {
2355         shift;
2356         my $user=shift;
2357         my %params=@_;
2358         
2359         my $regexp=IkiWiki::glob2re($user);
2360         
2361         if (! exists $params{user}) {
2362                 return IkiWiki::ErrorReason->new("no user specified");
2363         }
2365         if (defined $params{user} && $params{user}=~/^$regexp$/i) {
2366                 return IkiWiki::SuccessReason->new("user is $user");
2367         }
2368         elsif (! defined $params{user}) {
2369                 return IkiWiki::FailReason->new("not logged in");
2370         }
2371         else {
2372                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2373         }
2376 sub match_admin ($$;@) {
2377         shift;
2378         shift;
2379         my %params=@_;
2380         
2381         if (! exists $params{user}) {
2382                 return IkiWiki::ErrorReason->new("no user specified");
2383         }
2385         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2386                 return IkiWiki::SuccessReason->new("user is an admin");
2387         }
2388         elsif (! defined $params{user}) {
2389                 return IkiWiki::FailReason->new("not logged in");
2390         }
2391         else {
2392                 return IkiWiki::FailReason->new("user is not an admin");
2393         }
2396 sub match_ip ($$;@) {
2397         shift;
2398         my $ip=shift;
2399         my %params=@_;
2400         
2401         if (! exists $params{ip}) {
2402                 return IkiWiki::ErrorReason->new("no IP specified");
2403         }
2405         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2406                 return IkiWiki::SuccessReason->new("IP is $ip");
2407         }
2408         else {
2409                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2410         }
2413 package IkiWiki::SortSpec;
2415 sub cmp_title {
2416         IkiWiki::pagetitle(IkiWiki::basename($_[0]))
2417         cmp
2418         IkiWiki::pagetitle(IkiWiki::basename($_[1]))
2421 sub cmp_mtime { $IkiWiki::pagemtime{$_[1]} <=> $IkiWiki::pagemtime{$_[0]} }
2422 sub cmp_age { $IkiWiki::pagectime{$_[1]} <=> $IkiWiki::pagectime{$_[0]} }