]> git.vanrenterghem.biz Git - git.ikiwiki.info.git/blob - IkiWiki.pm
refactor sortspec translation
[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 %typedlinks %oldtypedlinks};
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 %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 => "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/;
1168         
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/sanitizers
1190                 $content=~s/^<p>//i;
1191                 $content=~s/<\/p>\n*$//i;
1192         }
1194         return $content;
1197 sub linkify ($$$) {
1198         my $page=shift;
1199         my $destpage=shift;
1200         my $content=shift;
1202         run_hooks(linkify => sub {
1203                 $content=shift->(
1204                         page => $page,
1205                         destpage => $destpage,
1206                         content => $content,
1207                 );
1208         });
1209         
1210         return $content;
1213 our %preprocessing;
1214 our $preprocess_preview=0;
1215 sub preprocess ($$$;$$) {
1216         my $page=shift; # the page the data comes from
1217         my $destpage=shift; # the page the data will appear in (different for inline)
1218         my $content=shift;
1219         my $scan=shift;
1220         my $preview=shift;
1222         # Using local because it needs to be set within any nested calls
1223         # of this function.
1224         local $preprocess_preview=$preview if defined $preview;
1226         my $handle=sub {
1227                 my $escape=shift;
1228                 my $prefix=shift;
1229                 my $command=shift;
1230                 my $params=shift;
1231                 $params="" if ! defined $params;
1233                 if (length $escape) {
1234                         return "[[$prefix$command $params]]";
1235                 }
1236                 elsif (exists $hooks{preprocess}{$command}) {
1237                         return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1238                         # Note: preserve order of params, some plugins may
1239                         # consider it significant.
1240                         my @params;
1241                         while ($params =~ m{
1242                                 (?:([-\w]+)=)?          # 1: named parameter key?
1243                                 (?:
1244                                         """(.*?)"""     # 2: triple-quoted value
1245                                 |
1246                                         "([^"]*?)"      # 3: single-quoted value
1247                                 |
1248                                         (\S+)           # 4: unquoted value
1249                                 )
1250                                 (?:\s+|$)               # delimiter to next param
1251                         }sgx) {
1252                                 my $key=$1;
1253                                 my $val;
1254                                 if (defined $2) {
1255                                         $val=$2;
1256                                         $val=~s/\r\n/\n/mg;
1257                                         $val=~s/^\n+//g;
1258                                         $val=~s/\n+$//g;
1259                                 }
1260                                 elsif (defined $3) {
1261                                         $val=$3;
1262                                 }
1263                                 elsif (defined $4) {
1264                                         $val=$4;
1265                                 }
1267                                 if (defined $key) {
1268                                         push @params, $key, $val;
1269                                 }
1270                                 else {
1271                                         push @params, $val, '';
1272                                 }
1273                         }
1274                         if ($preprocessing{$page}++ > 3) {
1275                                 # Avoid loops of preprocessed pages preprocessing
1276                                 # other pages that preprocess them, etc.
1277                                 return "[[!$command <span class=\"error\">".
1278                                         sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1279                                                 $page, $preprocessing{$page}).
1280                                         "</span>]]";
1281                         }
1282                         my $ret;
1283                         if (! $scan) {
1284                                 $ret=eval {
1285                                         $hooks{preprocess}{$command}{call}->(
1286                                                 @params,
1287                                                 page => $page,
1288                                                 destpage => $destpage,
1289                                                 preview => $preprocess_preview,
1290                                         );
1291                                 };
1292                                 if ($@) {
1293                                         my $error=$@;
1294                                         chomp $error;
1295                                         $ret="[[!$command <span class=\"error\">".
1296                                                 gettext("Error").": $error"."</span>]]";
1297                                 }
1298                         }
1299                         else {
1300                                 # use void context during scan pass
1301                                 eval {
1302                                         $hooks{preprocess}{$command}{call}->(
1303                                                 @params,
1304                                                 page => $page,
1305                                                 destpage => $destpage,
1306                                                 preview => $preprocess_preview,
1307                                         );
1308                                 };
1309                                 $ret="";
1310                         }
1311                         $preprocessing{$page}--;
1312                         return $ret;
1313                 }
1314                 else {
1315                         return "[[$prefix$command $params]]";
1316                 }
1317         };
1318         
1319         my $regex;
1320         if ($config{prefix_directives}) {
1321                 $regex = qr{
1322                         (\\?)           # 1: escape?
1323                         \[\[(!)         # directive open; 2: prefix
1324                         ([-\w]+)        # 3: command
1325                         (               # 4: the parameters..
1326                                 \s+     # Must have space if parameters present
1327                                 (?:
1328                                         (?:[-\w]+=)?            # named parameter key?
1329                                         (?:
1330                                                 """.*?"""       # triple-quoted value
1331                                                 |
1332                                                 "[^"]*?"        # single-quoted value
1333                                                 |
1334                                                 [^"\s\]]+       # unquoted value
1335                                         )
1336                                         \s*                     # whitespace or end
1337                                                                 # of directive
1338                                 )
1339                         *)?             # 0 or more parameters
1340                         \]\]            # directive closed
1341                 }sx;
1342         }
1343         else {
1344                 $regex = qr{
1345                         (\\?)           # 1: escape?
1346                         \[\[(!?)        # directive open; 2: optional prefix
1347                         ([-\w]+)        # 3: command
1348                         \s+
1349                         (               # 4: the parameters..
1350                                 (?:
1351                                         (?:[-\w]+=)?            # named parameter key?
1352                                         (?:
1353                                                 """.*?"""       # triple-quoted value
1354                                                 |
1355                                                 "[^"]*?"        # single-quoted value
1356                                                 |
1357                                                 [^"\s\]]+       # unquoted value
1358                                         )
1359                                         \s*                     # whitespace or end
1360                                                                 # of directive
1361                                 )
1362                         *)              # 0 or more parameters
1363                         \]\]            # directive closed
1364                 }sx;
1365         }
1367         $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1368         return $content;
1371 sub filter ($$$) {
1372         my $page=shift;
1373         my $destpage=shift;
1374         my $content=shift;
1376         run_hooks(filter => sub {
1377                 $content=shift->(page => $page, destpage => $destpage, 
1378                         content => $content);
1379         });
1381         return $content;
1384 sub indexlink () {
1385         return "<a href=\"$config{url}\">$config{wikiname}</a>";
1388 sub check_canedit ($$$;$) {
1389         my $page=shift;
1390         my $q=shift;
1391         my $session=shift;
1392         my $nonfatal=shift;
1393         
1394         my $canedit;
1395         run_hooks(canedit => sub {
1396                 return if defined $canedit;
1397                 my $ret=shift->($page, $q, $session);
1398                 if (defined $ret) {
1399                         if ($ret eq "") {
1400                                 $canedit=1;
1401                         }
1402                         elsif (ref $ret eq 'CODE') {
1403                                 $ret->() unless $nonfatal;
1404                                 $canedit=0;
1405                         }
1406                         elsif (defined $ret) {
1407                                 error($ret) unless $nonfatal;
1408                                 $canedit=0;
1409                         }
1410                 }
1411         });
1412         return defined $canedit ? $canedit : 1;
1415 sub check_content (@) {
1416         my %params=@_;
1417         
1418         return 1 if ! exists $hooks{checkcontent}; # optimisation
1420         if (exists $pagesources{$params{page}}) {
1421                 my @diff;
1422                 my %old=map { $_ => 1 }
1423                         split("\n", readfile(srcfile($pagesources{$params{page}})));
1424                 foreach my $line (split("\n", $params{content})) {
1425                         push @diff, $line if ! exists $old{$line};
1426                 }
1427                 $params{diff}=join("\n", @diff);
1428         }
1430         my $ok;
1431         run_hooks(checkcontent => sub {
1432                 return if defined $ok;
1433                 my $ret=shift->(%params);
1434                 if (defined $ret) {
1435                         if ($ret eq "") {
1436                                 $ok=1;
1437                         }
1438                         elsif (ref $ret eq 'CODE') {
1439                                 $ret->() unless $params{nonfatal};
1440                                 $ok=0;
1441                         }
1442                         elsif (defined $ret) {
1443                                 error($ret) unless $params{nonfatal};
1444                                 $ok=0;
1445                         }
1446                 }
1448         });
1449         return defined $ok ? $ok : 1;
1452 my $wikilock;
1454 sub lockwiki () {
1455         # Take an exclusive lock on the wiki to prevent multiple concurrent
1456         # run issues. The lock will be dropped on program exit.
1457         if (! -d $config{wikistatedir}) {
1458                 mkdir($config{wikistatedir});
1459         }
1460         open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1461                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1462         if (! flock($wikilock, 2)) { # LOCK_EX
1463                 error("failed to get lock");
1464         }
1465         return 1;
1468 sub unlockwiki () {
1469         POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1470         return close($wikilock) if $wikilock;
1471         return;
1474 my $commitlock;
1476 sub commit_hook_enabled () {
1477         open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1478                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1479         if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1480                 close($commitlock) || error("failed closing commitlock: $!");
1481                 return 0;
1482         }
1483         close($commitlock) || error("failed closing commitlock: $!");
1484         return 1;
1487 sub disable_commit_hook () {
1488         open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1489                 error("cannot write to $config{wikistatedir}/commitlock: $!");
1490         if (! flock($commitlock, 2)) { # LOCK_EX
1491                 error("failed to get commit lock");
1492         }
1493         return 1;
1496 sub enable_commit_hook () {
1497         return close($commitlock) if $commitlock;
1498         return;
1501 sub loadindex () {
1502         %oldrenderedfiles=%pagectime=();
1503         if (! $config{rebuild}) {
1504                 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1505                 %destsources=%renderedfiles=%pagecase=%pagestate=
1506                 %depends_simple=%typedlinks=%oldtypedlinks=();
1507         }
1508         my $in;
1509         if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1510                 if (-e "$config{wikistatedir}/index") {
1511                         system("ikiwiki-transition", "indexdb", $config{srcdir});
1512                         open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1513                 }
1514                 else {
1515                         return;
1516                 }
1517         }
1519         my $index=Storable::fd_retrieve($in);
1520         if (! defined $index) {
1521                 return 0;
1522         }
1524         my $pages;
1525         if (exists $index->{version} && ! ref $index->{version}) {
1526                 $pages=$index->{page};
1527                 %wikistate=%{$index->{state}};
1528         }
1529         else {
1530                 $pages=$index;
1531                 %wikistate=();
1532         }
1534         foreach my $src (keys %$pages) {
1535                 my $d=$pages->{$src};
1536                 my $page=pagename($src);
1537                 $pagectime{$page}=$d->{ctime};
1538                 if (! $config{rebuild}) {
1539                         $pagesources{$page}=$src;
1540                         $pagemtime{$page}=$d->{mtime};
1541                         $renderedfiles{$page}=$d->{dest};
1542                         if (exists $d->{links} && ref $d->{links}) {
1543                                 $links{$page}=$d->{links};
1544                                 $oldlinks{$page}=[@{$d->{links}}];
1545                         }
1546                         if (ref $d->{depends_simple} eq 'ARRAY') {
1547                                 # old format
1548                                 $depends_simple{$page}={
1549                                         map { $_ => 1 } @{$d->{depends_simple}}
1550                                 };
1551                         }
1552                         elsif (exists $d->{depends_simple}) {
1553                                 $depends_simple{$page}=$d->{depends_simple};
1554                         }
1555                         if (exists $d->{dependslist}) {
1556                                 # old format
1557                                 $depends{$page}={
1558                                         map { $_ => $DEPEND_CONTENT }
1559                                                 @{$d->{dependslist}}
1560                                 };
1561                         }
1562                         elsif (exists $d->{depends} && ! ref $d->{depends}) {
1563                                 # old format
1564                                 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1565                         }
1566                         elsif (exists $d->{depends}) {
1567                                 $depends{$page}=$d->{depends};
1568                         }
1569                         if (exists $d->{state}) {
1570                                 $pagestate{$page}=$d->{state};
1571                         }
1572                         if (exists $d->{typedlinks}) {
1573                                 $typedlinks{$page}=$d->{typedlinks};
1575                                 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1576                                         next unless %$links;
1577                                         $oldtypedlinks{$page}{$type} = {%$links};
1578                                 }
1579                         }
1580                 }
1581                 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1582         }
1583         foreach my $page (keys %pagesources) {
1584                 $pagecase{lc $page}=$page;
1585         }
1586         foreach my $page (keys %renderedfiles) {
1587                 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1588         }
1589         return close($in);
1592 sub saveindex () {
1593         run_hooks(savestate => sub { shift->() });
1595         my %hookids;
1596         foreach my $type (keys %hooks) {
1597                 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1598         }
1599         my @hookids=keys %hookids;
1601         if (! -d $config{wikistatedir}) {
1602                 mkdir($config{wikistatedir});
1603         }
1604         my $newfile="$config{wikistatedir}/indexdb.new";
1605         my $cleanup = sub { unlink($newfile) };
1606         open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1608         my %index;
1609         foreach my $page (keys %pagemtime) {
1610                 next unless $pagemtime{$page};
1611                 my $src=$pagesources{$page};
1613                 $index{page}{$src}={
1614                         ctime => $pagectime{$page},
1615                         mtime => $pagemtime{$page},
1616                         dest => $renderedfiles{$page},
1617                         links => $links{$page},
1618                 };
1620                 if (exists $depends{$page}) {
1621                         $index{page}{$src}{depends} = $depends{$page};
1622                 }
1624                 if (exists $depends_simple{$page}) {
1625                         $index{page}{$src}{depends_simple} = $depends_simple{$page};
1626                 }
1628                 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1629                         $index{page}{$src}{typedlinks} = $typedlinks{$page};
1630                 }
1632                 if (exists $pagestate{$page}) {
1633                         foreach my $id (@hookids) {
1634                                 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1635                                         $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1636                                 }
1637                         }
1638                 }
1639         }
1641         $index{state}={};
1642         foreach my $id (@hookids) {
1643                 foreach my $key (keys %{$wikistate{$id}}) {
1644                         $index{state}{$id}{$key}=$wikistate{$id}{$key};
1645                 }
1646         }
1647         
1648         $index{version}="3";
1649         my $ret=Storable::nstore_fd(\%index, $out);
1650         return if ! defined $ret || ! $ret;
1651         close $out || error("failed saving to $newfile: $!", $cleanup);
1652         rename($newfile, "$config{wikistatedir}/indexdb") ||
1653                 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1654         
1655         return 1;
1658 sub template_file ($) {
1659         my $template=shift;
1661         foreach my $dir ($config{templatedir}, @{$config{templatedirs}},
1662                          "$installdir/share/ikiwiki/templates") {
1663                 return "$dir/$template" if -e "$dir/$template";
1664         }
1665         return;
1668 sub template_params (@) {
1669         my $filename=template_file(shift);
1671         if (! defined $filename) {
1672                 return if wantarray;
1673                 return "";
1674         }
1676         my @ret=(
1677                 filter => sub {
1678                         my $text_ref = shift;
1679                         ${$text_ref} = decode_utf8(${$text_ref});
1680                 },
1681                 filename => $filename,
1682                 loop_context_vars => 1,
1683                 die_on_bad_params => 0,
1684                 @_
1685         );
1686         return wantarray ? @ret : {@ret};
1689 sub template ($;@) {
1690         require HTML::Template;
1691         return HTML::Template->new(template_params(@_));
1694 sub misctemplate ($$;@) {
1695         my $title=shift;
1696         my $pagebody=shift;
1697         
1698         my $template=template("misc.tmpl");
1699         $template->param(
1700                 title => $title,
1701                 indexlink => indexlink(),
1702                 wikiname => $config{wikiname},
1703                 pagebody => $pagebody,
1704                 baseurl => baseurl(),
1705                 @_,
1706         );
1707         run_hooks(pagetemplate => sub {
1708                 shift->(page => "", destpage => "", template => $template);
1709         });
1710         return $template->output;
1713 sub hook (@) {
1714         my %param=@_;
1715         
1716         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1717                 error 'hook requires type, call, and id parameters';
1718         }
1720         return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1721         
1722         $hooks{$param{type}}{$param{id}}=\%param;
1723         return 1;
1726 sub run_hooks ($$) {
1727         # Calls the given sub for each hook of the given type,
1728         # passing it the hook function to call.
1729         my $type=shift;
1730         my $sub=shift;
1732         if (exists $hooks{$type}) {
1733                 my (@first, @middle, @last);
1734                 foreach my $id (keys %{$hooks{$type}}) {
1735                         if ($hooks{$type}{$id}{first}) {
1736                                 push @first, $id;
1737                         }
1738                         elsif ($hooks{$type}{$id}{last}) {
1739                                 push @last, $id;
1740                         }
1741                         else {
1742                                 push @middle, $id;
1743                         }
1744                 }
1745                 foreach my $id (@first, @middle, @last) {
1746                         $sub->($hooks{$type}{$id}{call});
1747                 }
1748         }
1750         return 1;
1753 sub rcs_update () {
1754         $hooks{rcs}{rcs_update}{call}->(@_);
1757 sub rcs_prepedit ($) {
1758         $hooks{rcs}{rcs_prepedit}{call}->(@_);
1761 sub rcs_commit ($$$;$$) {
1762         $hooks{rcs}{rcs_commit}{call}->(@_);
1765 sub rcs_commit_staged ($$$) {
1766         $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1769 sub rcs_add ($) {
1770         $hooks{rcs}{rcs_add}{call}->(@_);
1773 sub rcs_remove ($) {
1774         $hooks{rcs}{rcs_remove}{call}->(@_);
1777 sub rcs_rename ($$) {
1778         $hooks{rcs}{rcs_rename}{call}->(@_);
1781 sub rcs_recentchanges ($) {
1782         $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1785 sub rcs_diff ($) {
1786         $hooks{rcs}{rcs_diff}{call}->(@_);
1789 sub rcs_getctime ($) {
1790         $hooks{rcs}{rcs_getctime}{call}->(@_);
1793 sub rcs_receive () {
1794         $hooks{rcs}{rcs_receive}{call}->();
1797 sub add_depends ($$;$) {
1798         my $page=shift;
1799         my $pagespec=shift;
1800         my $deptype=shift || $DEPEND_CONTENT;
1802         # Is the pagespec a simple page name?
1803         if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1804             $pagespec !~ /[\s*?()!]/) {
1805                 $depends_simple{$page}{lc $pagespec} |= $deptype;
1806                 return 1;
1807         }
1809         # Add explicit dependencies for influences.
1810         my $sub=pagespec_translate($pagespec);
1811         return unless defined $sub;
1812         foreach my $p (keys %pagesources) {
1813                 my $r=$sub->($p, location => $page);
1814                 my $i=$r->influences;
1815                 foreach my $k (keys %$i) {
1816                         $depends_simple{$page}{lc $k} |= $i->{$k};
1817                 }
1818                 last if $r->influences_static;
1819         }
1821         $depends{$page}{$pagespec} |= $deptype;
1822         return 1;
1825 sub deptype (@) {
1826         my $deptype=0;
1827         foreach my $type (@_) {
1828                 if ($type eq 'presence') {
1829                         $deptype |= $DEPEND_PRESENCE;
1830                 }
1831                 elsif ($type eq 'links') { 
1832                         $deptype |= $DEPEND_LINKS;
1833                 }
1834                 elsif ($type eq 'content') {
1835                         $deptype |= $DEPEND_CONTENT;
1836                 }
1837         }
1838         return $deptype;
1841 my $file_prune_regexp;
1842 sub file_pruned ($;$) {
1843         my $file=shift;
1844         if (@_) {
1845                 require File::Spec;
1846                 $file=File::Spec->canonpath($file);
1847                 my $base=File::Spec->canonpath(shift);
1848                 return if $file eq $base;
1849                 $file =~ s#^\Q$base\E/+##;
1850         }
1852         if (defined $config{include} && length $config{include}) {
1853                 return 0 if $file =~ m/$config{include}/;
1854         }
1856         if (! defined $file_prune_regexp) {
1857                 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1858                 $file_prune_regexp=qr/$file_prune_regexp/;
1859         }
1860         return $file =~ m/$file_prune_regexp/;
1863 sub define_gettext () {
1864         # If translation is needed, redefine the gettext function to do it.
1865         # Otherwise, it becomes a quick no-op.
1866         my $gettext_obj;
1867         my $getobj;
1868         if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1869             (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1870             (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1871                 $getobj=sub {
1872                         $gettext_obj=eval q{
1873                                 use Locale::gettext q{textdomain};
1874                                 Locale::gettext->domain('ikiwiki')
1875                         };
1876                 };
1877         }
1879         no warnings 'redefine';
1880         *gettext=sub {
1881                 $getobj->() if $getobj;
1882                 if ($gettext_obj) {
1883                         $gettext_obj->get(shift);
1884                 }
1885                 else {
1886                         return shift;
1887                 }
1888         };
1889         *ngettext=sub {
1890                 $getobj->() if $getobj;
1891                 if ($gettext_obj) {
1892                         $gettext_obj->nget(@_);
1893                 }
1894                 else {
1895                         return ($_[2] == 1 ? $_[0] : $_[1])
1896                 }
1897         };
1900 sub gettext {
1901         define_gettext();
1902         gettext(@_);
1905 sub ngettext {
1906         define_gettext();
1907         ngettext(@_);
1910 sub yesno ($) {
1911         my $val=shift;
1913         return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1916 sub inject {
1917         # Injects a new function into the symbol table to replace an
1918         # exported function.
1919         my %params=@_;
1921         # This is deep ugly perl foo, beware.
1922         no strict;
1923         no warnings;
1924         if (! defined $params{parent}) {
1925                 $params{parent}='::';
1926                 $params{old}=\&{$params{name}};
1927                 $params{name}=~s/.*:://;
1928         }
1929         my $parent=$params{parent};
1930         foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1931                 $ns = $params{parent} . $ns;
1932                 inject(%params, parent => $ns) unless $ns eq '::main::';
1933                 *{$ns . $params{name}} = $params{call}
1934                         if exists ${$ns}{$params{name}} &&
1935                            \&{${$ns}{$params{name}}} == $params{old};
1936         }
1937         use strict;
1938         use warnings;
1941 sub add_link ($$;$) {
1942         my $page=shift;
1943         my $link=shift;
1944         my $type=shift;
1946         push @{$links{$page}}, $link
1947                 unless grep { $_ eq $link } @{$links{$page}};
1949         if (defined $type) {
1950                 $typedlinks{$page}{$type}{$link} = 1;
1951         }
1954 sub sortspec_translate ($$) {
1955         my $spec = shift;
1956         my $reverse = shift;
1958         my $code = "";
1959         my @data;
1960         while ($spec =~ m{
1961                 \s*
1962                 (-?)            # group 1: perhaps negated
1963                 \s*
1964                 (               # group 2: a word
1965                         \w+\([^\)]*\)   # command(params)
1966                         |
1967                         [^\s]+          # or anything else
1968                 )
1969                 \s*
1970         }gx) {
1971                 my $negated = $1;
1972                 my $word = $2;
1973                 my $params = undef;
1975                 if ($word =~ m/^(\w+)\((.*)\)$/) {
1976                         # command with parameters
1977                         $params = $2;
1978                         $word = $1;
1979                 }
1980                 elsif ($word !~ m/^\w+$/) {
1981                         error(sprintf(gettext("invalid sort type %s"), $word));
1982                 }
1984                 if (length $code) {
1985                         $code .= " || ";
1986                 }
1988                 if ($negated) {
1989                         $code .= "-";
1990                 }
1992                 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
1993                         if (defined $params) {
1994                                 push @data, $params;
1995                                 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
1996                         }
1997                         else {
1998                                 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
1999                         }
2000                 }
2001                 else {
2002                         error(sprintf(gettext("unknown sort type %s"), $word));
2003                 }
2004         }
2006         if (! length $code) {
2007                 # undefined sorting method... sort arbitrarily
2008                 return sub { 0 };
2009         }
2011         if ($reverse) {
2012                 $code="-($code)";
2013         }
2015         no warnings;
2016         return eval 'sub { '.$code.' }';
2019 sub pagespec_translate ($) {
2020         my $spec=shift;
2022         # Convert spec to perl code.
2023         my $code="";
2024         my @data;
2025         while ($spec=~m{
2026                 \s*             # ignore whitespace
2027                 (               # 1: match a single word
2028                         \!              # !
2029                 |
2030                         \(              # (
2031                 |
2032                         \)              # )
2033                 |
2034                         \w+\([^\)]*\)   # command(params)
2035                 |
2036                         [^\s()]+        # any other text
2037                 )
2038                 \s*             # ignore whitespace
2039         }gx) {
2040                 my $word=$1;
2041                 if (lc $word eq 'and') {
2042                         $code.=' &';
2043                 }
2044                 elsif (lc $word eq 'or') {
2045                         $code.=' |';
2046                 }
2047                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2048                         $code.=' '.$word;
2049                 }
2050                 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2051                         if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2052                                 push @data, $2;
2053                                 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2054                         }
2055                         else {
2056                                 push @data, qq{unknown function in pagespec "$word"};
2057                                 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2058                         }
2059                 }
2060                 else {
2061                         push @data, $word;
2062                         $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2063                 }
2064         }
2066         if (! length $code) {
2067                 $code="IkiWiki::FailReason->new('empty pagespec')";
2068         }
2070         no warnings;
2071         return eval 'sub { my $page=shift; '.$code.' }';
2074 sub pagespec_match ($$;@) {
2075         my $page=shift;
2076         my $spec=shift;
2077         my @params=@_;
2079         # Backwards compatability with old calling convention.
2080         if (@params == 1) {
2081                 unshift @params, 'location';
2082         }
2084         my $sub=pagespec_translate($spec);
2085         return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2086                 if ! defined $sub;
2087         return $sub->($page, @params);
2090 sub pagespec_match_list ($$;@) {
2091         my $page=shift;
2092         my $pagespec=shift;
2093         my %params=@_;
2095         # Backwards compatability with old calling convention.
2096         if (ref $page) {
2097                 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2098                 $params{list}=$page;
2099                 $page=$params{location}; # ugh!
2100         }
2102         my $sub=pagespec_translate($pagespec);
2103         error "syntax error in pagespec \"$pagespec\""
2104                 if ! defined $sub;
2105         my $sort=sortspec_translate($params{sort}, $params{reverse})
2106                 if defined $params{sort};
2108         my @candidates;
2109         if (exists $params{list}) {
2110                 @candidates=exists $params{filter}
2111                         ? grep { ! $params{filter}->($_) } @{$params{list}}
2112                         : @{$params{list}};
2113         }
2114         else {
2115                 @candidates=exists $params{filter}
2116                         ? grep { ! $params{filter}->($_) } keys %pagesources
2117                         : keys %pagesources;
2118         }
2119         
2120         # clear params, remainder is passed to pagespec
2121         $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2122         my $num=$params{num};
2123         delete @params{qw{num deptype reverse sort filter list}};
2124         
2125         # when only the top matches will be returned, it's efficient to
2126         # sort before matching to pagespec,
2127         if (defined $num && defined $sort) {
2128                 @candidates=IkiWiki::SortSpec::sort_pages(
2129                         $sort, @candidates);
2130         }
2131         
2132         my @matches;
2133         my $firstfail;
2134         my $count=0;
2135         my $accum=IkiWiki::SuccessReason->new();
2136         foreach my $p (@candidates) {
2137                 my $r=$sub->($p, %params, location => $page);
2138                 error(sprintf(gettext("cannot match pages: %s"), $r))
2139                         if $r->isa("IkiWiki::ErrorReason");
2140                 $accum |= $r;
2141                 if ($r) {
2142                         push @matches, $p;
2143                         last if defined $num && ++$count == $num;
2144                 }
2145         }
2147         # Add simple dependencies for accumulated influences.
2148         my $i=$accum->influences;
2149         foreach my $k (keys %$i) {
2150                 $depends_simple{$page}{lc $k} |= $i->{$k};
2151         }
2153         # when all matches will be returned, it's efficient to
2154         # sort after matching
2155         if (! defined $num && defined $sort) {
2156                 return IkiWiki::SortSpec::sort_pages(
2157                         $sort, @matches);
2158         }
2159         else {
2160                 return @matches;
2161         }
2164 sub pagespec_valid ($) {
2165         my $spec=shift;
2167         return defined pagespec_translate($spec);
2170 sub glob2re ($) {
2171         my $re=quotemeta(shift);
2172         $re=~s/\\\*/.*/g;
2173         $re=~s/\\\?/./g;
2174         return $re;
2177 package IkiWiki::FailReason;
2179 use overload (
2180         '""'    => sub { $_[0][0] },
2181         '0+'    => sub { 0 },
2182         '!'     => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2183         '&'     => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2184         '|'     => sub { $_[1]->merge_influences($_[0]); $_[1] },
2185         fallback => 1,
2186 );
2188 our @ISA = 'IkiWiki::SuccessReason';
2190 package IkiWiki::SuccessReason;
2192 use overload (
2193         '""'    => sub { $_[0][0] },
2194         '0+'    => sub { 1 },
2195         '!'     => sub { bless $_[0], 'IkiWiki::FailReason'},
2196         '&'     => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2197         '|'     => sub { $_[0]->merge_influences($_[1]); $_[0] },
2198         fallback => 1,
2199 );
2201 sub new {
2202         my $class = shift;
2203         my $value = shift;
2204         return bless [$value, {@_}], $class;
2207 sub influences {
2208         my $this=shift;
2209         $this->[1]={@_} if @_;
2210         my %i=%{$this->[1]};
2211         delete $i{""};
2212         return \%i;
2215 sub influences_static {
2216         return ! $_[0][1]->{""};
2219 sub merge_influences {
2220         my $this=shift;
2221         my $other=shift;
2222         my $anded=shift;
2224         if (! $anded || (($this || %{$this->[1]}) &&
2225                         ($other || %{$other->[1]}))) {
2226                 foreach my $influence (keys %{$other->[1]}) {
2227                         $this->[1]{$influence} |= $other->[1]{$influence};
2228                 }
2229         }
2230         else {
2231                 # influence blocker
2232                 $this->[1]={};
2233         }
2236 package IkiWiki::ErrorReason;
2238 our @ISA = 'IkiWiki::FailReason';
2240 package IkiWiki::PageSpec;
2242 sub derel ($$) {
2243         my $path=shift;
2244         my $from=shift;
2246         if ($path =~ m!^\./!) {
2247                 $from=~s#/?[^/]+$## if defined $from;
2248                 $path=~s#^\./##;
2249                 $path="$from/$path" if length $from;
2250         }
2252         return $path;
2255 sub match_glob ($$;@) {
2256         my $page=shift;
2257         my $glob=shift;
2258         my %params=@_;
2259         
2260         $glob=derel($glob, $params{location});
2262         my $regexp=IkiWiki::glob2re($glob);
2263         if ($page=~/^$regexp$/i) {
2264                 if (! IkiWiki::isinternal($page) || $params{internal}) {
2265                         return IkiWiki::SuccessReason->new("$glob matches $page");
2266                 }
2267                 else {
2268                         return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2269                 }
2270         }
2271         else {
2272                 return IkiWiki::FailReason->new("$glob does not match $page");
2273         }
2276 sub match_internal ($$;@) {
2277         return match_glob($_[0], $_[1], @_, internal => 1)
2280 sub match_link ($$;@) {
2281         my $page=shift;
2282         my $link=lc(shift);
2283         my %params=@_;
2285         $link=derel($link, $params{location});
2286         my $from=exists $params{location} ? $params{location} : '';
2287         my $linktype=$params{linktype};
2288         my $qualifier='';
2289         if (defined $linktype) {
2290                 $qualifier=" with type $linktype";
2291         }
2293         my $links = $IkiWiki::links{$page};
2294         return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2295                 unless $links && @{$links};
2296         my $bestlink = IkiWiki::bestlink($from, $link);
2297         foreach my $p (@{$links}) {
2298                 if (length $bestlink) {
2299                         if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p}) && $bestlink eq IkiWiki::bestlink($page, $p)) {
2300                                 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2301                         }
2302                 }
2303                 else {
2304                         if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p}) && match_glob($p, $link, %params)) {
2305                                 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2306                         }
2307                         my ($p_rel)=$p=~/^\/?(.*)/;
2308                         $link=~s/^\///;
2309                         if ((!defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p_rel}) && match_glob($p_rel, $link, %params)) {
2310                                 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2311                         }
2312                 }
2313         }
2314         return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2317 sub match_backlink ($$;@) {
2318         my $ret=match_link($_[1], $_[0], @_);
2319         $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2320         return $ret;
2323 sub match_created_before ($$;@) {
2324         my $page=shift;
2325         my $testpage=shift;
2326         my %params=@_;
2327         
2328         $testpage=derel($testpage, $params{location});
2330         if (exists $IkiWiki::pagectime{$testpage}) {
2331                 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2332                         return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2333                 }
2334                 else {
2335                         return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2336                 }
2337         }
2338         else {
2339                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2340         }
2343 sub match_created_after ($$;@) {
2344         my $page=shift;
2345         my $testpage=shift;
2346         my %params=@_;
2347         
2348         $testpage=derel($testpage, $params{location});
2350         if (exists $IkiWiki::pagectime{$testpage}) {
2351                 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2352                         return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2353                 }
2354                 else {
2355                         return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2356                 }
2357         }
2358         else {
2359                 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2360         }
2363 sub match_creation_day ($$;@) {
2364         if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2365                 return IkiWiki::SuccessReason->new('creation_day matched');
2366         }
2367         else {
2368                 return IkiWiki::FailReason->new('creation_day did not match');
2369         }
2372 sub match_creation_month ($$;@) {
2373         if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2374                 return IkiWiki::SuccessReason->new('creation_month matched');
2375         }
2376         else {
2377                 return IkiWiki::FailReason->new('creation_month did not match');
2378         }
2381 sub match_creation_year ($$;@) {
2382         if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2383                 return IkiWiki::SuccessReason->new('creation_year matched');
2384         }
2385         else {
2386                 return IkiWiki::FailReason->new('creation_year did not match');
2387         }
2390 sub match_user ($$;@) {
2391         shift;
2392         my $user=shift;
2393         my %params=@_;
2394         
2395         my $regexp=IkiWiki::glob2re($user);
2396         
2397         if (! exists $params{user}) {
2398                 return IkiWiki::ErrorReason->new("no user specified");
2399         }
2401         if (defined $params{user} && $params{user}=~/^$regexp$/i) {
2402                 return IkiWiki::SuccessReason->new("user is $user");
2403         }
2404         elsif (! defined $params{user}) {
2405                 return IkiWiki::FailReason->new("not logged in");
2406         }
2407         else {
2408                 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2409         }
2412 sub match_admin ($$;@) {
2413         shift;
2414         shift;
2415         my %params=@_;
2416         
2417         if (! exists $params{user}) {
2418                 return IkiWiki::ErrorReason->new("no user specified");
2419         }
2421         if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2422                 return IkiWiki::SuccessReason->new("user is an admin");
2423         }
2424         elsif (! defined $params{user}) {
2425                 return IkiWiki::FailReason->new("not logged in");
2426         }
2427         else {
2428                 return IkiWiki::FailReason->new("user is not an admin");
2429         }
2432 sub match_ip ($$;@) {
2433         shift;
2434         my $ip=shift;
2435         my %params=@_;
2436         
2437         if (! exists $params{ip}) {
2438                 return IkiWiki::ErrorReason->new("no IP specified");
2439         }
2441         if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2442                 return IkiWiki::SuccessReason->new("IP is $ip");
2443         }
2444         else {
2445                 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2446         }
2449 package IkiWiki::SortSpec;
2451 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2452 # are easily available in this namespace, for cmp functions to use them.
2453 sub sort_pages {
2454         my $f=shift;
2455         sort $f @_
2458 sub cmp_title {
2459         IkiWiki::pagetitle(IkiWiki::basename($a))
2460         cmp
2461         IkiWiki::pagetitle(IkiWiki::basename($b))
2464 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2465 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }