avoid uninitialized value warning when running -dumpsetup
[ikiwiki.git] / IkiWiki.pm
blob7d1f5c401f3daf6f6eeb7726a46e2f36fa1a7356
1 #!/usr/bin/perl
3 package IkiWiki;
5 use warnings;
6 use strict;
7 use Encode;
8 use URI::Escape q{uri_escape_utf8};
9 use POSIX ();
10 use Storable;
11 use open qw{:utf8 :std};
13 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
14 %pagestate %wikistate %renderedfiles %oldrenderedfiles
15 %pagesources %delpagesources %destsources %depends %depends_simple
16 @mass_depends %hooks %forcerebuild %loaded_plugins %typedlinks
17 %oldtypedlinks %autofiles};
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error htmlpage template template_depends
21 deptype add_depends pagespec_match pagespec_match_list bestlink
22 htmllink readfile writefile pagetype srcfile pagename
23 displaytime will_render gettext ngettext urlto targetpage
24 add_underlay pagetitle titlepage linkpage newpagefile
25 inject add_link add_autofile
26 %config %links %pagestate %wikistate %renderedfiles
27 %pagesources %destsources %typedlinks);
28 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
29 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
30 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
32 # Page dependency types.
33 our $DEPEND_CONTENT=1;
34 our $DEPEND_PRESENCE=2;
35 our $DEPEND_LINKS=4;
37 # Optimisation.
38 use Memoize;
39 memoize("abs2rel");
40 memoize("sortspec_translate");
41 memoize("pagespec_translate");
42 memoize("template_file");
44 sub getsetup () {
45 wikiname => {
46 type => "string",
47 default => "wiki",
48 description => "name of the wiki",
49 safe => 1,
50 rebuild => 1,
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,
60 adminuser => {
61 type => "string",
62 default => [],
63 description => "users who are wiki admins",
64 safe => 1,
65 rebuild => 0,
67 banned_users => {
68 type => "string",
69 default => [],
70 description => "users who are banned from the wiki",
71 safe => 1,
72 rebuild => 0,
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,
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,
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,
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,
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,
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,
121 rcs => {
122 type => "string",
123 default => '',
124 description => "rcs backend to use",
125 safe => 0, # don't allow overriding
126 rebuild => 0,
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,
137 add_plugins => {
138 type => "string",
139 default => [],
140 description => "plugins to add to the default configuration",
141 safe => 1,
142 rebuild => 1,
144 disable_plugins => {
145 type => "string",
146 default => [],
147 description => "plugins to disable",
148 safe => 1,
149 rebuild => 1,
151 templatedir => {
152 type => "string",
153 default => "$installdir/share/ikiwiki/templates",
154 description => "additional directory to search for template files",
155 advanced => 1,
156 safe => 0, # path
157 rebuild => 1,
159 underlaydir => {
160 type => "string",
161 default => "$installdir/share/ikiwiki/basewiki",
162 description => "base wiki source location",
163 advanced => 1,
164 safe => 0, # path
165 rebuild => 0,
167 underlaydirbase => {
168 type => "internal",
169 default => "$installdir/share/ikiwiki",
170 description => "parent directory containing additional underlays",
171 safe => 0,
172 rebuild => 0,
174 wrappers => {
175 type => "internal",
176 default => [],
177 description => "wrappers to generate",
178 safe => 0,
179 rebuild => 0,
181 underlaydirs => {
182 type => "internal",
183 default => [],
184 description => "additional underlays to use",
185 safe => 0,
186 rebuild => 0,
188 verbose => {
189 type => "boolean",
190 example => 1,
191 description => "display verbose messages?",
192 safe => 1,
193 rebuild => 0,
195 syslog => {
196 type => "boolean",
197 example => 1,
198 description => "log to syslog?",
199 safe => 1,
200 rebuild => 0,
202 usedirs => {
203 type => "boolean",
204 default => 1,
205 description => "create output files named page/index.html?",
206 safe => 0, # changing requires manual transition
207 rebuild => 1,
209 prefix_directives => {
210 type => "boolean",
211 default => 1,
212 description => "use '!'-prefixed preprocessor directives?",
213 safe => 0, # changing requires manual transition
214 rebuild => 1,
216 indexpages => {
217 type => "boolean",
218 default => 0,
219 description => "use page/index.mdwn source files",
220 safe => 1,
221 rebuild => 1,
223 discussion => {
224 type => "boolean",
225 default => 1,
226 description => "enable Discussion pages?",
227 safe => 1,
228 rebuild => 1,
230 discussionpage => {
231 type => "string",
232 default => gettext("Discussion"),
233 description => "name of Discussion pages",
234 safe => 1,
235 rebuild => 1,
237 html5 => {
238 type => "boolean",
239 default => 0,
240 description => "generate HTML5? (experimental)",
241 advanced => 1,
242 safe => 1,
243 rebuild => 1,
245 sslcookie => {
246 type => "boolean",
247 default => 0,
248 description => "only send cookies over SSL connections?",
249 advanced => 1,
250 safe => 1,
251 rebuild => 0,
253 default_pageext => {
254 type => "string",
255 default => "mdwn",
256 description => "extension to use for new pages",
257 safe => 0, # not sanitized
258 rebuild => 0,
260 htmlext => {
261 type => "string",
262 default => "html",
263 description => "extension to use for html files",
264 safe => 0, # not sanitized
265 rebuild => 1,
267 timeformat => {
268 type => "string",
269 default => '%c',
270 description => "strftime format string to display date",
271 advanced => 1,
272 safe => 1,
273 rebuild => 1,
275 locale => {
276 type => "string",
277 default => undef,
278 example => "en_US.UTF-8",
279 description => "UTF-8 locale to use",
280 advanced => 1,
281 safe => 0,
282 rebuild => 1,
284 userdir => {
285 type => "string",
286 default => "",
287 example => "users",
288 description => "put user pages below specified page",
289 safe => 1,
290 rebuild => 1,
292 numbacklinks => {
293 type => "integer",
294 default => 10,
295 description => "how many backlinks to show before hiding excess (0 to show all)",
296 safe => 1,
297 rebuild => 1,
299 hardlink => {
300 type => "boolean",
301 default => 0,
302 description => "attempt to hardlink source files? (optimisation for large files)",
303 advanced => 1,
304 safe => 0, # paranoia
305 rebuild => 0,
307 umask => {
308 type => "integer",
309 example => "022",
310 description => "force ikiwiki to use a particular umask",
311 advanced => 1,
312 safe => 0, # paranoia
313 rebuild => 0,
315 wrappergroup => {
316 type => "string",
317 example => "ikiwiki",
318 description => "group for wrappers to run in",
319 advanced => 1,
320 safe => 0, # paranoia
321 rebuild => 0,
323 libdir => {
324 type => "string",
325 default => "",
326 example => "$ENV{HOME}/.ikiwiki/",
327 description => "extra library and plugin directory",
328 advanced => 1,
329 safe => 0, # directory
330 rebuild => 0,
332 ENV => {
333 type => "string",
334 default => {},
335 description => "environment variables",
336 safe => 0, # paranoia
337 rebuild => 0,
339 include => {
340 type => "string",
341 default => undef,
342 example => '^\.htaccess$',
343 description => "regexp of normally excluded files to include",
344 advanced => 1,
345 safe => 0, # regexp
346 rebuild => 1,
348 exclude => {
349 type => "string",
350 default => undef,
351 example => '^(*\.private|Makefile)$',
352 description => "regexp of files that should be skipped",
353 advanced => 1,
354 safe => 0, # regexp
355 rebuild => 1,
357 wiki_file_prune_regexps => {
358 type => "internal",
359 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\//, qr/^\./, qr/\/\./,
360 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
361 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
362 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
363 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
364 description => "regexps of source files to ignore",
365 safe => 0,
366 rebuild => 1,
368 wiki_file_chars => {
369 type => "string",
370 description => "specifies the characters that are allowed in source filenames",
371 default => "-[:alnum:]+/.:_",
372 safe => 0,
373 rebuild => 1,
375 wiki_file_regexp => {
376 type => "internal",
377 description => "regexp of legal source files",
378 safe => 0,
379 rebuild => 1,
381 web_commit_regexp => {
382 type => "internal",
383 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
384 description => "regexp to parse web commits from logs",
385 safe => 0,
386 rebuild => 0,
388 cgi => {
389 type => "internal",
390 default => 0,
391 description => "run as a cgi",
392 safe => 0,
393 rebuild => 0,
395 cgi_disable_uploads => {
396 type => "internal",
397 default => 1,
398 description => "whether CGI should accept file uploads",
399 safe => 0,
400 rebuild => 0,
402 post_commit => {
403 type => "internal",
404 default => 0,
405 description => "run as a post-commit hook",
406 safe => 0,
407 rebuild => 0,
409 rebuild => {
410 type => "internal",
411 default => 0,
412 description => "running in rebuild mode",
413 safe => 0,
414 rebuild => 0,
416 setup => {
417 type => "internal",
418 default => undef,
419 description => "running in setup mode",
420 safe => 0,
421 rebuild => 0,
423 clean => {
424 type => "internal",
425 default => 0,
426 description => "running in clean mode",
427 safe => 0,
428 rebuild => 0,
430 refresh => {
431 type => "internal",
432 default => 0,
433 description => "running in refresh mode",
434 safe => 0,
435 rebuild => 0,
437 test_receive => {
438 type => "internal",
439 default => 0,
440 description => "running in receive test mode",
441 safe => 0,
442 rebuild => 0,
444 wrapper_background_command => {
445 type => "internal",
446 default => '',
447 description => "background shell command to run",
448 safe => 0,
449 rebuild => 0,
451 gettime => {
452 type => "internal",
453 description => "running in gettime mode",
454 safe => 0,
455 rebuild => 0,
457 w3mmode => {
458 type => "internal",
459 default => 0,
460 description => "running in w3mmode",
461 safe => 0,
462 rebuild => 0,
464 wikistatedir => {
465 type => "internal",
466 default => undef,
467 description => "path to the .ikiwiki directory holding ikiwiki state",
468 safe => 0,
469 rebuild => 0,
471 setupfile => {
472 type => "internal",
473 default => undef,
474 description => "path to setup file",
475 safe => 0,
476 rebuild => 0,
478 setuptype => {
479 type => "internal",
480 default => "Standard",
481 description => "perl class to use to dump setup file",
482 safe => 0,
483 rebuild => 0,
485 allow_symlinks_before_srcdir => {
486 type => "boolean",
487 default => 0,
488 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
489 safe => 0,
490 rebuild => 0,
494 sub defaultconfig () {
495 my %s=getsetup();
496 my @ret;
497 foreach my $key (keys %s) {
498 push @ret, $key, $s{$key}->{default};
500 use Data::Dumper;
501 return @ret;
504 # URL to top of wiki as a path starting with /, valid from any wiki page or
505 # the CGI; if that's not possible, an absolute URL. Either way, it ends with /
506 my $local_url;
507 # URL to CGI script, similar to $local_url
508 my $local_cgiurl;
510 sub checkconfig () {
511 # locale stuff; avoid LC_ALL since it overrides everything
512 if (defined $ENV{LC_ALL}) {
513 $ENV{LANG} = $ENV{LC_ALL};
514 delete $ENV{LC_ALL};
516 if (defined $config{locale}) {
517 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
518 $ENV{LANG}=$config{locale};
519 define_gettext();
523 if (! defined $config{wiki_file_regexp}) {
524 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
527 if (ref $config{ENV} eq 'HASH') {
528 foreach my $val (keys %{$config{ENV}}) {
529 $ENV{$val}=$config{ENV}{$val};
533 if ($config{w3mmode}) {
534 eval q{use Cwd q{abs_path}};
535 error($@) if $@;
536 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
537 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
538 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
539 unless $config{cgiurl} =~ m!file:///!;
540 $config{url}="file://".$config{destdir};
543 if ($config{cgi} && ! length $config{url}) {
544 error(gettext("Must specify url to wiki with --url when using --cgi"));
547 if (defined $config{url} && length $config{url}) {
548 eval q{use URI};
549 my $baseurl = URI->new($config{url});
551 $local_url = $baseurl->path . "/";
552 $local_cgiurl = undef;
554 if (length $config{cgiurl}) {
555 my $cgiurl = URI->new($config{cgiurl});
557 $local_cgiurl = $cgiurl->path;
559 if ($cgiurl->scheme ne $baseurl->scheme or
560 $cgiurl->authority ne $baseurl->authority) {
561 # too far apart, fall back to absolute URLs
562 $local_url = "$config{url}/";
563 $local_cgiurl = $config{cgiurl};
567 $local_url =~ s{//$}{/};
569 else {
570 $local_cgiurl = $config{cgiurl};
573 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
574 unless exists $config{wikistatedir} && defined $config{wikistatedir};
576 if (defined $config{umask}) {
577 umask(possibly_foolish_untaint($config{umask}));
580 run_hooks(checkconfig => sub { shift->() });
582 return 1;
585 sub listplugins () {
586 my %ret;
588 foreach my $dir (@INC, $config{libdir}) {
589 next unless defined $dir && length $dir;
590 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
591 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
592 $ret{$plugin}=1;
595 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
596 next unless defined $dir && length $dir;
597 foreach my $file (glob("$dir/plugins/*")) {
598 $ret{basename($file)}=1 if -x $file;
602 return keys %ret;
605 sub loadplugins () {
606 if (defined $config{libdir} && length $config{libdir}) {
607 unshift @INC, possibly_foolish_untaint($config{libdir});
610 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
611 loadplugin($plugin);
614 if ($config{rcs}) {
615 if (exists $hooks{rcs}) {
616 error(gettext("cannot use multiple rcs plugins"));
618 loadplugin($config{rcs});
620 if (! exists $hooks{rcs}) {
621 loadplugin("norcs");
624 run_hooks(getopt => sub { shift->() });
625 if (grep /^-/, @ARGV) {
626 print STDERR "Unknown option (or missing parameter): $_\n"
627 foreach grep /^-/, @ARGV;
628 usage();
631 return 1;
634 sub loadplugin ($;$) {
635 my $plugin=shift;
636 my $force=shift;
638 return if ! $force && grep { $_ eq $plugin} @{$config{disable_plugins}};
640 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
641 "$installdir/lib/ikiwiki") {
642 if (defined $dir && -x "$dir/plugins/$plugin") {
643 eval { require IkiWiki::Plugin::external };
644 if ($@) {
645 my $reason=$@;
646 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
648 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
649 $loaded_plugins{$plugin}=1;
650 return 1;
654 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
655 eval qq{use $mod};
656 if ($@) {
657 error("Failed to load plugin $mod: $@");
659 $loaded_plugins{$plugin}=1;
660 return 1;
663 sub error ($;$) {
664 my $message=shift;
665 my $cleaner=shift;
666 log_message('err' => $message) if $config{syslog};
667 if (defined $cleaner) {
668 $cleaner->();
670 die $message."\n";
673 sub debug ($) {
674 return unless $config{verbose};
675 return log_message(debug => @_);
678 my $log_open=0;
679 sub log_message ($$) {
680 my $type=shift;
682 if ($config{syslog}) {
683 require Sys::Syslog;
684 if (! $log_open) {
685 Sys::Syslog::setlogsock('unix');
686 Sys::Syslog::openlog('ikiwiki', '', 'user');
687 $log_open=1;
689 return eval {
690 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
693 elsif (! $config{cgi}) {
694 return print "@_\n";
696 else {
697 return print STDERR "@_\n";
701 sub possibly_foolish_untaint ($) {
702 my $tainted=shift;
703 my ($untainted)=$tainted=~/(.*)/s;
704 return $untainted;
707 sub basename ($) {
708 my $file=shift;
710 $file=~s!.*/+!!;
711 return $file;
714 sub dirname ($) {
715 my $file=shift;
717 $file=~s!/*[^/]+$!!;
718 return $file;
721 sub isinternal ($) {
722 my $page=shift;
723 return exists $pagesources{$page} &&
724 $pagesources{$page} =~ /\._([^.]+)$/;
727 sub pagetype ($) {
728 my $file=shift;
730 if ($file =~ /\.([^.]+)$/) {
731 return $1 if exists $hooks{htmlize}{$1};
733 my $base=basename($file);
734 if (exists $hooks{htmlize}{$base} &&
735 $hooks{htmlize}{$base}{noextension}) {
736 return $base;
738 return;
741 my %pagename_cache;
743 sub pagename ($) {
744 my $file=shift;
746 if (exists $pagename_cache{$file}) {
747 return $pagename_cache{$file};
750 my $type=pagetype($file);
751 my $page=$file;
752 $page=~s/\Q.$type\E*$//
753 if defined $type && !$hooks{htmlize}{$type}{keepextension}
754 && !$hooks{htmlize}{$type}{noextension};
755 if ($config{indexpages} && $page=~/(.*)\/index$/) {
756 $page=$1;
759 $pagename_cache{$file} = $page;
760 return $page;
763 sub newpagefile ($$) {
764 my $page=shift;
765 my $type=shift;
767 if (! $config{indexpages} || $page eq 'index') {
768 return $page.".".$type;
770 else {
771 return $page."/index.".$type;
775 sub targetpage ($$;$) {
776 my $page=shift;
777 my $ext=shift;
778 my $filename=shift;
780 if (defined $filename) {
781 return $page."/".$filename.".".$ext;
783 elsif (! $config{usedirs} || $page eq 'index') {
784 return $page.".".$ext;
786 else {
787 return $page."/index.".$ext;
791 sub htmlpage ($) {
792 my $page=shift;
794 return targetpage($page, $config{htmlext});
797 sub srcfile_stat {
798 my $file=shift;
799 my $nothrow=shift;
801 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
802 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
803 return "$dir/$file", stat(_) if -e "$dir/$file";
805 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
806 return;
809 sub srcfile ($;$) {
810 return (srcfile_stat(@_))[0];
813 sub add_literal_underlay ($) {
814 my $dir=shift;
816 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
817 unshift @{$config{underlaydirs}}, $dir;
821 sub add_underlay ($) {
822 my $dir = shift;
824 if ($dir !~ /^\//) {
825 $dir="$config{underlaydirbase}/$dir";
828 add_literal_underlay($dir);
829 # why does it return 1? we just don't know
830 return 1;
833 sub readfile ($;$$) {
834 my $file=shift;
835 my $binary=shift;
836 my $wantfd=shift;
838 if (-l $file) {
839 error("cannot read a symlink ($file)");
842 local $/=undef;
843 open (my $in, "<", $file) || error("failed to read $file: $!");
844 binmode($in) if ($binary);
845 return \*$in if $wantfd;
846 my $ret=<$in>;
847 # check for invalid utf-8, and toss it back to avoid crashes
848 if (! utf8::valid($ret)) {
849 $ret=encode_utf8($ret);
851 close $in || error("failed to read $file: $!");
852 return $ret;
855 sub prep_writefile ($$) {
856 my $file=shift;
857 my $destdir=shift;
859 my $test=$file;
860 while (length $test) {
861 if (-l "$destdir/$test") {
862 error("cannot write to a symlink ($test)");
864 if (-f _ && $test ne $file) {
865 # Remove conflicting file.
866 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
867 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
868 if ($f eq $test) {
869 unlink("$destdir/$test");
870 last;
875 $test=dirname($test);
878 my $dir=dirname("$destdir/$file");
879 if (! -d $dir) {
880 my $d="";
881 foreach my $s (split(m!/+!, $dir)) {
882 $d.="$s/";
883 if (! -d $d) {
884 mkdir($d) || error("failed to create directory $d: $!");
889 return 1;
892 sub writefile ($$$;$$) {
893 my $file=shift; # can include subdirs
894 my $destdir=shift; # directory to put file in
895 my $content=shift;
896 my $binary=shift;
897 my $writer=shift;
899 prep_writefile($file, $destdir);
901 my $newfile="$destdir/$file.ikiwiki-new";
902 if (-l $newfile) {
903 error("cannot write to a symlink ($newfile)");
906 my $cleanup = sub { unlink($newfile) };
907 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
908 binmode($out) if ($binary);
909 if ($writer) {
910 $writer->(\*$out, $cleanup);
912 else {
913 print $out $content or error("failed writing to $newfile: $!", $cleanup);
915 close $out || error("failed saving $newfile: $!", $cleanup);
916 rename($newfile, "$destdir/$file") ||
917 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
919 return 1;
922 my %cleared;
923 sub will_render ($$;$) {
924 my $page=shift;
925 my $dest=shift;
926 my $clear=shift;
928 # Important security check for independently created files.
929 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
930 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
931 my $from_other_page=0;
932 # Expensive, but rarely runs.
933 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
934 if (grep {
935 $_ eq $dest ||
936 dirname($_) eq $dest
937 } @{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
938 $from_other_page=1;
939 last;
943 error("$config{destdir}/$dest independently created, not overwriting with version from $page")
944 unless $from_other_page;
947 # If $dest exists as a directory, remove conflicting files in it
948 # rendered from other pages.
949 if (-d _) {
950 foreach my $p (keys %renderedfiles, keys %oldrenderedfiles) {
951 foreach my $f (@{$renderedfiles{$p}}, @{$oldrenderedfiles{$p}}) {
952 if (dirname($f) eq $dest) {
953 unlink("$config{destdir}/$f");
954 rmdir(dirname("$config{destdir}/$f"));
960 if (! $clear || $cleared{$page}) {
961 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
963 else {
964 foreach my $old (@{$renderedfiles{$page}}) {
965 delete $destsources{$old};
967 $renderedfiles{$page}=[$dest];
968 $cleared{$page}=1;
970 $destsources{$dest}=$page;
972 return 1;
975 sub bestlink ($$) {
976 my $page=shift;
977 my $link=shift;
979 my $cwd=$page;
980 if ($link=~s/^\/+//) {
981 # absolute links
982 $cwd="";
984 $link=~s/\/$//;
986 do {
987 my $l=$cwd;
988 $l.="/" if length $l;
989 $l.=$link;
991 if (exists $pagesources{$l}) {
992 return $l;
994 elsif (exists $pagecase{lc $l}) {
995 return $pagecase{lc $l};
997 } while $cwd=~s{/?[^/]+$}{};
999 if (length $config{userdir}) {
1000 my $l = "$config{userdir}/".lc($link);
1001 if (exists $pagesources{$l}) {
1002 return $l;
1004 elsif (exists $pagecase{lc $l}) {
1005 return $pagecase{lc $l};
1009 #print STDERR "warning: page $page, broken link: $link\n";
1010 return "";
1013 sub isinlinableimage ($) {
1014 my $file=shift;
1016 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
1019 sub pagetitle ($;$) {
1020 my $page=shift;
1021 my $unescaped=shift;
1023 if ($unescaped) {
1024 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
1026 else {
1027 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
1030 return $page;
1033 sub titlepage ($) {
1034 my $title=shift;
1035 # support use w/o %config set
1036 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1037 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1038 return $title;
1041 sub linkpage ($) {
1042 my $link=shift;
1043 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
1044 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
1045 return $link;
1048 sub cgiurl (@) {
1049 my %params=@_;
1051 my $cgiurl=$local_cgiurl;
1053 if (exists $params{cgiurl}) {
1054 $cgiurl=$params{cgiurl};
1055 delete $params{cgiurl};
1058 unless (%params) {
1059 return $cgiurl;
1062 return $cgiurl."?".
1063 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
1066 sub baseurl (;$) {
1067 my $page=shift;
1069 return $local_url if ! defined $page;
1071 $page=htmlpage($page);
1072 $page=~s/[^\/]+$//;
1073 $page=~s/[^\/]+\//..\//g;
1074 return $page;
1077 sub urlabs ($$) {
1078 my $url=shift;
1079 my $urlbase=shift;
1081 return $url unless defined $urlbase && length $urlbase;
1083 eval q{use URI};
1084 URI->new_abs($url, $urlbase)->as_string;
1087 sub abs2rel ($$) {
1088 # Work around very innefficient behavior in File::Spec if abs2rel
1089 # is passed two relative paths. It's much faster if paths are
1090 # absolute! (Debian bug #376658; fixed in debian unstable now)
1091 my $path="/".shift;
1092 my $base="/".shift;
1094 require File::Spec;
1095 my $ret=File::Spec->abs2rel($path, $base);
1096 $ret=~s/^// if defined $ret;
1097 return $ret;
1100 sub displaytime ($;$$) {
1101 # Plugins can override this function to mark up the time to
1102 # display.
1103 my $time=formattime($_[0], $_[1]);
1104 if ($config{html5}) {
1105 return '<time datetime="'.date_3339($_[0]).'"'.
1106 ($_[2] ? ' pubdate="pubdate"' : '').
1107 '>'.$time.'</time>';
1109 else {
1110 return '<span class="date">'.$time.'</span>';
1114 sub formattime ($;$) {
1115 # Plugins can override this function to format the time.
1116 my $time=shift;
1117 my $format=shift;
1118 if (! defined $format) {
1119 $format=$config{timeformat};
1122 # strftime doesn't know about encodings, so make sure
1123 # its output is properly treated as utf8
1124 return decode_utf8(POSIX::strftime($format, localtime($time)));
1127 sub date_3339 ($) {
1128 my $time=shift;
1130 my $lc_time=POSIX::setlocale(&POSIX::LC_TIME);
1131 POSIX::setlocale(&POSIX::LC_TIME, "C");
1132 my $ret=POSIX::strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($time));
1133 POSIX::setlocale(&POSIX::LC_TIME, $lc_time);
1134 return $ret;
1137 sub beautify_urlpath ($) {
1138 my $url=shift;
1140 # Ensure url is not an empty link, and if necessary,
1141 # add ./ to avoid colon confusion.
1142 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1143 $url="./$url";
1146 if ($config{usedirs}) {
1147 $url =~ s!/index.$config{htmlext}$!/!;
1150 return $url;
1153 sub urlto ($;$$) {
1154 my $to=shift;
1155 my $from=shift;
1156 my $absolute=shift;
1158 if (! length $to) {
1159 $to = 'index';
1162 if (! $destsources{$to}) {
1163 $to=htmlpage($to);
1166 if ($absolute) {
1167 return $config{url}.beautify_urlpath("/".$to);
1170 if (! defined $from) {
1171 my $u = $local_url;
1172 $u =~ s{/$}{};
1173 return $u.beautify_urlpath("/".$to);
1176 my $link = abs2rel($to, dirname(htmlpage($from)));
1178 return beautify_urlpath($link);
1181 sub isselflink ($$) {
1182 # Plugins can override this function to support special types
1183 # of selflinks.
1184 my $page=shift;
1185 my $link=shift;
1187 return $page eq $link;
1190 sub htmllink ($$$;@) {
1191 my $lpage=shift; # the page doing the linking
1192 my $page=shift; # the page that will contain the link (different for inline)
1193 my $link=shift;
1194 my %opts=@_;
1196 $link=~s/\/$//;
1198 my $bestlink;
1199 if (! $opts{forcesubpage}) {
1200 $bestlink=bestlink($lpage, $link);
1202 else {
1203 $bestlink="$lpage/".lc($link);
1206 my $linktext;
1207 if (defined $opts{linktext}) {
1208 $linktext=$opts{linktext};
1210 else {
1211 $linktext=pagetitle(basename($link));
1214 return "<span class=\"selflink\">$linktext</span>"
1215 if length $bestlink && isselflink($page, $bestlink) &&
1216 ! defined $opts{anchor};
1218 if (! $destsources{$bestlink}) {
1219 $bestlink=htmlpage($bestlink);
1221 if (! $destsources{$bestlink}) {
1222 my $cgilink = "";
1223 if (length $config{cgiurl}) {
1224 $cgilink = "<a href=\"".
1225 cgiurl(
1226 do => "create",
1227 page => lc($link),
1228 from => $lpage
1229 )."\" rel=\"nofollow\">?</a>";
1231 return "<span class=\"createlink\">$cgilink$linktext</span>"
1235 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1236 $bestlink=beautify_urlpath($bestlink);
1238 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1239 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1242 if (defined $opts{anchor}) {
1243 $bestlink.="#".$opts{anchor};
1246 my @attrs;
1247 foreach my $attr (qw{rel class title}) {
1248 if (defined $opts{$attr}) {
1249 push @attrs, " $attr=\"$opts{$attr}\"";
1253 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1256 sub userpage ($) {
1257 my $user=shift;
1258 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1261 sub openiduser ($) {
1262 my $user=shift;
1264 if (defined $user && $user =~ m!^https?://! &&
1265 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1266 my $display;
1268 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1269 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1271 else {
1272 # backcompat with old version
1273 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1274 $display=$oid->display;
1277 # Convert "user.somehost.com" to "user [somehost.com]"
1278 # (also "user.somehost.co.uk")
1279 if ($display !~ /\[/) {
1280 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1282 # Convert "http://somehost.com/user" to "user [somehost.com]".
1283 # (also "https://somehost.com/user/")
1284 if ($display !~ /\[/) {
1285 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1287 $display=~s!^https?://!!; # make sure this is removed
1288 eval q{use CGI 'escapeHTML'};
1289 error($@) if $@;
1290 return escapeHTML($display);
1292 return;
1295 sub htmlize ($$$$) {
1296 my $page=shift;
1297 my $destpage=shift;
1298 my $type=shift;
1299 my $content=shift;
1301 my $oneline = $content !~ /\n/;
1303 if (exists $hooks{htmlize}{$type}) {
1304 $content=$hooks{htmlize}{$type}{call}->(
1305 page => $page,
1306 content => $content,
1309 else {
1310 error("htmlization of $type not supported");
1313 run_hooks(sanitize => sub {
1314 $content=shift->(
1315 page => $page,
1316 destpage => $destpage,
1317 content => $content,
1321 if ($oneline) {
1322 # hack to get rid of enclosing junk added by markdown
1323 # and other htmlizers/sanitizers
1324 $content=~s/^<p>//i;
1325 $content=~s/<\/p>\n*$//i;
1328 return $content;
1331 sub linkify ($$$) {
1332 my $page=shift;
1333 my $destpage=shift;
1334 my $content=shift;
1336 run_hooks(linkify => sub {
1337 $content=shift->(
1338 page => $page,
1339 destpage => $destpage,
1340 content => $content,
1344 return $content;
1347 our %preprocessing;
1348 our $preprocess_preview=0;
1349 sub preprocess ($$$;$$) {
1350 my $page=shift; # the page the data comes from
1351 my $destpage=shift; # the page the data will appear in (different for inline)
1352 my $content=shift;
1353 my $scan=shift;
1354 my $preview=shift;
1356 # Using local because it needs to be set within any nested calls
1357 # of this function.
1358 local $preprocess_preview=$preview if defined $preview;
1360 my $handle=sub {
1361 my $escape=shift;
1362 my $prefix=shift;
1363 my $command=shift;
1364 my $params=shift;
1365 $params="" if ! defined $params;
1367 if (length $escape) {
1368 return "[[$prefix$command $params]]";
1370 elsif (exists $hooks{preprocess}{$command}) {
1371 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1372 # Note: preserve order of params, some plugins may
1373 # consider it significant.
1374 my @params;
1375 while ($params =~ m{
1376 (?:([-\w]+)=)? # 1: named parameter key?
1378 """(.*?)""" # 2: triple-quoted value
1380 "([^"]*?)" # 3: single-quoted value
1382 (\S+) # 4: unquoted value
1384 (?:\s+|$) # delimiter to next param
1385 }sgx) {
1386 my $key=$1;
1387 my $val;
1388 if (defined $2) {
1389 $val=$2;
1390 $val=~s/\r\n/\n/mg;
1391 $val=~s/^\n+//g;
1392 $val=~s/\n+$//g;
1394 elsif (defined $3) {
1395 $val=$3;
1397 elsif (defined $4) {
1398 $val=$4;
1401 if (defined $key) {
1402 push @params, $key, $val;
1404 else {
1405 push @params, $val, '';
1408 if ($preprocessing{$page}++ > 3) {
1409 # Avoid loops of preprocessed pages preprocessing
1410 # other pages that preprocess them, etc.
1411 return "[[!$command <span class=\"error\">".
1412 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1413 $page, $preprocessing{$page}).
1414 "</span>]]";
1416 my $ret;
1417 if (! $scan) {
1418 $ret=eval {
1419 $hooks{preprocess}{$command}{call}->(
1420 @params,
1421 page => $page,
1422 destpage => $destpage,
1423 preview => $preprocess_preview,
1426 if ($@) {
1427 my $error=$@;
1428 chomp $error;
1429 $ret="[[!$command <span class=\"error\">".
1430 gettext("Error").": $error"."</span>]]";
1433 else {
1434 # use void context during scan pass
1435 eval {
1436 $hooks{preprocess}{$command}{call}->(
1437 @params,
1438 page => $page,
1439 destpage => $destpage,
1440 preview => $preprocess_preview,
1443 $ret="";
1445 $preprocessing{$page}--;
1446 return $ret;
1448 else {
1449 return "[[$prefix$command $params]]";
1453 my $regex;
1454 if ($config{prefix_directives}) {
1455 $regex = qr{
1456 (\\?) # 1: escape?
1457 \[\[(!) # directive open; 2: prefix
1458 ([-\w]+) # 3: command
1459 ( # 4: the parameters..
1460 \s+ # Must have space if parameters present
1462 (?:[-\w]+=)? # named parameter key?
1464 """.*?""" # triple-quoted value
1466 "[^"]*?" # single-quoted value
1468 [^"\s\]]+ # unquoted value
1470 \s* # whitespace or end
1471 # of directive
1473 *)? # 0 or more parameters
1474 \]\] # directive closed
1475 }sx;
1477 else {
1478 $regex = qr{
1479 (\\?) # 1: escape?
1480 \[\[(!?) # directive open; 2: optional prefix
1481 ([-\w]+) # 3: command
1483 ( # 4: the parameters..
1485 (?:[-\w]+=)? # named parameter key?
1487 """.*?""" # triple-quoted value
1489 "[^"]*?" # single-quoted value
1491 [^"\s\]]+ # unquoted value
1493 \s* # whitespace or end
1494 # of directive
1496 *) # 0 or more parameters
1497 \]\] # directive closed
1498 }sx;
1501 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1502 return $content;
1505 sub filter ($$$) {
1506 my $page=shift;
1507 my $destpage=shift;
1508 my $content=shift;
1510 run_hooks(filter => sub {
1511 $content=shift->(page => $page, destpage => $destpage,
1512 content => $content);
1515 return $content;
1518 sub check_canedit ($$$;$) {
1519 my $page=shift;
1520 my $q=shift;
1521 my $session=shift;
1522 my $nonfatal=shift;
1524 my $canedit;
1525 run_hooks(canedit => sub {
1526 return if defined $canedit;
1527 my $ret=shift->($page, $q, $session);
1528 if (defined $ret) {
1529 if ($ret eq "") {
1530 $canedit=1;
1532 elsif (ref $ret eq 'CODE') {
1533 $ret->() unless $nonfatal;
1534 $canedit=0;
1536 elsif (defined $ret) {
1537 error($ret) unless $nonfatal;
1538 $canedit=0;
1542 return defined $canedit ? $canedit : 1;
1545 sub check_content (@) {
1546 my %params=@_;
1548 return 1 if ! exists $hooks{checkcontent}; # optimisation
1550 if (exists $pagesources{$params{page}}) {
1551 my @diff;
1552 my %old=map { $_ => 1 }
1553 split("\n", readfile(srcfile($pagesources{$params{page}})));
1554 foreach my $line (split("\n", $params{content})) {
1555 push @diff, $line if ! exists $old{$line};
1557 $params{diff}=join("\n", @diff);
1560 my $ok;
1561 run_hooks(checkcontent => sub {
1562 return if defined $ok;
1563 my $ret=shift->(%params);
1564 if (defined $ret) {
1565 if ($ret eq "") {
1566 $ok=1;
1568 elsif (ref $ret eq 'CODE') {
1569 $ret->() unless $params{nonfatal};
1570 $ok=0;
1572 elsif (defined $ret) {
1573 error($ret) unless $params{nonfatal};
1574 $ok=0;
1579 return defined $ok ? $ok : 1;
1582 sub check_canchange (@) {
1583 my %params = @_;
1584 my $cgi = $params{cgi};
1585 my $session = $params{session};
1586 my @changes = @{$params{changes}};
1588 my %newfiles;
1589 foreach my $change (@changes) {
1590 # This untaint is safe because we check file_pruned and
1591 # wiki_file_regexp.
1592 my ($file)=$change->{file}=~/$config{wiki_file_regexp}/;
1593 $file=possibly_foolish_untaint($file);
1594 if (! defined $file || ! length $file ||
1595 file_pruned($file)) {
1596 error(gettext("bad file name %s"), $file);
1599 my $type=pagetype($file);
1600 my $page=pagename($file) if defined $type;
1602 if ($change->{action} eq 'add') {
1603 $newfiles{$file}=1;
1606 if ($change->{action} eq 'change' ||
1607 $change->{action} eq 'add') {
1608 if (defined $page) {
1609 check_canedit($page, $cgi, $session);
1610 next;
1612 else {
1613 if (IkiWiki::Plugin::attachment->can("check_canattach")) {
1614 IkiWiki::Plugin::attachment::check_canattach($session, $file, $change->{path});
1615 check_canedit($file, $cgi, $session);
1616 next;
1620 elsif ($change->{action} eq 'remove') {
1621 # check_canremove tests to see if the file is present
1622 # on disk. This will fail when a single commit adds a
1623 # file and then removes it again. Avoid the problem
1624 # by not testing the removal in such pairs of changes.
1625 # (The add is still tested, just to make sure that
1626 # no data is added to the repo that a web edit
1627 # could not add.)
1628 next if $newfiles{$file};
1630 if (IkiWiki::Plugin::remove->can("check_canremove")) {
1631 IkiWiki::Plugin::remove::check_canremove(defined $page ? $page : $file, $cgi, $session);
1632 check_canedit(defined $page ? $page : $file, $cgi, $session);
1633 next;
1636 else {
1637 error "unknown action ".$change->{action};
1640 error sprintf(gettext("you are not allowed to change %s"), $file);
1645 my $wikilock;
1647 sub lockwiki () {
1648 # Take an exclusive lock on the wiki to prevent multiple concurrent
1649 # run issues. The lock will be dropped on program exit.
1650 if (! -d $config{wikistatedir}) {
1651 mkdir($config{wikistatedir});
1653 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1654 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1655 if (! flock($wikilock, 2)) { # LOCK_EX
1656 error("failed to get lock");
1658 return 1;
1661 sub unlockwiki () {
1662 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1663 return close($wikilock) if $wikilock;
1664 return;
1667 my $commitlock;
1669 sub commit_hook_enabled () {
1670 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1671 error("cannot write to $config{wikistatedir}/commitlock: $!");
1672 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1673 close($commitlock) || error("failed closing commitlock: $!");
1674 return 0;
1676 close($commitlock) || error("failed closing commitlock: $!");
1677 return 1;
1680 sub disable_commit_hook () {
1681 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1682 error("cannot write to $config{wikistatedir}/commitlock: $!");
1683 if (! flock($commitlock, 2)) { # LOCK_EX
1684 error("failed to get commit lock");
1686 return 1;
1689 sub enable_commit_hook () {
1690 return close($commitlock) if $commitlock;
1691 return;
1694 sub loadindex () {
1695 %oldrenderedfiles=%pagectime=();
1696 if (! $config{rebuild}) {
1697 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1698 %destsources=%renderedfiles=%pagecase=%pagestate=
1699 %depends_simple=%typedlinks=%oldtypedlinks=();
1701 my $in;
1702 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1703 if (-e "$config{wikistatedir}/index") {
1704 system("ikiwiki-transition", "indexdb", $config{srcdir});
1705 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1707 else {
1708 $config{gettime}=1; # first build
1709 return;
1713 my $index=Storable::fd_retrieve($in);
1714 if (! defined $index) {
1715 return 0;
1718 my $pages;
1719 if (exists $index->{version} && ! ref $index->{version}) {
1720 $pages=$index->{page};
1721 %wikistate=%{$index->{state}};
1722 # Handle plugins that got disabled by loading a new setup.
1723 if (exists $config{setupfile}) {
1724 require IkiWiki::Setup;
1725 IkiWiki::Setup::disabled_plugins(
1726 grep { ! $loaded_plugins{$_} } keys %wikistate);
1729 else {
1730 $pages=$index;
1731 %wikistate=();
1734 foreach my $src (keys %$pages) {
1735 my $d=$pages->{$src};
1736 my $page=pagename($src);
1737 $pagectime{$page}=$d->{ctime};
1738 $pagesources{$page}=$src;
1739 if (! $config{rebuild}) {
1740 $pagemtime{$page}=$d->{mtime};
1741 $renderedfiles{$page}=$d->{dest};
1742 if (exists $d->{links} && ref $d->{links}) {
1743 $links{$page}=$d->{links};
1744 $oldlinks{$page}=[@{$d->{links}}];
1746 if (ref $d->{depends_simple} eq 'ARRAY') {
1747 # old format
1748 $depends_simple{$page}={
1749 map { $_ => 1 } @{$d->{depends_simple}}
1752 elsif (exists $d->{depends_simple}) {
1753 $depends_simple{$page}=$d->{depends_simple};
1755 if (exists $d->{dependslist}) {
1756 # old format
1757 $depends{$page}={
1758 map { $_ => $DEPEND_CONTENT }
1759 @{$d->{dependslist}}
1762 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1763 # old format
1764 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1766 elsif (exists $d->{depends}) {
1767 $depends{$page}=$d->{depends};
1769 if (exists $d->{state}) {
1770 $pagestate{$page}=$d->{state};
1772 if (exists $d->{typedlinks}) {
1773 $typedlinks{$page}=$d->{typedlinks};
1775 while (my ($type, $links) = each %{$typedlinks{$page}}) {
1776 next unless %$links;
1777 $oldtypedlinks{$page}{$type} = {%$links};
1781 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1783 foreach my $page (keys %pagesources) {
1784 $pagecase{lc $page}=$page;
1786 foreach my $page (keys %renderedfiles) {
1787 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1789 return close($in);
1792 sub saveindex () {
1793 run_hooks(savestate => sub { shift->() });
1795 my @plugins=keys %loaded_plugins;
1797 if (! -d $config{wikistatedir}) {
1798 mkdir($config{wikistatedir});
1800 my $newfile="$config{wikistatedir}/indexdb.new";
1801 my $cleanup = sub { unlink($newfile) };
1802 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1804 my %index;
1805 foreach my $page (keys %pagemtime) {
1806 next unless $pagemtime{$page};
1807 my $src=$pagesources{$page};
1809 $index{page}{$src}={
1810 ctime => $pagectime{$page},
1811 mtime => $pagemtime{$page},
1812 dest => $renderedfiles{$page},
1813 links => $links{$page},
1816 if (exists $depends{$page}) {
1817 $index{page}{$src}{depends} = $depends{$page};
1820 if (exists $depends_simple{$page}) {
1821 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1824 if (exists $typedlinks{$page} && %{$typedlinks{$page}}) {
1825 $index{page}{$src}{typedlinks} = $typedlinks{$page};
1828 if (exists $pagestate{$page}) {
1829 foreach my $id (@plugins) {
1830 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1831 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1837 $index{state}={};
1838 foreach my $id (@plugins) {
1839 $index{state}{$id}={}; # used to detect disabled plugins
1840 foreach my $key (keys %{$wikistate{$id}}) {
1841 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1845 $index{version}="3";
1846 my $ret=Storable::nstore_fd(\%index, $out);
1847 return if ! defined $ret || ! $ret;
1848 close $out || error("failed saving to $newfile: $!", $cleanup);
1849 rename($newfile, "$config{wikistatedir}/indexdb") ||
1850 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1852 return 1;
1855 sub template_file ($) {
1856 my $name=shift;
1858 my $tpage=($name =~ s/^\///) ? $name : "templates/$name";
1859 my $template;
1860 if ($name !~ /\.tmpl$/ && exists $pagesources{$tpage}) {
1861 $template=srcfile($pagesources{$tpage}, 1);
1862 $name.=".tmpl";
1864 else {
1865 $template=srcfile($tpage, 1);
1868 if (defined $template) {
1869 return $template, $tpage, 1 if wantarray;
1870 return $template;
1872 else {
1873 $name=~s:/::; # avoid path traversal
1874 foreach my $dir ($config{templatedir},
1875 "$installdir/share/ikiwiki/templates") {
1876 if (-e "$dir/$name") {
1877 $template="$dir/$name";
1878 last;
1881 if (defined $template) {
1882 return $template, $tpage if wantarray;
1883 return $template;
1887 return;
1890 sub template_depends ($$;@) {
1891 my $name=shift;
1892 my $page=shift;
1894 my ($filename, $tpage, $untrusted)=template_file($name);
1895 if (! defined $filename) {
1896 error(sprintf(gettext("template %s not found"), $name))
1899 if (defined $page && defined $tpage) {
1900 add_depends($page, $tpage);
1903 my @opts=(
1904 filter => sub {
1905 my $text_ref = shift;
1906 ${$text_ref} = decode_utf8(${$text_ref});
1908 loop_context_vars => 1,
1909 die_on_bad_params => 0,
1910 parent_global_vars => 1,
1911 filename => $filename,
1913 ($untrusted ? (no_includes => 1) : ()),
1915 return @opts if wantarray;
1917 require HTML::Template;
1918 return HTML::Template->new(@opts);
1921 sub template ($;@) {
1922 template_depends(shift, undef, @_);
1925 sub templateactions ($$) {
1926 my $template=shift;
1927 my $page=shift;
1929 my $have_actions=0;
1930 my @actions;
1931 run_hooks(pageactions => sub {
1932 push @actions, map { { action => $_ } }
1933 grep { defined } shift->(page => $page);
1935 $template->param(actions => \@actions);
1937 if ($config{cgiurl} && exists $hooks{auth}) {
1938 $template->param(prefsurl => cgiurl(do => "prefs"));
1939 $have_actions=1;
1942 if ($have_actions || @actions) {
1943 $template->param(have_actions => 1);
1947 sub hook (@) {
1948 my %param=@_;
1950 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1951 error 'hook requires type, call, and id parameters';
1954 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1956 $hooks{$param{type}}{$param{id}}=\%param;
1957 return 1;
1960 sub run_hooks ($$) {
1961 # Calls the given sub for each hook of the given type,
1962 # passing it the hook function to call.
1963 my $type=shift;
1964 my $sub=shift;
1966 if (exists $hooks{$type}) {
1967 my (@first, @middle, @last);
1968 foreach my $id (keys %{$hooks{$type}}) {
1969 if ($hooks{$type}{$id}{first}) {
1970 push @first, $id;
1972 elsif ($hooks{$type}{$id}{last}) {
1973 push @last, $id;
1975 else {
1976 push @middle, $id;
1979 foreach my $id (@first, @middle, @last) {
1980 $sub->($hooks{$type}{$id}{call});
1984 return 1;
1987 sub rcs_update () {
1988 $hooks{rcs}{rcs_update}{call}->(@_);
1991 sub rcs_prepedit ($) {
1992 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1995 sub rcs_commit (@) {
1996 $hooks{rcs}{rcs_commit}{call}->(@_);
1999 sub rcs_commit_staged (@) {
2000 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
2003 sub rcs_add ($) {
2004 $hooks{rcs}{rcs_add}{call}->(@_);
2007 sub rcs_remove ($) {
2008 $hooks{rcs}{rcs_remove}{call}->(@_);
2011 sub rcs_rename ($$) {
2012 $hooks{rcs}{rcs_rename}{call}->(@_);
2015 sub rcs_recentchanges ($) {
2016 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
2019 sub rcs_diff ($;$) {
2020 $hooks{rcs}{rcs_diff}{call}->(@_);
2023 sub rcs_getctime ($) {
2024 $hooks{rcs}{rcs_getctime}{call}->(@_);
2027 sub rcs_getmtime ($) {
2028 $hooks{rcs}{rcs_getmtime}{call}->(@_);
2031 sub rcs_receive () {
2032 $hooks{rcs}{rcs_receive}{call}->();
2035 sub add_depends ($$;$) {
2036 my $page=shift;
2037 my $pagespec=shift;
2038 my $deptype=shift || $DEPEND_CONTENT;
2040 # Is the pagespec a simple page name?
2041 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
2042 $pagespec !~ /[\s*?()!]/) {
2043 $depends_simple{$page}{lc $pagespec} |= $deptype;
2044 return 1;
2047 # Add explicit dependencies for influences.
2048 my $sub=pagespec_translate($pagespec);
2049 return unless defined $sub;
2050 foreach my $p (keys %pagesources) {
2051 my $r=$sub->($p, location => $page);
2052 my $i=$r->influences;
2053 my $static=$r->influences_static;
2054 foreach my $k (keys %$i) {
2055 next unless $r || $static || $k eq $page;
2056 $depends_simple{$page}{lc $k} |= $i->{$k};
2058 last if $static;
2061 $depends{$page}{$pagespec} |= $deptype;
2062 return 1;
2065 sub deptype (@) {
2066 my $deptype=0;
2067 foreach my $type (@_) {
2068 if ($type eq 'presence') {
2069 $deptype |= $DEPEND_PRESENCE;
2071 elsif ($type eq 'links') {
2072 $deptype |= $DEPEND_LINKS;
2074 elsif ($type eq 'content') {
2075 $deptype |= $DEPEND_CONTENT;
2078 return $deptype;
2081 my $file_prune_regexp;
2082 sub file_pruned ($) {
2083 my $file=shift;
2085 if (defined $config{include} && length $config{include}) {
2086 return 0 if $file =~ m/$config{include}/;
2089 if (! defined $file_prune_regexp) {
2090 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
2091 $file_prune_regexp=qr/$file_prune_regexp/;
2093 return $file =~ m/$file_prune_regexp/;
2096 sub define_gettext () {
2097 # If translation is needed, redefine the gettext function to do it.
2098 # Otherwise, it becomes a quick no-op.
2099 my $gettext_obj;
2100 my $getobj;
2101 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
2102 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
2103 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
2104 $getobj=sub {
2105 $gettext_obj=eval q{
2106 use Locale::gettext q{textdomain};
2107 Locale::gettext->domain('ikiwiki')
2112 no warnings 'redefine';
2113 *gettext=sub {
2114 $getobj->() if $getobj;
2115 if ($gettext_obj) {
2116 $gettext_obj->get(shift);
2118 else {
2119 return shift;
2122 *ngettext=sub {
2123 $getobj->() if $getobj;
2124 if ($gettext_obj) {
2125 $gettext_obj->nget(@_);
2127 else {
2128 return ($_[2] == 1 ? $_[0] : $_[1])
2133 sub gettext {
2134 define_gettext();
2135 gettext(@_);
2138 sub ngettext {
2139 define_gettext();
2140 ngettext(@_);
2143 sub yesno ($) {
2144 my $val=shift;
2146 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
2149 sub inject {
2150 # Injects a new function into the symbol table to replace an
2151 # exported function.
2152 my %params=@_;
2154 # This is deep ugly perl foo, beware.
2155 no strict;
2156 no warnings;
2157 if (! defined $params{parent}) {
2158 $params{parent}='::';
2159 $params{old}=\&{$params{name}};
2160 $params{name}=~s/.*:://;
2162 my $parent=$params{parent};
2163 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
2164 $ns = $params{parent} . $ns;
2165 inject(%params, parent => $ns) unless $ns eq '::main::';
2166 *{$ns . $params{name}} = $params{call}
2167 if exists ${$ns}{$params{name}} &&
2168 \&{${$ns}{$params{name}}} == $params{old};
2170 use strict;
2171 use warnings;
2174 sub add_link ($$;$) {
2175 my $page=shift;
2176 my $link=shift;
2177 my $type=shift;
2179 push @{$links{$page}}, $link
2180 unless grep { $_ eq $link } @{$links{$page}};
2182 if (defined $type) {
2183 $typedlinks{$page}{$type}{$link} = 1;
2187 sub add_autofile ($$$) {
2188 my $file=shift;
2189 my $plugin=shift;
2190 my $generator=shift;
2192 $autofiles{$file}{plugin}=$plugin;
2193 $autofiles{$file}{generator}=$generator;
2196 sub sortspec_translate ($$) {
2197 my $spec = shift;
2198 my $reverse = shift;
2200 my $code = "";
2201 my @data;
2202 while ($spec =~ m{
2204 (-?) # group 1: perhaps negated
2206 ( # group 2: a word
2207 \w+\([^\)]*\) # command(params)
2209 [^\s]+ # or anything else
2212 }gx) {
2213 my $negated = $1;
2214 my $word = $2;
2215 my $params = undef;
2217 if ($word =~ m/^(\w+)\((.*)\)$/) {
2218 # command with parameters
2219 $params = $2;
2220 $word = $1;
2222 elsif ($word !~ m/^\w+$/) {
2223 error(sprintf(gettext("invalid sort type %s"), $word));
2226 if (length $code) {
2227 $code .= " || ";
2230 if ($negated) {
2231 $code .= "-";
2234 if (exists $IkiWiki::SortSpec::{"cmp_$word"}) {
2235 if (defined $params) {
2236 push @data, $params;
2237 $code .= "IkiWiki::SortSpec::cmp_$word(\$data[$#data])";
2239 else {
2240 $code .= "IkiWiki::SortSpec::cmp_$word(undef)";
2243 else {
2244 error(sprintf(gettext("unknown sort type %s"), $word));
2248 if (! length $code) {
2249 # undefined sorting method... sort arbitrarily
2250 return sub { 0 };
2253 if ($reverse) {
2254 $code="-($code)";
2257 no warnings;
2258 return eval 'sub { '.$code.' }';
2261 sub pagespec_translate ($) {
2262 my $spec=shift;
2264 # Convert spec to perl code.
2265 my $code="";
2266 my @data;
2267 while ($spec=~m{
2268 \s* # ignore whitespace
2269 ( # 1: match a single word
2270 \! # !
2272 \( # (
2274 \) # )
2276 \w+\([^\)]*\) # command(params)
2278 [^\s()]+ # any other text
2280 \s* # ignore whitespace
2281 }gx) {
2282 my $word=$1;
2283 if (lc $word eq 'and') {
2284 $code.=' &';
2286 elsif (lc $word eq 'or') {
2287 $code.=' |';
2289 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
2290 $code.=' '.$word;
2292 elsif ($word =~ /^(\w+)\((.*)\)$/) {
2293 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
2294 push @data, $2;
2295 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
2297 else {
2298 push @data, qq{unknown function in pagespec "$word"};
2299 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
2302 else {
2303 push @data, $word;
2304 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
2308 if (! length $code) {
2309 $code="IkiWiki::FailReason->new('empty pagespec')";
2312 no warnings;
2313 return eval 'sub { my $page=shift; '.$code.' }';
2316 sub pagespec_match ($$;@) {
2317 my $page=shift;
2318 my $spec=shift;
2319 my @params=@_;
2321 # Backwards compatability with old calling convention.
2322 if (@params == 1) {
2323 unshift @params, 'location';
2326 my $sub=pagespec_translate($spec);
2327 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2328 if ! defined $sub;
2329 return $sub->($page, @params);
2332 sub pagespec_match_list ($$;@) {
2333 my $page=shift;
2334 my $pagespec=shift;
2335 my %params=@_;
2337 # Backwards compatability with old calling convention.
2338 if (ref $page) {
2339 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2340 $params{list}=$page;
2341 $page=$params{location}; # ugh!
2344 my $sub=pagespec_translate($pagespec);
2345 error "syntax error in pagespec \"$pagespec\""
2346 if ! defined $sub;
2347 my $sort=sortspec_translate($params{sort}, $params{reverse})
2348 if defined $params{sort};
2350 my @candidates;
2351 if (exists $params{list}) {
2352 @candidates=exists $params{filter}
2353 ? grep { ! $params{filter}->($_) } @{$params{list}}
2354 : @{$params{list}};
2356 else {
2357 @candidates=exists $params{filter}
2358 ? grep { ! $params{filter}->($_) } keys %pagesources
2359 : keys %pagesources;
2362 # clear params, remainder is passed to pagespec
2363 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2364 my $num=$params{num};
2365 delete @params{qw{num deptype reverse sort filter list}};
2367 # when only the top matches will be returned, it's efficient to
2368 # sort before matching to pagespec,
2369 if (defined $num && defined $sort) {
2370 @candidates=IkiWiki::SortSpec::sort_pages(
2371 $sort, @candidates);
2374 my @matches;
2375 my $firstfail;
2376 my $count=0;
2377 my $accum=IkiWiki::SuccessReason->new();
2378 foreach my $p (@candidates) {
2379 my $r=$sub->($p, %params, location => $page);
2380 error(sprintf(gettext("cannot match pages: %s"), $r))
2381 if $r->isa("IkiWiki::ErrorReason");
2382 unless ($r || $r->influences_static) {
2383 $r->remove_influence($p);
2385 $accum |= $r;
2386 if ($r) {
2387 push @matches, $p;
2388 last if defined $num && ++$count == $num;
2392 # Add simple dependencies for accumulated influences.
2393 my $i=$accum->influences;
2394 foreach my $k (keys %$i) {
2395 $depends_simple{$page}{lc $k} |= $i->{$k};
2398 # when all matches will be returned, it's efficient to
2399 # sort after matching
2400 if (! defined $num && defined $sort) {
2401 return IkiWiki::SortSpec::sort_pages(
2402 $sort, @matches);
2404 else {
2405 return @matches;
2409 sub pagespec_valid ($) {
2410 my $spec=shift;
2412 return defined pagespec_translate($spec);
2415 sub glob2re ($) {
2416 my $re=quotemeta(shift);
2417 $re=~s/\\\*/.*/g;
2418 $re=~s/\\\?/./g;
2419 return qr/^$re$/i;
2422 package IkiWiki::FailReason;
2424 use overload (
2425 '""' => sub { $_[0][0] },
2426 '0+' => sub { 0 },
2427 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2428 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2429 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2430 fallback => 1,
2433 our @ISA = 'IkiWiki::SuccessReason';
2435 package IkiWiki::SuccessReason;
2437 use overload (
2438 '""' => sub { $_[0][0] },
2439 '0+' => sub { 1 },
2440 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2441 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2442 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2443 fallback => 1,
2446 sub new {
2447 my $class = shift;
2448 my $value = shift;
2449 return bless [$value, {@_}], $class;
2452 sub influences {
2453 my $this=shift;
2454 $this->[1]={@_} if @_;
2455 my %i=%{$this->[1]};
2456 delete $i{""};
2457 return \%i;
2460 sub influences_static {
2461 return ! $_[0][1]->{""};
2464 sub merge_influences {
2465 my $this=shift;
2466 my $other=shift;
2467 my $anded=shift;
2469 if (! $anded || (($this || %{$this->[1]}) &&
2470 ($other || %{$other->[1]}))) {
2471 foreach my $influence (keys %{$other->[1]}) {
2472 $this->[1]{$influence} |= $other->[1]{$influence};
2475 else {
2476 # influence blocker
2477 $this->[1]={};
2481 sub remove_influence {
2482 my $this=shift;
2483 my $torm=shift;
2485 delete $this->[1]{$torm};
2488 package IkiWiki::ErrorReason;
2490 our @ISA = 'IkiWiki::FailReason';
2492 package IkiWiki::PageSpec;
2494 sub derel ($$) {
2495 my $path=shift;
2496 my $from=shift;
2498 if ($path =~ m!^\.(/|$)!) {
2499 if ($1) {
2500 $from=~s#/?[^/]+$## if defined $from;
2501 $path=~s#^\./##;
2502 $path="$from/$path" if defined $from && length $from;
2504 else {
2505 $path = $from;
2506 $path = "" unless defined $path;
2510 return $path;
2513 my %glob_cache;
2515 sub match_glob ($$;@) {
2516 my $page=shift;
2517 my $glob=shift;
2518 my %params=@_;
2520 $glob=derel($glob, $params{location});
2522 # Instead of converting the glob to a regex every time,
2523 # cache the compiled regex to save time.
2524 my $re=$glob_cache{$glob};
2525 unless (defined $re) {
2526 $glob_cache{$glob} = $re = IkiWiki::glob2re($glob);
2528 if ($page =~ $re) {
2529 if (! IkiWiki::isinternal($page) || $params{internal}) {
2530 return IkiWiki::SuccessReason->new("$glob matches $page");
2532 else {
2533 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2536 else {
2537 return IkiWiki::FailReason->new("$glob does not match $page");
2541 sub match_internal ($$;@) {
2542 return match_glob(shift, shift, @_, internal => 1)
2545 sub match_page ($$;@) {
2546 my $page=shift;
2547 my $match=match_glob($page, shift, @_);
2548 if ($match) {
2549 my $source=exists $IkiWiki::pagesources{$page} ?
2550 $IkiWiki::pagesources{$page} :
2551 $IkiWiki::delpagesources{$page};
2552 my $type=defined $source ? IkiWiki::pagetype($source) : undef;
2553 if (! defined $type) {
2554 return IkiWiki::FailReason->new("$page is not a page");
2557 return $match;
2560 sub match_link ($$;@) {
2561 my $page=shift;
2562 my $link=lc(shift);
2563 my %params=@_;
2565 $link=derel($link, $params{location});
2566 my $from=exists $params{location} ? $params{location} : '';
2567 my $linktype=$params{linktype};
2568 my $qualifier='';
2569 if (defined $linktype) {
2570 $qualifier=" with type $linktype";
2573 my $links = $IkiWiki::links{$page};
2574 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2575 unless $links && @{$links};
2576 my $bestlink = IkiWiki::bestlink($from, $link);
2577 foreach my $p (@{$links}) {
2578 next unless (! defined $linktype || exists $IkiWiki::typedlinks{$page}{$linktype}{$p});
2580 if (length $bestlink) {
2581 if ($bestlink eq IkiWiki::bestlink($page, $p)) {
2582 return IkiWiki::SuccessReason->new("$page links to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2585 else {
2586 if (match_glob($p, $link, %params)) {
2587 return IkiWiki::SuccessReason->new("$page links to page $p$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2589 my ($p_rel)=$p=~/^\/?(.*)/;
2590 $link=~s/^\///;
2591 if (match_glob($p_rel, $link, %params)) {
2592 return IkiWiki::SuccessReason->new("$page links to page $p_rel$qualifier, matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2596 return IkiWiki::FailReason->new("$page does not link to $link$qualifier", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2599 sub match_backlink ($$;@) {
2600 my $ret=match_link($_[1], $_[0], @_);
2601 $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2602 return $ret;
2605 sub match_created_before ($$;@) {
2606 my $page=shift;
2607 my $testpage=shift;
2608 my %params=@_;
2610 $testpage=derel($testpage, $params{location});
2612 if (exists $IkiWiki::pagectime{$testpage}) {
2613 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2614 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2616 else {
2617 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2620 else {
2621 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2625 sub match_created_after ($$;@) {
2626 my $page=shift;
2627 my $testpage=shift;
2628 my %params=@_;
2630 $testpage=derel($testpage, $params{location});
2632 if (exists $IkiWiki::pagectime{$testpage}) {
2633 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2634 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2636 else {
2637 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2640 else {
2641 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2645 sub match_creation_day ($$;@) {
2646 my $page=shift;
2647 my $d=shift;
2648 if ($d !~ /^\d+$/) {
2649 return IkiWiki::ErrorReason->new("invalid day $d");
2651 if ((localtime($IkiWiki::pagectime{$page}))[3] == $d) {
2652 return IkiWiki::SuccessReason->new('creation_day matched');
2654 else {
2655 return IkiWiki::FailReason->new('creation_day did not match');
2659 sub match_creation_month ($$;@) {
2660 my $page=shift;
2661 my $m=shift;
2662 if ($m !~ /^\d+$/) {
2663 return IkiWiki::ErrorReason->new("invalid month $m");
2665 if ((localtime($IkiWiki::pagectime{$page}))[4] + 1 == $m) {
2666 return IkiWiki::SuccessReason->new('creation_month matched');
2668 else {
2669 return IkiWiki::FailReason->new('creation_month did not match');
2673 sub match_creation_year ($$;@) {
2674 my $page=shift;
2675 my $y=shift;
2676 if ($y !~ /^\d+$/) {
2677 return IkiWiki::ErrorReason->new("invalid year $y");
2679 if ((localtime($IkiWiki::pagectime{$page}))[5] + 1900 == $y) {
2680 return IkiWiki::SuccessReason->new('creation_year matched');
2682 else {
2683 return IkiWiki::FailReason->new('creation_year did not match');
2687 sub match_user ($$;@) {
2688 shift;
2689 my $user=shift;
2690 my %params=@_;
2692 my $regexp=IkiWiki::glob2re($user);
2694 if (! exists $params{user}) {
2695 return IkiWiki::ErrorReason->new("no user specified");
2698 if (defined $params{user} && $params{user}=~$regexp) {
2699 return IkiWiki::SuccessReason->new("user is $user");
2701 elsif (! defined $params{user}) {
2702 return IkiWiki::FailReason->new("not logged in");
2704 else {
2705 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2709 sub match_admin ($$;@) {
2710 shift;
2711 shift;
2712 my %params=@_;
2714 if (! exists $params{user}) {
2715 return IkiWiki::ErrorReason->new("no user specified");
2718 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2719 return IkiWiki::SuccessReason->new("user is an admin");
2721 elsif (! defined $params{user}) {
2722 return IkiWiki::FailReason->new("not logged in");
2724 else {
2725 return IkiWiki::FailReason->new("user is not an admin");
2729 sub match_ip ($$;@) {
2730 shift;
2731 my $ip=shift;
2732 my %params=@_;
2734 if (! exists $params{ip}) {
2735 return IkiWiki::ErrorReason->new("no IP specified");
2738 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2739 return IkiWiki::SuccessReason->new("IP is $ip");
2741 else {
2742 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");
2746 package IkiWiki::SortSpec;
2748 # This is in the SortSpec namespace so that the $a and $b that sort() uses
2749 # are easily available in this namespace, for cmp functions to use them.
2750 sub sort_pages {
2751 my $f=shift;
2752 sort $f @_
2755 sub cmp_title {
2756 IkiWiki::pagetitle(IkiWiki::basename($a))
2758 IkiWiki::pagetitle(IkiWiki::basename($b))
2761 sub cmp_mtime { $IkiWiki::pagemtime{$b} <=> $IkiWiki::pagemtime{$a} }
2762 sub cmp_age { $IkiWiki::pagectime{$b} <=> $IkiWiki::pagectime{$a} }