The GNU Hurd pages have long been converted to ikiwiki.
[ikiwiki.git] / IkiWiki.pm
blob6233d2eada36e376ccacbc3abe140598cf9004e4
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 %hooks %forcerebuild
17 $gettext_obj %loaded_plugins};
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error template htmlpage add_depends pagespec_match
21 pagespec_match_list bestlink htmllink readfile writefile
22 pagetype srcfile pagename displaytime will_render gettext urlto
23 targetpage add_underlay pagetitle titlepage linkpage
24 newpagefile inject add_link
25 %config %links %pagestate %wikistate %renderedfiles
26 %pagesources %destsources);
27 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
28 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
29 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
31 # Optimisation.
32 use Memoize;
33 memoize("abs2rel");
34 memoize("pagespec_translate");
35 memoize("file_pruned");
37 sub getsetup () {
38 wikiname => {
39 type => "string",
40 default => "wiki",
41 description => "name of the wiki",
42 safe => 1,
43 rebuild => 1,
45 adminemail => {
46 type => "string",
47 default => undef,
48 example => 'me@example.com',
49 description => "contact email for wiki",
50 safe => 1,
51 rebuild => 0,
53 adminuser => {
54 type => "string",
55 default => [],
56 description => "users who are wiki admins",
57 safe => 1,
58 rebuild => 0,
60 banned_users => {
61 type => "string",
62 default => [],
63 description => "users who are banned from the wiki",
64 safe => 1,
65 rebuild => 0,
67 srcdir => {
68 type => "string",
69 default => undef,
70 example => "$ENV{HOME}/wiki",
71 description => "where the source of the wiki is located",
72 safe => 0, # path
73 rebuild => 1,
75 destdir => {
76 type => "string",
77 default => undef,
78 example => "/var/www/wiki",
79 description => "where to build the wiki",
80 safe => 0, # path
81 rebuild => 1,
83 url => {
84 type => "string",
85 default => '',
86 example => "http://example.com/wiki",
87 description => "base url to the wiki",
88 safe => 1,
89 rebuild => 1,
91 cgiurl => {
92 type => "string",
93 default => '',
94 example => "http://example.com/wiki/ikiwiki.cgi",
95 description => "url to the ikiwiki.cgi",
96 safe => 1,
97 rebuild => 1,
99 cgi_wrapper => {
100 type => "string",
101 default => '',
102 example => "/var/www/wiki/ikiwiki.cgi",
103 description => "filename of cgi wrapper to generate",
104 safe => 0, # file
105 rebuild => 0,
107 cgi_wrappermode => {
108 type => "string",
109 default => '06755',
110 description => "mode for cgi_wrapper (can safely be made suid)",
111 safe => 0,
112 rebuild => 0,
114 rcs => {
115 type => "string",
116 default => '',
117 description => "rcs backend to use",
118 safe => 0, # don't allow overriding
119 rebuild => 0,
121 default_plugins => {
122 type => "internal",
123 default => [qw{mdwn link inline meta htmlscrubber passwordauth
124 openid signinedit lockedit conditional
125 recentchanges parentlinks editpage}],
126 description => "plugins to enable by default",
127 safe => 0,
128 rebuild => 1,
130 add_plugins => {
131 type => "string",
132 default => [],
133 description => "plugins to add to the default configuration",
134 safe => 1,
135 rebuild => 1,
137 disable_plugins => {
138 type => "string",
139 default => [],
140 description => "plugins to disable",
141 safe => 1,
142 rebuild => 1,
144 templatedir => {
145 type => "string",
146 default => "$installdir/share/ikiwiki/templates",
147 description => "location of template files",
148 advanced => 1,
149 safe => 0, # path
150 rebuild => 1,
152 underlaydir => {
153 type => "string",
154 default => "$installdir/share/ikiwiki/basewiki",
155 description => "base wiki source location",
156 advanced => 1,
157 safe => 0, # path
158 rebuild => 0,
160 underlaydirbase => {
161 type => "internal",
162 default => "$installdir/share/ikiwiki",
163 description => "parent directory containing additional underlays",
164 safe => 0,
165 rebuild => 0,
167 wrappers => {
168 type => "internal",
169 default => [],
170 description => "wrappers to generate",
171 safe => 0,
172 rebuild => 0,
174 underlaydirs => {
175 type => "internal",
176 default => [],
177 description => "additional underlays to use",
178 safe => 0,
179 rebuild => 0,
181 verbose => {
182 type => "boolean",
183 example => 1,
184 description => "display verbose messages?",
185 safe => 1,
186 rebuild => 0,
188 syslog => {
189 type => "boolean",
190 example => 1,
191 description => "log to syslog?",
192 safe => 1,
193 rebuild => 0,
195 usedirs => {
196 type => "boolean",
197 default => 1,
198 description => "create output files named page/index.html?",
199 safe => 0, # changing requires manual transition
200 rebuild => 1,
202 prefix_directives => {
203 type => "boolean",
204 default => 1,
205 description => "use '!'-prefixed preprocessor directives?",
206 safe => 0, # changing requires manual transition
207 rebuild => 1,
209 indexpages => {
210 type => "boolean",
211 default => 0,
212 description => "use page/index.mdwn source files",
213 safe => 1,
214 rebuild => 1,
216 discussion => {
217 type => "boolean",
218 default => 1,
219 description => "enable Discussion pages?",
220 safe => 1,
221 rebuild => 1,
223 sslcookie => {
224 type => "boolean",
225 default => 0,
226 description => "only send cookies over SSL connections?",
227 advanced => 1,
228 safe => 1,
229 rebuild => 0,
231 default_pageext => {
232 type => "string",
233 default => "mdwn",
234 description => "extension to use for new pages",
235 safe => 0, # not sanitized
236 rebuild => 0,
238 htmlext => {
239 type => "string",
240 default => "html",
241 description => "extension to use for html files",
242 safe => 0, # not sanitized
243 rebuild => 1,
245 timeformat => {
246 type => "string",
247 default => '%c',
248 description => "strftime format string to display date",
249 advanced => 1,
250 safe => 1,
251 rebuild => 1,
253 locale => {
254 type => "string",
255 default => undef,
256 example => "en_US.UTF-8",
257 description => "UTF-8 locale to use",
258 advanced => 1,
259 safe => 0,
260 rebuild => 1,
262 userdir => {
263 type => "string",
264 default => "",
265 example => "users",
266 description => "put user pages below specified page",
267 safe => 1,
268 rebuild => 1,
270 numbacklinks => {
271 type => "integer",
272 default => 10,
273 description => "how many backlinks to show before hiding excess (0 to show all)",
274 safe => 1,
275 rebuild => 1,
277 hardlink => {
278 type => "boolean",
279 default => 0,
280 description => "attempt to hardlink source files? (optimisation for large files)",
281 advanced => 1,
282 safe => 0, # paranoia
283 rebuild => 0,
285 umask => {
286 type => "integer",
287 example => "022",
288 description => "force ikiwiki to use a particular umask",
289 advanced => 1,
290 safe => 0, # paranoia
291 rebuild => 0,
293 wrappergroup => {
294 type => "string",
295 example => "ikiwiki",
296 description => "group for wrappers to run in",
297 advanced => 1,
298 safe => 0, # paranoia
299 rebuild => 0,
301 libdir => {
302 type => "string",
303 default => "",
304 example => "$ENV{HOME}/.ikiwiki/",
305 description => "extra library and plugin directory",
306 advanced => 1,
307 safe => 0, # directory
308 rebuild => 0,
310 ENV => {
311 type => "string",
312 default => {},
313 description => "environment variables",
314 safe => 0, # paranoia
315 rebuild => 0,
317 exclude => {
318 type => "string",
319 default => undef,
320 example => '\.wav$',
321 description => "regexp of source files to ignore",
322 advanced => 1,
323 safe => 0, # regexp
324 rebuild => 1,
326 wiki_file_prune_regexps => {
327 type => "internal",
328 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
329 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
330 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
331 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
332 qr/\.dpkg-tmp$/],
333 description => "regexps of source files to ignore",
334 safe => 0,
335 rebuild => 1,
337 wiki_file_chars => {
338 type => "string",
339 description => "specifies the characters that are allowed in source filenames",
340 default => "-[:alnum:]+/.:_",
341 safe => 0,
342 rebuild => 1,
344 wiki_file_regexp => {
345 type => "internal",
346 description => "regexp of legal source files",
347 safe => 0,
348 rebuild => 1,
350 web_commit_regexp => {
351 type => "internal",
352 default => qr/^web commit (by (.*?(?=: |$))|from (\d+\.\d+\.\d+\.\d+)):?(.*)/,
353 description => "regexp to parse web commits from logs",
354 safe => 0,
355 rebuild => 0,
357 cgi => {
358 type => "internal",
359 default => 0,
360 description => "run as a cgi",
361 safe => 0,
362 rebuild => 0,
364 cgi_disable_uploads => {
365 type => "internal",
366 default => 1,
367 description => "whether CGI should accept file uploads",
368 safe => 0,
369 rebuild => 0,
371 post_commit => {
372 type => "internal",
373 default => 0,
374 description => "run as a post-commit hook",
375 safe => 0,
376 rebuild => 0,
378 rebuild => {
379 type => "internal",
380 default => 0,
381 description => "running in rebuild mode",
382 safe => 0,
383 rebuild => 0,
385 setup => {
386 type => "internal",
387 default => undef,
388 description => "running in setup mode",
389 safe => 0,
390 rebuild => 0,
392 refresh => {
393 type => "internal",
394 default => 0,
395 description => "running in refresh mode",
396 safe => 0,
397 rebuild => 0,
399 test_receive => {
400 type => "internal",
401 default => 0,
402 description => "running in receive test mode",
403 safe => 0,
404 rebuild => 0,
406 getctime => {
407 type => "internal",
408 default => 0,
409 description => "running in getctime mode",
410 safe => 0,
411 rebuild => 0,
413 w3mmode => {
414 type => "internal",
415 default => 0,
416 description => "running in w3mmode",
417 safe => 0,
418 rebuild => 0,
420 wikistatedir => {
421 type => "internal",
422 default => undef,
423 description => "path to the .ikiwiki directory holding ikiwiki state",
424 safe => 0,
425 rebuild => 0,
427 setupfile => {
428 type => "internal",
429 default => undef,
430 description => "path to setup file",
431 safe => 0,
432 rebuild => 0,
434 allow_symlinks_before_srcdir => {
435 type => "boolean",
436 default => 0,
437 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
438 safe => 0,
439 rebuild => 0,
443 sub defaultconfig () {
444 my %s=getsetup();
445 my @ret;
446 foreach my $key (keys %s) {
447 push @ret, $key, $s{$key}->{default};
449 use Data::Dumper;
450 return @ret;
453 sub checkconfig () {
454 # locale stuff; avoid LC_ALL since it overrides everything
455 if (defined $ENV{LC_ALL}) {
456 $ENV{LANG} = $ENV{LC_ALL};
457 delete $ENV{LC_ALL};
459 if (defined $config{locale}) {
460 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
461 $ENV{LANG}=$config{locale};
462 $gettext_obj=undef;
466 if (! defined $config{wiki_file_regexp}) {
467 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
470 if (ref $config{ENV} eq 'HASH') {
471 foreach my $val (keys %{$config{ENV}}) {
472 $ENV{$val}=$config{ENV}{$val};
476 if ($config{w3mmode}) {
477 eval q{use Cwd q{abs_path}};
478 error($@) if $@;
479 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
480 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
481 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
482 unless $config{cgiurl} =~ m!file:///!;
483 $config{url}="file://".$config{destdir};
486 if ($config{cgi} && ! length $config{url}) {
487 error(gettext("Must specify url to wiki with --url when using --cgi"));
490 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
491 unless exists $config{wikistatedir} && defined $config{wikistatedir};
493 if (defined $config{umask}) {
494 umask(possibly_foolish_untaint($config{umask}));
497 run_hooks(checkconfig => sub { shift->() });
499 return 1;
502 sub listplugins () {
503 my %ret;
505 foreach my $dir (@INC, $config{libdir}) {
506 next unless defined $dir && length $dir;
507 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
508 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
509 $ret{$plugin}=1;
512 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
513 next unless defined $dir && length $dir;
514 foreach my $file (glob("$dir/plugins/*")) {
515 $ret{basename($file)}=1 if -x $file;
519 return keys %ret;
522 sub loadplugins () {
523 if (defined $config{libdir} && length $config{libdir}) {
524 unshift @INC, possibly_foolish_untaint($config{libdir});
527 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
528 loadplugin($plugin);
531 if ($config{rcs}) {
532 if (exists $IkiWiki::hooks{rcs}) {
533 error(gettext("cannot use multiple rcs plugins"));
535 loadplugin($config{rcs});
537 if (! exists $IkiWiki::hooks{rcs}) {
538 loadplugin("norcs");
541 run_hooks(getopt => sub { shift->() });
542 if (grep /^-/, @ARGV) {
543 print STDERR "Unknown option (or missing parameter): $_\n"
544 foreach grep /^-/, @ARGV;
545 usage();
548 return 1;
551 sub loadplugin ($) {
552 my $plugin=shift;
554 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
556 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
557 "$installdir/lib/ikiwiki") {
558 if (defined $dir && -x "$dir/plugins/$plugin") {
559 eval { require IkiWiki::Plugin::external };
560 if ($@) {
561 my $reason=$@;
562 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
564 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
565 $loaded_plugins{$plugin}=1;
566 return 1;
570 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
571 eval qq{use $mod};
572 if ($@) {
573 error("Failed to load plugin $mod: $@");
575 $loaded_plugins{$plugin}=1;
576 return 1;
579 sub error ($;$) {
580 my $message=shift;
581 my $cleaner=shift;
582 log_message('err' => $message) if $config{syslog};
583 if (defined $cleaner) {
584 $cleaner->();
586 die $message."\n";
589 sub debug ($) {
590 return unless $config{verbose};
591 return log_message(debug => @_);
594 my $log_open=0;
595 sub log_message ($$) {
596 my $type=shift;
598 if ($config{syslog}) {
599 require Sys::Syslog;
600 if (! $log_open) {
601 Sys::Syslog::setlogsock('unix');
602 Sys::Syslog::openlog('ikiwiki', '', 'user');
603 $log_open=1;
605 return eval {
606 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
609 elsif (! $config{cgi}) {
610 return print "@_\n";
612 else {
613 return print STDERR "@_\n";
617 sub possibly_foolish_untaint ($) {
618 my $tainted=shift;
619 my ($untainted)=$tainted=~/(.*)/s;
620 return $untainted;
623 sub basename ($) {
624 my $file=shift;
626 $file=~s!.*/+!!;
627 return $file;
630 sub dirname ($) {
631 my $file=shift;
633 $file=~s!/*[^/]+$!!;
634 return $file;
637 sub isinternal ($) {
638 my $page=shift;
639 return exists $pagesources{$page} &&
640 $pagesources{$page} =~ /\._([^.]+)$/;
643 sub pagetype ($) {
644 my $file=shift;
646 if ($file =~ /\.([^.]+)$/) {
647 return $1 if exists $hooks{htmlize}{$1};
649 my $base=basename($file);
650 if (exists $hooks{htmlize}{$base} &&
651 $hooks{htmlize}{$base}{noextension}) {
652 return $base;
654 return;
657 sub pagename ($) {
658 my $file=shift;
660 my $type=pagetype($file);
661 my $page=$file;
662 $page=~s/\Q.$type\E*$//
663 if defined $type && !$hooks{htmlize}{$type}{keepextension}
664 && !$hooks{htmlize}{$type}{noextension};
665 if ($config{indexpages} && $page=~/(.*)\/index$/) {
666 $page=$1;
668 return $page;
671 sub newpagefile ($$) {
672 my $page=shift;
673 my $type=shift;
675 if (! $config{indexpages} || $page eq 'index') {
676 return $page.".".$type;
678 else {
679 return $page."/index.".$type;
683 sub targetpage ($$;$) {
684 my $page=shift;
685 my $ext=shift;
686 my $filename=shift;
688 if (defined $filename) {
689 return $page."/".$filename.".".$ext;
691 elsif (! $config{usedirs} || $page eq 'index') {
692 return $page.".".$ext;
694 else {
695 return $page."/index.".$ext;
699 sub htmlpage ($) {
700 my $page=shift;
702 return targetpage($page, $config{htmlext});
705 sub srcfile_stat {
706 my $file=shift;
707 my $nothrow=shift;
709 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
710 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
711 return "$dir/$file", stat(_) if -e "$dir/$file";
713 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
714 return;
717 sub srcfile ($;$) {
718 return (srcfile_stat(@_))[0];
721 sub add_underlay ($) {
722 my $dir=shift;
724 if ($dir !~ /^\//) {
725 $dir="$config{underlaydirbase}/$dir";
728 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
729 unshift @{$config{underlaydirs}}, $dir;
732 return 1;
735 sub readfile ($;$$) {
736 my $file=shift;
737 my $binary=shift;
738 my $wantfd=shift;
740 if (-l $file) {
741 error("cannot read a symlink ($file)");
744 local $/=undef;
745 open (my $in, "<", $file) || error("failed to read $file: $!");
746 binmode($in) if ($binary);
747 return \*$in if $wantfd;
748 my $ret=<$in>;
749 # check for invalid utf-8, and toss it back to avoid crashes
750 if (! utf8::valid($ret)) {
751 $ret=encode_utf8($ret);
753 close $in || error("failed to read $file: $!");
754 return $ret;
757 sub prep_writefile ($$) {
758 my $file=shift;
759 my $destdir=shift;
761 my $test=$file;
762 while (length $test) {
763 if (-l "$destdir/$test") {
764 error("cannot write to a symlink ($test)");
766 $test=dirname($test);
769 my $dir=dirname("$destdir/$file");
770 if (! -d $dir) {
771 my $d="";
772 foreach my $s (split(m!/+!, $dir)) {
773 $d.="$s/";
774 if (! -d $d) {
775 mkdir($d) || error("failed to create directory $d: $!");
780 return 1;
783 sub writefile ($$$;$$) {
784 my $file=shift; # can include subdirs
785 my $destdir=shift; # directory to put file in
786 my $content=shift;
787 my $binary=shift;
788 my $writer=shift;
790 prep_writefile($file, $destdir);
792 my $newfile="$destdir/$file.ikiwiki-new";
793 if (-l $newfile) {
794 error("cannot write to a symlink ($newfile)");
797 my $cleanup = sub { unlink($newfile) };
798 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
799 binmode($out) if ($binary);
800 if ($writer) {
801 $writer->(\*$out, $cleanup);
803 else {
804 print $out $content or error("failed writing to $newfile: $!", $cleanup);
806 close $out || error("failed saving $newfile: $!", $cleanup);
807 rename($newfile, "$destdir/$file") ||
808 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
810 return 1;
813 my %cleared;
814 sub will_render ($$;$) {
815 my $page=shift;
816 my $dest=shift;
817 my $clear=shift;
819 # Important security check.
820 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
821 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
822 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
825 if (! $clear || $cleared{$page}) {
826 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
828 else {
829 foreach my $old (@{$renderedfiles{$page}}) {
830 delete $destsources{$old};
832 $renderedfiles{$page}=[$dest];
833 $cleared{$page}=1;
835 $destsources{$dest}=$page;
837 return 1;
840 sub bestlink ($$) {
841 my $page=shift;
842 my $link=shift;
844 my $cwd=$page;
845 if ($link=~s/^\/+//) {
846 # absolute links
847 $cwd="";
849 $link=~s/\/$//;
851 do {
852 my $l=$cwd;
853 $l.="/" if length $l;
854 $l.=$link;
856 if (exists $links{$l}) {
857 return $l;
859 elsif (exists $pagecase{lc $l}) {
860 return $pagecase{lc $l};
862 } while $cwd=~s{/?[^/]+$}{};
864 if (length $config{userdir}) {
865 my $l = "$config{userdir}/".lc($link);
866 if (exists $links{$l}) {
867 return $l;
869 elsif (exists $pagecase{lc $l}) {
870 return $pagecase{lc $l};
874 #print STDERR "warning: page $page, broken link: $link\n";
875 return "";
878 sub isinlinableimage ($) {
879 my $file=shift;
881 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
884 sub pagetitle ($;$) {
885 my $page=shift;
886 my $unescaped=shift;
888 if ($unescaped) {
889 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
891 else {
892 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
895 return $page;
898 sub titlepage ($) {
899 my $title=shift;
900 # support use w/o %config set
901 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
902 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
903 return $title;
906 sub linkpage ($) {
907 my $link=shift;
908 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
909 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
910 return $link;
913 sub cgiurl (@) {
914 my %params=@_;
916 return $config{cgiurl}."?".
917 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
920 sub baseurl (;$) {
921 my $page=shift;
923 return "$config{url}/" if ! defined $page;
925 $page=htmlpage($page);
926 $page=~s/[^\/]+$//;
927 $page=~s/[^\/]+\//..\//g;
928 return $page;
931 sub abs2rel ($$) {
932 # Work around very innefficient behavior in File::Spec if abs2rel
933 # is passed two relative paths. It's much faster if paths are
934 # absolute! (Debian bug #376658; fixed in debian unstable now)
935 my $path="/".shift;
936 my $base="/".shift;
938 require File::Spec;
939 my $ret=File::Spec->abs2rel($path, $base);
940 $ret=~s/^// if defined $ret;
941 return $ret;
944 sub displaytime ($;$) {
945 # Plugins can override this function to mark up the time to
946 # display.
947 return '<span class="date">'.formattime(@_).'</span>';
950 sub formattime ($;$) {
951 # Plugins can override this function to format the time.
952 my $time=shift;
953 my $format=shift;
954 if (! defined $format) {
955 $format=$config{timeformat};
958 # strftime doesn't know about encodings, so make sure
959 # its output is properly treated as utf8
960 return decode_utf8(POSIX::strftime($format, localtime($time)));
963 sub beautify_urlpath ($) {
964 my $url=shift;
966 # Ensure url is not an empty link, and if necessary,
967 # add ./ to avoid colon confusion.
968 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
969 $url="./$url";
972 if ($config{usedirs}) {
973 $url =~ s!/index.$config{htmlext}$!/!;
976 return $url;
979 sub urlto ($$;$) {
980 my $to=shift;
981 my $from=shift;
982 my $absolute=shift;
984 if (! length $to) {
985 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
988 if (! $destsources{$to}) {
989 $to=htmlpage($to);
992 if ($absolute) {
993 return $config{url}.beautify_urlpath("/".$to);
996 my $link = abs2rel($to, dirname(htmlpage($from)));
998 return beautify_urlpath($link);
1001 sub htmllink ($$$;@) {
1002 my $lpage=shift; # the page doing the linking
1003 my $page=shift; # the page that will contain the link (different for inline)
1004 my $link=shift;
1005 my %opts=@_;
1007 $link=~s/\/$//;
1009 my $bestlink;
1010 if (! $opts{forcesubpage}) {
1011 $bestlink=bestlink($lpage, $link);
1013 else {
1014 $bestlink="$lpage/".lc($link);
1017 my $linktext;
1018 if (defined $opts{linktext}) {
1019 $linktext=$opts{linktext};
1021 else {
1022 $linktext=pagetitle(basename($link));
1025 return "<span class=\"selflink\">$linktext</span>"
1026 if length $bestlink && $page eq $bestlink &&
1027 ! defined $opts{anchor};
1029 if (! $destsources{$bestlink}) {
1030 $bestlink=htmlpage($bestlink);
1032 if (! $destsources{$bestlink}) {
1033 return $linktext unless length $config{cgiurl};
1034 return "<span class=\"createlink\"><a href=\"".
1035 cgiurl(
1036 do => "create",
1037 page => lc($link),
1038 from => $lpage
1040 "\" rel=\"nofollow\">?</a>$linktext</span>"
1044 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1045 $bestlink=beautify_urlpath($bestlink);
1047 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1048 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1051 if (defined $opts{anchor}) {
1052 $bestlink.="#".$opts{anchor};
1055 my @attrs;
1056 if (defined $opts{rel}) {
1057 push @attrs, ' rel="'.$opts{rel}.'"';
1059 if (defined $opts{class}) {
1060 push @attrs, ' class="'.$opts{class}.'"';
1063 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1066 sub userlink ($) {
1067 my $user=shift;
1069 my $oiduser=eval { openiduser($user) };
1070 if (defined $oiduser) {
1071 return "<a href=\"$user\">$oiduser</a>";
1073 else {
1074 eval q{use CGI 'escapeHTML'};
1075 error($@) if $@;
1077 return htmllink("", "", escapeHTML(
1078 length $config{userdir} ? $config{userdir}."/".$user : $user
1079 ), noimageinline => 1);
1083 sub htmlize ($$$$) {
1084 my $page=shift;
1085 my $destpage=shift;
1086 my $type=shift;
1087 my $content=shift;
1089 my $oneline = $content !~ /\n/;
1091 if (exists $hooks{htmlize}{$type}) {
1092 $content=$hooks{htmlize}{$type}{call}->(
1093 page => $page,
1094 content => $content,
1097 else {
1098 error("htmlization of $type not supported");
1101 run_hooks(sanitize => sub {
1102 $content=shift->(
1103 page => $page,
1104 destpage => $destpage,
1105 content => $content,
1109 if ($oneline) {
1110 # hack to get rid of enclosing junk added by markdown
1111 # and other htmlizers
1112 $content=~s/^<p>//i;
1113 $content=~s/<\/p>$//i;
1114 chomp $content;
1117 return $content;
1120 sub linkify ($$$) {
1121 my $page=shift;
1122 my $destpage=shift;
1123 my $content=shift;
1125 run_hooks(linkify => sub {
1126 $content=shift->(
1127 page => $page,
1128 destpage => $destpage,
1129 content => $content,
1133 return $content;
1136 our %preprocessing;
1137 our $preprocess_preview=0;
1138 sub preprocess ($$$;$$) {
1139 my $page=shift; # the page the data comes from
1140 my $destpage=shift; # the page the data will appear in (different for inline)
1141 my $content=shift;
1142 my $scan=shift;
1143 my $preview=shift;
1145 # Using local because it needs to be set within any nested calls
1146 # of this function.
1147 local $preprocess_preview=$preview if defined $preview;
1149 my $handle=sub {
1150 my $escape=shift;
1151 my $prefix=shift;
1152 my $command=shift;
1153 my $params=shift;
1154 $params="" if ! defined $params;
1156 if (length $escape) {
1157 return "[[$prefix$command $params]]";
1159 elsif (exists $hooks{preprocess}{$command}) {
1160 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1161 # Note: preserve order of params, some plugins may
1162 # consider it significant.
1163 my @params;
1164 while ($params =~ m{
1165 (?:([-\w]+)=)? # 1: named parameter key?
1167 """(.*?)""" # 2: triple-quoted value
1169 "([^"]+)" # 3: single-quoted value
1171 (\S+) # 4: unquoted value
1173 (?:\s+|$) # delimiter to next param
1174 }sgx) {
1175 my $key=$1;
1176 my $val;
1177 if (defined $2) {
1178 $val=$2;
1179 $val=~s/\r\n/\n/mg;
1180 $val=~s/^\n+//g;
1181 $val=~s/\n+$//g;
1183 elsif (defined $3) {
1184 $val=$3;
1186 elsif (defined $4) {
1187 $val=$4;
1190 if (defined $key) {
1191 push @params, $key, $val;
1193 else {
1194 push @params, $val, '';
1197 if ($preprocessing{$page}++ > 3) {
1198 # Avoid loops of preprocessed pages preprocessing
1199 # other pages that preprocess them, etc.
1200 return "[[!$command <span class=\"error\">".
1201 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1202 $page, $preprocessing{$page}).
1203 "</span>]]";
1205 my $ret;
1206 if (! $scan) {
1207 $ret=eval {
1208 $hooks{preprocess}{$command}{call}->(
1209 @params,
1210 page => $page,
1211 destpage => $destpage,
1212 preview => $preprocess_preview,
1215 if ($@) {
1216 chomp $@;
1217 $ret="[[!$command <span class=\"error\">".
1218 gettext("Error").": $@"."</span>]]";
1221 else {
1222 # use void context during scan pass
1223 eval {
1224 $hooks{preprocess}{$command}{call}->(
1225 @params,
1226 page => $page,
1227 destpage => $destpage,
1228 preview => $preprocess_preview,
1231 $ret="";
1233 $preprocessing{$page}--;
1234 return $ret;
1236 else {
1237 return "[[$prefix$command $params]]";
1241 my $regex;
1242 if ($config{prefix_directives}) {
1243 $regex = qr{
1244 (\\?) # 1: escape?
1245 \[\[(!) # directive open; 2: prefix
1246 ([-\w]+) # 3: command
1247 ( # 4: the parameters..
1248 \s+ # Must have space if parameters present
1250 (?:[-\w]+=)? # named parameter key?
1252 """.*?""" # triple-quoted value
1254 "[^"]+" # single-quoted value
1256 [^\s\]]+ # unquoted value
1258 \s* # whitespace or end
1259 # of directive
1261 *)? # 0 or more parameters
1262 \]\] # directive closed
1263 }sx;
1265 else {
1266 $regex = qr{
1267 (\\?) # 1: escape?
1268 \[\[(!?) # directive open; 2: optional prefix
1269 ([-\w]+) # 3: command
1271 ( # 4: the parameters..
1273 (?:[-\w]+=)? # named parameter key?
1275 """.*?""" # triple-quoted value
1277 "[^"]+" # single-quoted value
1279 [^\s\]]+ # unquoted value
1281 \s* # whitespace or end
1282 # of directive
1284 *) # 0 or more parameters
1285 \]\] # directive closed
1286 }sx;
1289 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1290 return $content;
1293 sub filter ($$$) {
1294 my $page=shift;
1295 my $destpage=shift;
1296 my $content=shift;
1298 run_hooks(filter => sub {
1299 $content=shift->(page => $page, destpage => $destpage,
1300 content => $content);
1303 return $content;
1306 sub indexlink () {
1307 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1310 sub check_canedit ($$$;$) {
1311 my $page=shift;
1312 my $q=shift;
1313 my $session=shift;
1314 my $nonfatal=shift;
1316 my $canedit;
1317 run_hooks(canedit => sub {
1318 return if defined $canedit;
1319 my $ret=shift->($page, $q, $session);
1320 if (defined $ret) {
1321 if ($ret eq "") {
1322 $canedit=1;
1324 elsif (ref $ret eq 'CODE') {
1325 $ret->() unless $nonfatal;
1326 $canedit=0;
1328 elsif (defined $ret) {
1329 error($ret) unless $nonfatal;
1330 $canedit=0;
1334 return defined $canedit ? $canedit : 1;
1337 sub check_content (@) {
1338 my %params=@_;
1340 return 1 if ! exists $hooks{checkcontent}; # optimisation
1342 if (exists $pagesources{$params{page}}) {
1343 my @diff;
1344 my %old=map { $_ => 1 }
1345 split("\n", readfile(srcfile($pagesources{$params{page}})));
1346 foreach my $line (split("\n", $params{content})) {
1347 push @diff, $line if ! exists $old{$_};
1349 $params{content}=join("\n", @diff);
1352 my $ok;
1353 run_hooks(checkcontent => sub {
1354 return if defined $ok;
1355 my $ret=shift->(%params);
1356 if (defined $ret) {
1357 if ($ret eq "") {
1358 $ok=1;
1360 elsif (ref $ret eq 'CODE') {
1361 $ret->() unless $params{nonfatal};
1362 $ok=0;
1364 elsif (defined $ret) {
1365 error($ret) unless $params{nonfatal};
1366 $ok=0;
1371 return defined $ok ? $ok : 1;
1374 my $wikilock;
1376 sub lockwiki () {
1377 # Take an exclusive lock on the wiki to prevent multiple concurrent
1378 # run issues. The lock will be dropped on program exit.
1379 if (! -d $config{wikistatedir}) {
1380 mkdir($config{wikistatedir});
1382 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1383 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1384 if (! flock($wikilock, 2)) { # LOCK_EX
1385 error("failed to get lock");
1387 return 1;
1390 sub unlockwiki () {
1391 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1392 return close($wikilock) if $wikilock;
1393 return;
1396 my $commitlock;
1398 sub commit_hook_enabled () {
1399 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1400 error("cannot write to $config{wikistatedir}/commitlock: $!");
1401 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1402 close($commitlock) || error("failed closing commitlock: $!");
1403 return 0;
1405 close($commitlock) || error("failed closing commitlock: $!");
1406 return 1;
1409 sub disable_commit_hook () {
1410 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1411 error("cannot write to $config{wikistatedir}/commitlock: $!");
1412 if (! flock($commitlock, 2)) { # LOCK_EX
1413 error("failed to get commit lock");
1415 return 1;
1418 sub enable_commit_hook () {
1419 return close($commitlock) if $commitlock;
1420 return;
1423 sub loadindex () {
1424 %oldrenderedfiles=%pagectime=();
1425 if (! $config{rebuild}) {
1426 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1427 %destsources=%renderedfiles=%pagecase=%pagestate=();
1429 my $in;
1430 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1431 if (-e "$config{wikistatedir}/index") {
1432 system("ikiwiki-transition", "indexdb", $config{srcdir});
1433 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1435 else {
1436 return;
1440 my $index=Storable::fd_retrieve($in);
1441 if (! defined $index) {
1442 return 0;
1445 my $pages;
1446 if (exists $index->{version} && ! ref $index->{version}) {
1447 $pages=$index->{page};
1448 %wikistate=%{$index->{state}};
1450 else {
1451 $pages=$index;
1452 %wikistate=();
1455 foreach my $src (keys %$pages) {
1456 my $d=$pages->{$src};
1457 my $page=pagename($src);
1458 $pagectime{$page}=$d->{ctime};
1459 if (! $config{rebuild}) {
1460 $pagesources{$page}=$src;
1461 $pagemtime{$page}=$d->{mtime};
1462 $renderedfiles{$page}=$d->{dest};
1463 if (exists $d->{links} && ref $d->{links}) {
1464 $links{$page}=$d->{links};
1465 $oldlinks{$page}=[@{$d->{links}}];
1467 if (exists $d->{depends}) {
1468 $depends{$page}=$d->{depends};
1470 if (exists $d->{state}) {
1471 $pagestate{$page}=$d->{state};
1474 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1476 foreach my $page (keys %pagesources) {
1477 $pagecase{lc $page}=$page;
1479 foreach my $page (keys %renderedfiles) {
1480 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1482 return close($in);
1485 sub saveindex () {
1486 run_hooks(savestate => sub { shift->() });
1488 my %hookids;
1489 foreach my $type (keys %hooks) {
1490 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1492 my @hookids=keys %hookids;
1494 if (! -d $config{wikistatedir}) {
1495 mkdir($config{wikistatedir});
1497 my $newfile="$config{wikistatedir}/indexdb.new";
1498 my $cleanup = sub { unlink($newfile) };
1499 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1501 my %index;
1502 foreach my $page (keys %pagemtime) {
1503 next unless $pagemtime{$page};
1504 my $src=$pagesources{$page};
1506 $index{page}{$src}={
1507 ctime => $pagectime{$page},
1508 mtime => $pagemtime{$page},
1509 dest => $renderedfiles{$page},
1510 links => $links{$page},
1513 if (exists $depends{$page}) {
1514 $index{page}{$src}{depends} = $depends{$page};
1517 if (exists $pagestate{$page}) {
1518 foreach my $id (@hookids) {
1519 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1520 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1526 $index{state}={};
1527 foreach my $id (@hookids) {
1528 foreach my $key (keys %{$wikistate{$id}}) {
1529 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1533 $index{version}="3";
1534 my $ret=Storable::nstore_fd(\%index, $out);
1535 return if ! defined $ret || ! $ret;
1536 close $out || error("failed saving to $newfile: $!", $cleanup);
1537 rename($newfile, "$config{wikistatedir}/indexdb") ||
1538 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1540 return 1;
1543 sub template_file ($) {
1544 my $template=shift;
1546 foreach my $dir ($config{templatedir}, "$installdir/share/ikiwiki/templates") {
1547 return "$dir/$template" if -e "$dir/$template";
1549 return;
1552 sub template_params (@) {
1553 my $filename=template_file(shift);
1555 if (! defined $filename) {
1556 return if wantarray;
1557 return "";
1560 my @ret=(
1561 filter => sub {
1562 my $text_ref = shift;
1563 ${$text_ref} = decode_utf8(${$text_ref});
1565 filename => $filename,
1566 loop_context_vars => 1,
1567 die_on_bad_params => 0,
1570 return wantarray ? @ret : {@ret};
1573 sub template ($;@) {
1574 require HTML::Template;
1575 return HTML::Template->new(template_params(@_));
1578 sub misctemplate ($$;@) {
1579 my $title=shift;
1580 my $pagebody=shift;
1582 my $template=template("misc.tmpl");
1583 $template->param(
1584 title => $title,
1585 indexlink => indexlink(),
1586 wikiname => $config{wikiname},
1587 pagebody => $pagebody,
1588 baseurl => baseurl(),
1591 run_hooks(pagetemplate => sub {
1592 shift->(page => "", destpage => "", template => $template);
1594 return $template->output;
1597 sub hook (@) {
1598 my %param=@_;
1600 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1601 error 'hook requires type, call, and id parameters';
1604 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1606 $hooks{$param{type}}{$param{id}}=\%param;
1607 return 1;
1610 sub run_hooks ($$) {
1611 # Calls the given sub for each hook of the given type,
1612 # passing it the hook function to call.
1613 my $type=shift;
1614 my $sub=shift;
1616 if (exists $hooks{$type}) {
1617 my (@first, @middle, @last);
1618 foreach my $id (keys %{$hooks{$type}}) {
1619 if ($hooks{$type}{$id}{first}) {
1620 push @first, $id;
1622 elsif ($hooks{$type}{$id}{last}) {
1623 push @last, $id;
1625 else {
1626 push @middle, $id;
1629 foreach my $id (@first, @middle, @last) {
1630 $sub->($hooks{$type}{$id}{call});
1634 return 1;
1637 sub rcs_update () {
1638 $hooks{rcs}{rcs_update}{call}->(@_);
1641 sub rcs_prepedit ($) {
1642 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1645 sub rcs_commit ($$$;$$) {
1646 $hooks{rcs}{rcs_commit}{call}->(@_);
1649 sub rcs_commit_staged ($$$) {
1650 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1653 sub rcs_add ($) {
1654 $hooks{rcs}{rcs_add}{call}->(@_);
1657 sub rcs_remove ($) {
1658 $hooks{rcs}{rcs_remove}{call}->(@_);
1661 sub rcs_rename ($$) {
1662 $hooks{rcs}{rcs_rename}{call}->(@_);
1665 sub rcs_recentchanges ($) {
1666 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1669 sub rcs_diff ($) {
1670 $hooks{rcs}{rcs_diff}{call}->(@_);
1673 sub rcs_getctime ($) {
1674 $hooks{rcs}{rcs_getctime}{call}->(@_);
1677 sub rcs_receive () {
1678 $hooks{rcs}{rcs_receive}{call}->();
1681 sub safequote ($) {
1682 my $s=shift;
1683 $s=~s/[{}]//g;
1684 return "q{$s}";
1687 sub add_depends ($$) {
1688 my $page=shift;
1689 my $pagespec=shift;
1691 return unless pagespec_valid($pagespec);
1693 if (! exists $depends{$page}) {
1694 $depends{$page}=$pagespec;
1696 else {
1697 $depends{$page}=pagespec_merge($depends{$page}, $pagespec);
1700 return 1;
1703 sub file_pruned ($$) {
1704 require File::Spec;
1705 my $file=File::Spec->canonpath(shift);
1706 my $base=File::Spec->canonpath(shift);
1707 $file =~ s#^\Q$base\E/+##;
1709 my $regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1710 return $file =~ m/$regexp/ && $file ne $base;
1713 sub gettext {
1714 # Only use gettext in the rare cases it's needed.
1715 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1716 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1717 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1718 if (! $gettext_obj) {
1719 $gettext_obj=eval q{
1720 use Locale::gettext q{textdomain};
1721 Locale::gettext->domain('ikiwiki')
1723 if ($@) {
1724 print STDERR "$@";
1725 $gettext_obj=undef;
1726 return shift;
1729 return $gettext_obj->get(shift);
1731 else {
1732 return shift;
1736 sub yesno ($) {
1737 my $val=shift;
1739 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1742 sub inject {
1743 # Injects a new function into the symbol table to replace an
1744 # exported function.
1745 my %params=@_;
1747 # This is deep ugly perl foo, beware.
1748 no strict;
1749 no warnings;
1750 if (! defined $params{parent}) {
1751 $params{parent}='::';
1752 $params{old}=\&{$params{name}};
1753 $params{name}=~s/.*:://;
1755 my $parent=$params{parent};
1756 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1757 $ns = $params{parent} . $ns;
1758 inject(%params, parent => $ns) unless $ns eq '::main::';
1759 *{$ns . $params{name}} = $params{call}
1760 if exists ${$ns}{$params{name}} &&
1761 \&{${$ns}{$params{name}}} == $params{old};
1763 use strict;
1764 use warnings;
1767 sub add_link ($$) {
1768 my $page=shift;
1769 my $link=shift;
1771 push @{$links{$page}}, $link
1772 unless grep { $_ eq $link } @{$links{$page}};
1775 sub pagespec_merge ($$) {
1776 my $a=shift;
1777 my $b=shift;
1779 return $a if $a eq $b;
1780 return "($a) or ($b)";
1783 sub pagespec_translate ($) {
1784 my $spec=shift;
1786 # Convert spec to perl code.
1787 my $code="";
1788 while ($spec=~m{
1789 \s* # ignore whitespace
1790 ( # 1: match a single word
1791 \! # !
1793 \( # (
1795 \) # )
1797 \w+\([^\)]*\) # command(params)
1799 [^\s()]+ # any other text
1801 \s* # ignore whitespace
1802 }igx) {
1803 my $word=$1;
1804 if (lc $word eq 'and') {
1805 $code.=' &&';
1807 elsif (lc $word eq 'or') {
1808 $code.=' ||';
1810 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1811 $code.=' '.$word;
1813 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1814 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1815 $code.="IkiWiki::PageSpec::match_$1(\$page, ".safequote($2).", \@_)";
1817 else {
1818 $code.="IkiWiki::ErrorReason->new(".safequote(qq{unknown function in pagespec "$word"}).")";
1821 else {
1822 $code.=" IkiWiki::PageSpec::match_glob(\$page, ".safequote($word).", \@_)";
1826 if (! length $code) {
1827 $code="IkiWiki::FailReason->new('empty pagespec')";
1830 no warnings;
1831 return eval 'sub { my $page=shift; '.$code.' }';
1834 sub pagespec_match ($$;@) {
1835 my $page=shift;
1836 my $spec=shift;
1837 my @params=@_;
1839 # Backwards compatability with old calling convention.
1840 if (@params == 1) {
1841 unshift @params, 'location';
1844 my $sub=pagespec_translate($spec);
1845 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
1846 if $@ || ! defined $sub;
1847 return $sub->($page, @params);
1850 sub pagespec_match_list ($$;@) {
1851 my $pages=shift;
1852 my $spec=shift;
1853 my @params=@_;
1855 my $sub=pagespec_translate($spec);
1856 error "syntax error in pagespec \"$spec\""
1857 if $@ || ! defined $sub;
1859 my @ret;
1860 my $r;
1861 foreach my $page (@$pages) {
1862 $r=$sub->($page, @params);
1863 push @ret, $page if $r;
1866 if (! @ret && defined $r && $r->isa("IkiWiki::ErrorReason")) {
1867 error(sprintf(gettext("cannot match pages: %s"), $r));
1869 else {
1870 return @ret;
1874 sub pagespec_valid ($) {
1875 my $spec=shift;
1877 my $sub=pagespec_translate($spec);
1878 return ! $@;
1881 sub glob2re ($) {
1882 my $re=quotemeta(shift);
1883 $re=~s/\\\*/.*/g;
1884 $re=~s/\\\?/./g;
1885 return $re;
1888 package IkiWiki::FailReason;
1890 use overload (
1891 '""' => sub { ${$_[0]} },
1892 '0+' => sub { 0 },
1893 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
1894 fallback => 1,
1897 sub new {
1898 my $class = shift;
1899 my $value = shift;
1900 return bless \$value, $class;
1903 package IkiWiki::ErrorReason;
1905 our @ISA = 'IkiWiki::FailReason';
1907 package IkiWiki::SuccessReason;
1909 use overload (
1910 '""' => sub { ${$_[0]} },
1911 '0+' => sub { 1 },
1912 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
1913 fallback => 1,
1916 sub new {
1917 my $class = shift;
1918 my $value = shift;
1919 return bless \$value, $class;
1922 package IkiWiki::PageSpec;
1924 sub derel ($$) {
1925 my $path=shift;
1926 my $from=shift;
1928 if ($path =~ m!^\./!) {
1929 $from=~s#/?[^/]+$## if defined $from;
1930 $path=~s#^\./##;
1931 $path="$from/$path" if length $from;
1934 return $path;
1937 sub match_glob ($$;@) {
1938 my $page=shift;
1939 my $glob=shift;
1940 my %params=@_;
1942 $glob=derel($glob, $params{location});
1944 my $regexp=IkiWiki::glob2re($glob);
1945 if ($page=~/^$regexp$/i) {
1946 if (! IkiWiki::isinternal($page) || $params{internal}) {
1947 return IkiWiki::SuccessReason->new("$glob matches $page");
1949 else {
1950 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
1953 else {
1954 return IkiWiki::FailReason->new("$glob does not match $page");
1958 sub match_internal ($$;@) {
1959 return match_glob($_[0], $_[1], @_, internal => 1)
1962 sub match_link ($$;@) {
1963 my $page=shift;
1964 my $link=lc(shift);
1965 my %params=@_;
1967 $link=derel($link, $params{location});
1968 my $from=exists $params{location} ? $params{location} : '';
1970 my $links = $IkiWiki::links{$page};
1971 return IkiWiki::FailReason->new("$page has no links") unless $links && @{$links};
1972 my $bestlink = IkiWiki::bestlink($from, $link);
1973 foreach my $p (@{$links}) {
1974 if (length $bestlink) {
1975 return IkiWiki::SuccessReason->new("$page links to $link")
1976 if $bestlink eq IkiWiki::bestlink($page, $p);
1978 else {
1979 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1980 if match_glob($p, $link, %params);
1981 $p=~s/^\///;
1982 $link=~s/^\///;
1983 return IkiWiki::SuccessReason->new("$page links to page $p matching $link")
1984 if match_glob($p, $link, %params);
1987 return IkiWiki::FailReason->new("$page does not link to $link");
1990 sub match_backlink ($$;@) {
1991 return match_link($_[1], $_[0], @_);
1994 sub match_created_before ($$;@) {
1995 my $page=shift;
1996 my $testpage=shift;
1997 my %params=@_;
1999 $testpage=derel($testpage, $params{location});
2001 if (exists $IkiWiki::pagectime{$testpage}) {
2002 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2003 return IkiWiki::SuccessReason->new("$page created before $testpage");
2005 else {
2006 return IkiWiki::FailReason->new("$page not created before $testpage");
2009 else {
2010 return IkiWiki::FailReason->new("$testpage has no ctime");
2014 sub match_created_after ($$;@) {
2015 my $page=shift;
2016 my $testpage=shift;
2017 my %params=@_;
2019 $testpage=derel($testpage, $params{location});
2021 if (exists $IkiWiki::pagectime{$testpage}) {
2022 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2023 return IkiWiki::SuccessReason->new("$page created after $testpage");
2025 else {
2026 return IkiWiki::FailReason->new("$page not created after $testpage");
2029 else {
2030 return IkiWiki::FailReason->new("$testpage has no ctime");
2034 sub match_creation_day ($$;@) {
2035 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2036 return IkiWiki::SuccessReason->new('creation_day matched');
2038 else {
2039 return IkiWiki::FailReason->new('creation_day did not match');
2043 sub match_creation_month ($$;@) {
2044 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2045 return IkiWiki::SuccessReason->new('creation_month matched');
2047 else {
2048 return IkiWiki::FailReason->new('creation_month did not match');
2052 sub match_creation_year ($$;@) {
2053 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2054 return IkiWiki::SuccessReason->new('creation_year matched');
2056 else {
2057 return IkiWiki::FailReason->new('creation_year did not match');
2061 sub match_user ($$;@) {
2062 shift;
2063 my $user=shift;
2064 my %params=@_;
2066 if (! exists $params{user}) {
2067 return IkiWiki::ErrorReason->new("no user specified");
2070 if (defined $params{user} && lc $params{user} eq lc $user) {
2071 return IkiWiki::SuccessReason->new("user is $user");
2073 elsif (! defined $params{user}) {
2074 return IkiWiki::FailReason->new("not logged in");
2076 else {
2077 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2081 sub match_admin ($$;@) {
2082 shift;
2083 shift;
2084 my %params=@_;
2086 if (! exists $params{user}) {
2087 return IkiWiki::ErrorReason->new("no user specified");
2090 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2091 return IkiWiki::SuccessReason->new("user is an admin");
2093 elsif (! defined $params{user}) {
2094 return IkiWiki::FailReason->new("not logged in");
2096 else {
2097 return IkiWiki::FailReason->new("user is not an admin");
2101 sub match_ip ($$;@) {
2102 shift;
2103 my $ip=shift;
2104 my %params=@_;
2106 if (! exists $params{ip}) {
2107 return IkiWiki::ErrorReason->new("no IP specified");
2110 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2111 return IkiWiki::SuccessReason->new("IP is $ip");
2113 else {
2114 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");