if applied, reverting this would be problematic
[ikiwiki.git] / IkiWiki.pm
blob0cbc847887b1b6d8493268e41721a7f8d8784a32
1 #!/usr/bin/perl
3 package IkiWiki;
5 use warnings;
6 use strict;
7 use Encode;
8 use HTML::Entities;
9 use URI::Escape q{uri_escape_utf8};
10 use POSIX ();
11 use Storable;
12 use open qw{:utf8 :std};
14 use vars qw{%config %links %oldlinks %pagemtime %pagectime %pagecase
15 %pagestate %wikistate %renderedfiles %oldrenderedfiles
16 %pagesources %destsources %depends %depends_simple %hooks
17 %forcerebuild %loaded_plugins};
19 use Exporter q{import};
20 our @EXPORT = qw(hook debug error template htmlpage deptype
21 add_depends pagespec_match pagespec_match_list bestlink
22 htmllink readfile writefile pagetype srcfile pagename
23 displaytime will_render gettext ngettext urlto targetpage
24 add_underlay pagetitle titlepage linkpage newpagefile
25 inject add_link
26 %config %links %pagestate %wikistate %renderedfiles
27 %pagesources %destsources);
28 our $VERSION = 3.00; # plugin interface version, next is ikiwiki version
29 our $version='unknown'; # VERSION_AUTOREPLACE done by Makefile, DNE
30 our $installdir='/usr'; # INSTALLDIR_AUTOREPLACE done by Makefile, DNE
32 # Page dependency types.
33 our $DEPEND_CONTENT=1;
34 our $DEPEND_PRESENCE=2;
35 our $DEPEND_LINKS=4;
37 # Optimisation.
38 use Memoize;
39 memoize("abs2rel");
40 memoize("pagespec_translate");
41 memoize("template_file");
43 sub getsetup () {
44 wikiname => {
45 type => "string",
46 default => "wiki",
47 description => "name of the wiki",
48 safe => 1,
49 rebuild => 1,
51 adminemail => {
52 type => "string",
53 default => undef,
54 example => 'me@example.com',
55 description => "contact email for wiki",
56 safe => 1,
57 rebuild => 0,
59 adminuser => {
60 type => "string",
61 default => [],
62 description => "users who are wiki admins",
63 safe => 1,
64 rebuild => 0,
66 banned_users => {
67 type => "string",
68 default => [],
69 description => "users who are banned from the wiki",
70 safe => 1,
71 rebuild => 0,
73 srcdir => {
74 type => "string",
75 default => undef,
76 example => "$ENV{HOME}/wiki",
77 description => "where the source of the wiki is located",
78 safe => 0, # path
79 rebuild => 1,
81 destdir => {
82 type => "string",
83 default => undef,
84 example => "/var/www/wiki",
85 description => "where to build the wiki",
86 safe => 0, # path
87 rebuild => 1,
89 url => {
90 type => "string",
91 default => '',
92 example => "http://example.com/wiki",
93 description => "base url to the wiki",
94 safe => 1,
95 rebuild => 1,
97 cgiurl => {
98 type => "string",
99 default => '',
100 example => "http://example.com/wiki/ikiwiki.cgi",
101 description => "url to the ikiwiki.cgi",
102 safe => 1,
103 rebuild => 1,
105 cgi_wrapper => {
106 type => "string",
107 default => '',
108 example => "/var/www/wiki/ikiwiki.cgi",
109 description => "filename of cgi wrapper to generate",
110 safe => 0, # file
111 rebuild => 0,
113 cgi_wrappermode => {
114 type => "string",
115 default => '06755',
116 description => "mode for cgi_wrapper (can safely be made suid)",
117 safe => 0,
118 rebuild => 0,
120 rcs => {
121 type => "string",
122 default => '',
123 description => "rcs backend to use",
124 safe => 0, # don't allow overriding
125 rebuild => 0,
127 default_plugins => {
128 type => "internal",
129 default => [qw{mdwn link inline meta htmlscrubber passwordauth
130 openid signinedit lockedit conditional
131 recentchanges parentlinks editpage}],
132 description => "plugins to enable by default",
133 safe => 0,
134 rebuild => 1,
136 add_plugins => {
137 type => "string",
138 default => [],
139 description => "plugins to add to the default configuration",
140 safe => 1,
141 rebuild => 1,
143 disable_plugins => {
144 type => "string",
145 default => [],
146 description => "plugins to disable",
147 safe => 1,
148 rebuild => 1,
150 templatedir => {
151 type => "string",
152 default => "$installdir/share/ikiwiki/templates",
153 description => "location of template files",
154 advanced => 1,
155 safe => 0, # path
156 rebuild => 1,
158 templatedirs => {
159 type => "internal",
160 default => [],
161 description => "additional directories containing template files",
162 safe => 0,
163 rebuild => 0,
165 underlaydir => {
166 type => "string",
167 default => "$installdir/share/ikiwiki/basewiki",
168 description => "base wiki source location",
169 advanced => 1,
170 safe => 0, # path
171 rebuild => 0,
173 underlaydirbase => {
174 type => "internal",
175 default => "$installdir/share/ikiwiki",
176 description => "parent directory containing additional underlays",
177 safe => 0,
178 rebuild => 0,
180 wrappers => {
181 type => "internal",
182 default => [],
183 description => "wrappers to generate",
184 safe => 0,
185 rebuild => 0,
187 underlaydirs => {
188 type => "internal",
189 default => [],
190 description => "additional underlays to use",
191 safe => 0,
192 rebuild => 0,
194 verbose => {
195 type => "boolean",
196 example => 1,
197 description => "display verbose messages?",
198 safe => 1,
199 rebuild => 0,
201 syslog => {
202 type => "boolean",
203 example => 1,
204 description => "log to syslog?",
205 safe => 1,
206 rebuild => 0,
208 usedirs => {
209 type => "boolean",
210 default => 1,
211 description => "create output files named page/index.html?",
212 safe => 0, # changing requires manual transition
213 rebuild => 1,
215 prefix_directives => {
216 type => "boolean",
217 default => 1,
218 description => "use '!'-prefixed preprocessor directives?",
219 safe => 0, # changing requires manual transition
220 rebuild => 1,
222 indexpages => {
223 type => "boolean",
224 default => 0,
225 description => "use page/index.mdwn source files",
226 safe => 1,
227 rebuild => 1,
229 discussion => {
230 type => "boolean",
231 default => 1,
232 description => "enable Discussion pages?",
233 safe => 1,
234 rebuild => 1,
236 discussionpage => {
237 type => "string",
238 default => gettext("Discussion"),
239 description => "name of Discussion pages",
240 safe => 1,
241 rebuild => 1,
243 sslcookie => {
244 type => "boolean",
245 default => 0,
246 description => "only send cookies over SSL connections?",
247 advanced => 1,
248 safe => 1,
249 rebuild => 0,
251 default_pageext => {
252 type => "string",
253 default => "mdwn",
254 description => "extension to use for new pages",
255 safe => 0, # not sanitized
256 rebuild => 0,
258 htmlext => {
259 type => "string",
260 default => "html",
261 description => "extension to use for html files",
262 safe => 0, # not sanitized
263 rebuild => 1,
265 timeformat => {
266 type => "string",
267 default => '%c',
268 description => "strftime format string to display date",
269 advanced => 1,
270 safe => 1,
271 rebuild => 1,
273 locale => {
274 type => "string",
275 default => undef,
276 example => "en_US.UTF-8",
277 description => "UTF-8 locale to use",
278 advanced => 1,
279 safe => 0,
280 rebuild => 1,
282 userdir => {
283 type => "string",
284 default => "",
285 example => "users",
286 description => "put user pages below specified page",
287 safe => 1,
288 rebuild => 1,
290 numbacklinks => {
291 type => "integer",
292 default => 10,
293 description => "how many backlinks to show before hiding excess (0 to show all)",
294 safe => 1,
295 rebuild => 1,
297 hardlink => {
298 type => "boolean",
299 default => 0,
300 description => "attempt to hardlink source files? (optimisation for large files)",
301 advanced => 1,
302 safe => 0, # paranoia
303 rebuild => 0,
305 umask => {
306 type => "integer",
307 example => "022",
308 description => "force ikiwiki to use a particular umask",
309 advanced => 1,
310 safe => 0, # paranoia
311 rebuild => 0,
313 wrappergroup => {
314 type => "string",
315 example => "ikiwiki",
316 description => "group for wrappers to run in",
317 advanced => 1,
318 safe => 0, # paranoia
319 rebuild => 0,
321 libdir => {
322 type => "string",
323 default => "",
324 example => "$ENV{HOME}/.ikiwiki/",
325 description => "extra library and plugin directory",
326 advanced => 1,
327 safe => 0, # directory
328 rebuild => 0,
330 ENV => {
331 type => "string",
332 default => {},
333 description => "environment variables",
334 safe => 0, # paranoia
335 rebuild => 0,
337 include => {
338 type => "string",
339 default => undef,
340 example => '^\.htaccess$',
341 description => "regexp of normally excluded files to include",
342 advanced => 1,
343 safe => 0, # regexp
344 rebuild => 1,
346 exclude => {
347 type => "string",
348 default => undef,
349 example => '^(*\.private|Makefile)$',
350 description => "regexp of files that should be skipped",
351 advanced => 1,
352 safe => 0, # regexp
353 rebuild => 1,
355 wiki_file_prune_regexps => {
356 type => "internal",
357 default => [qr/(^|\/)\.\.(\/|$)/, qr/^\./, qr/\/\./,
358 qr/\.x?html?$/, qr/\.ikiwiki-new$/,
359 qr/(^|\/).svn\//, qr/.arch-ids\//, qr/{arch}\//,
360 qr/(^|\/)_MTN\//, qr/(^|\/)_darcs\//,
361 qr/(^|\/)CVS\//, qr/\.dpkg-tmp$/],
362 description => "regexps of source files to ignore",
363 safe => 0,
364 rebuild => 1,
366 wiki_file_chars => {
367 type => "string",
368 description => "specifies the characters that are allowed in source filenames",
369 default => "-[:alnum:]+/.:_",
370 safe => 0,
371 rebuild => 1,
373 wiki_file_regexp => {
374 type => "internal",
375 description => "regexp of legal source files",
376 safe => 0,
377 rebuild => 1,
379 web_commit_regexp => {
380 type => "internal",
381 default => qr/^web commit (by (.*?(?=: |$))|from ([0-9a-fA-F:.]+[0-9a-fA-F])):?(.*)/,
382 description => "regexp to parse web commits from logs",
383 safe => 0,
384 rebuild => 0,
386 cgi => {
387 type => "internal",
388 default => 0,
389 description => "run as a cgi",
390 safe => 0,
391 rebuild => 0,
393 cgi_disable_uploads => {
394 type => "internal",
395 default => 1,
396 description => "whether CGI should accept file uploads",
397 safe => 0,
398 rebuild => 0,
400 post_commit => {
401 type => "internal",
402 default => 0,
403 description => "run as a post-commit hook",
404 safe => 0,
405 rebuild => 0,
407 rebuild => {
408 type => "internal",
409 default => 0,
410 description => "running in rebuild mode",
411 safe => 0,
412 rebuild => 0,
414 setup => {
415 type => "internal",
416 default => undef,
417 description => "running in setup mode",
418 safe => 0,
419 rebuild => 0,
421 clean => {
422 type => "internal",
423 default => 0,
424 description => "running in clean mode",
425 safe => 0,
426 rebuild => 0,
428 refresh => {
429 type => "internal",
430 default => 0,
431 description => "running in refresh mode",
432 safe => 0,
433 rebuild => 0,
435 test_receive => {
436 type => "internal",
437 default => 0,
438 description => "running in receive test mode",
439 safe => 0,
440 rebuild => 0,
442 getctime => {
443 type => "internal",
444 default => 0,
445 description => "running in getctime mode",
446 safe => 0,
447 rebuild => 0,
449 w3mmode => {
450 type => "internal",
451 default => 0,
452 description => "running in w3mmode",
453 safe => 0,
454 rebuild => 0,
456 wikistatedir => {
457 type => "internal",
458 default => undef,
459 description => "path to the .ikiwiki directory holding ikiwiki state",
460 safe => 0,
461 rebuild => 0,
463 setupfile => {
464 type => "internal",
465 default => undef,
466 description => "path to setup file",
467 safe => 0,
468 rebuild => 0,
470 setuptype => {
471 type => "internal",
472 default => "Standard",
473 description => "perl class to use to dump setup file",
474 safe => 0,
475 rebuild => 0,
477 allow_symlinks_before_srcdir => {
478 type => "boolean",
479 default => 0,
480 description => "allow symlinks in the path leading to the srcdir (potentially insecure)",
481 safe => 0,
482 rebuild => 0,
486 sub defaultconfig () {
487 my %s=getsetup();
488 my @ret;
489 foreach my $key (keys %s) {
490 push @ret, $key, $s{$key}->{default};
492 use Data::Dumper;
493 return @ret;
496 sub checkconfig () {
497 # locale stuff; avoid LC_ALL since it overrides everything
498 if (defined $ENV{LC_ALL}) {
499 $ENV{LANG} = $ENV{LC_ALL};
500 delete $ENV{LC_ALL};
502 if (defined $config{locale}) {
503 if (POSIX::setlocale(&POSIX::LC_ALL, $config{locale})) {
504 $ENV{LANG}=$config{locale};
505 define_gettext();
509 if (! defined $config{wiki_file_regexp}) {
510 $config{wiki_file_regexp}=qr/(^[$config{wiki_file_chars}]+$)/;
513 if (ref $config{ENV} eq 'HASH') {
514 foreach my $val (keys %{$config{ENV}}) {
515 $ENV{$val}=$config{ENV}{$val};
519 if ($config{w3mmode}) {
520 eval q{use Cwd q{abs_path}};
521 error($@) if $@;
522 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
523 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
524 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
525 unless $config{cgiurl} =~ m!file:///!;
526 $config{url}="file://".$config{destdir};
529 if ($config{cgi} && ! length $config{url}) {
530 error(gettext("Must specify url to wiki with --url when using --cgi"));
533 $config{wikistatedir}="$config{srcdir}/.ikiwiki"
534 unless exists $config{wikistatedir} && defined $config{wikistatedir};
536 if (defined $config{umask}) {
537 umask(possibly_foolish_untaint($config{umask}));
540 run_hooks(checkconfig => sub { shift->() });
542 return 1;
545 sub listplugins () {
546 my %ret;
548 foreach my $dir (@INC, $config{libdir}) {
549 next unless defined $dir && length $dir;
550 foreach my $file (glob("$dir/IkiWiki/Plugin/*.pm")) {
551 my ($plugin)=$file=~/.*\/(.*)\.pm$/;
552 $ret{$plugin}=1;
555 foreach my $dir ($config{libdir}, "$installdir/lib/ikiwiki") {
556 next unless defined $dir && length $dir;
557 foreach my $file (glob("$dir/plugins/*")) {
558 $ret{basename($file)}=1 if -x $file;
562 return keys %ret;
565 sub loadplugins () {
566 if (defined $config{libdir} && length $config{libdir}) {
567 unshift @INC, possibly_foolish_untaint($config{libdir});
570 foreach my $plugin (@{$config{default_plugins}}, @{$config{add_plugins}}) {
571 loadplugin($plugin);
574 if ($config{rcs}) {
575 if (exists $hooks{rcs}) {
576 error(gettext("cannot use multiple rcs plugins"));
578 loadplugin($config{rcs});
580 if (! exists $hooks{rcs}) {
581 loadplugin("norcs");
584 run_hooks(getopt => sub { shift->() });
585 if (grep /^-/, @ARGV) {
586 print STDERR "Unknown option (or missing parameter): $_\n"
587 foreach grep /^-/, @ARGV;
588 usage();
591 return 1;
594 sub loadplugin ($) {
595 my $plugin=shift;
597 return if grep { $_ eq $plugin} @{$config{disable_plugins}};
599 foreach my $dir (defined $config{libdir} ? possibly_foolish_untaint($config{libdir}) : undef,
600 "$installdir/lib/ikiwiki") {
601 if (defined $dir && -x "$dir/plugins/$plugin") {
602 eval { require IkiWiki::Plugin::external };
603 if ($@) {
604 my $reason=$@;
605 error(sprintf(gettext("failed to load external plugin needed for %s plugin: %s"), $plugin, $reason));
607 import IkiWiki::Plugin::external "$dir/plugins/$plugin";
608 $loaded_plugins{$plugin}=1;
609 return 1;
613 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
614 eval qq{use $mod};
615 if ($@) {
616 error("Failed to load plugin $mod: $@");
618 $loaded_plugins{$plugin}=1;
619 return 1;
622 sub error ($;$) {
623 my $message=shift;
624 my $cleaner=shift;
625 log_message('err' => $message) if $config{syslog};
626 if (defined $cleaner) {
627 $cleaner->();
629 die $message."\n";
632 sub debug ($) {
633 return unless $config{verbose};
634 return log_message(debug => @_);
637 my $log_open=0;
638 sub log_message ($$) {
639 my $type=shift;
641 if ($config{syslog}) {
642 require Sys::Syslog;
643 if (! $log_open) {
644 Sys::Syslog::setlogsock('unix');
645 Sys::Syslog::openlog('ikiwiki', '', 'user');
646 $log_open=1;
648 return eval {
649 Sys::Syslog::syslog($type, "[$config{wikiname}] %s", join(" ", @_));
652 elsif (! $config{cgi}) {
653 return print "@_\n";
655 else {
656 return print STDERR "@_\n";
660 sub possibly_foolish_untaint ($) {
661 my $tainted=shift;
662 my ($untainted)=$tainted=~/(.*)/s;
663 return $untainted;
666 sub basename ($) {
667 my $file=shift;
669 $file=~s!.*/+!!;
670 return $file;
673 sub dirname ($) {
674 my $file=shift;
676 $file=~s!/*[^/]+$!!;
677 return $file;
680 sub isinternal ($) {
681 my $page=shift;
682 return exists $pagesources{$page} &&
683 $pagesources{$page} =~ /\._([^.]+)$/;
686 sub pagetype ($) {
687 my $file=shift;
689 if ($file =~ /\.([^.]+)$/) {
690 return $1 if exists $hooks{htmlize}{$1};
692 my $base=basename($file);
693 if (exists $hooks{htmlize}{$base} &&
694 $hooks{htmlize}{$base}{noextension}) {
695 return $base;
697 return;
700 my %pagename_cache;
702 sub pagename ($) {
703 my $file=shift;
705 if (exists $pagename_cache{$file}) {
706 return $pagename_cache{$file};
709 my $type=pagetype($file);
710 my $page=$file;
711 $page=~s/\Q.$type\E*$//
712 if defined $type && !$hooks{htmlize}{$type}{keepextension}
713 && !$hooks{htmlize}{$type}{noextension};
714 if ($config{indexpages} && $page=~/(.*)\/index$/) {
715 $page=$1;
718 $pagename_cache{$file} = $page;
719 return $page;
722 sub newpagefile ($$) {
723 my $page=shift;
724 my $type=shift;
726 if (! $config{indexpages} || $page eq 'index') {
727 return $page.".".$type;
729 else {
730 return $page."/index.".$type;
734 sub targetpage ($$;$) {
735 my $page=shift;
736 my $ext=shift;
737 my $filename=shift;
739 if (defined $filename) {
740 return $page."/".$filename.".".$ext;
742 elsif (! $config{usedirs} || $page eq 'index') {
743 return $page.".".$ext;
745 else {
746 return $page."/index.".$ext;
750 sub htmlpage ($) {
751 my $page=shift;
753 return targetpage($page, $config{htmlext});
756 sub srcfile_stat {
757 my $file=shift;
758 my $nothrow=shift;
760 return "$config{srcdir}/$file", stat(_) if -e "$config{srcdir}/$file";
761 foreach my $dir (@{$config{underlaydirs}}, $config{underlaydir}) {
762 return "$dir/$file", stat(_) if -e "$dir/$file";
764 error("internal error: $file cannot be found in $config{srcdir} or underlay") unless $nothrow;
765 return;
768 sub srcfile ($;$) {
769 return (srcfile_stat(@_))[0];
772 sub add_underlay ($) {
773 my $dir=shift;
775 if ($dir !~ /^\//) {
776 $dir="$config{underlaydirbase}/$dir";
779 if (! grep { $_ eq $dir } @{$config{underlaydirs}}) {
780 unshift @{$config{underlaydirs}}, $dir;
783 return 1;
786 sub readfile ($;$$) {
787 my $file=shift;
788 my $binary=shift;
789 my $wantfd=shift;
791 if (-l $file) {
792 error("cannot read a symlink ($file)");
795 local $/=undef;
796 open (my $in, "<", $file) || error("failed to read $file: $!");
797 binmode($in) if ($binary);
798 return \*$in if $wantfd;
799 my $ret=<$in>;
800 # check for invalid utf-8, and toss it back to avoid crashes
801 if (! utf8::valid($ret)) {
802 $ret=encode_utf8($ret);
804 close $in || error("failed to read $file: $!");
805 return $ret;
808 sub prep_writefile ($$) {
809 my $file=shift;
810 my $destdir=shift;
812 my $test=$file;
813 while (length $test) {
814 if (-l "$destdir/$test") {
815 error("cannot write to a symlink ($test)");
817 $test=dirname($test);
820 my $dir=dirname("$destdir/$file");
821 if (! -d $dir) {
822 my $d="";
823 foreach my $s (split(m!/+!, $dir)) {
824 $d.="$s/";
825 if (! -d $d) {
826 mkdir($d) || error("failed to create directory $d: $!");
831 return 1;
834 sub writefile ($$$;$$) {
835 my $file=shift; # can include subdirs
836 my $destdir=shift; # directory to put file in
837 my $content=shift;
838 my $binary=shift;
839 my $writer=shift;
841 prep_writefile($file, $destdir);
843 my $newfile="$destdir/$file.ikiwiki-new";
844 if (-l $newfile) {
845 error("cannot write to a symlink ($newfile)");
848 my $cleanup = sub { unlink($newfile) };
849 open (my $out, '>', $newfile) || error("failed to write $newfile: $!", $cleanup);
850 binmode($out) if ($binary);
851 if ($writer) {
852 $writer->(\*$out, $cleanup);
854 else {
855 print $out $content or error("failed writing to $newfile: $!", $cleanup);
857 close $out || error("failed saving $newfile: $!", $cleanup);
858 rename($newfile, "$destdir/$file") ||
859 error("failed renaming $newfile to $destdir/$file: $!", $cleanup);
861 return 1;
864 my %cleared;
865 sub will_render ($$;$) {
866 my $page=shift;
867 my $dest=shift;
868 my $clear=shift;
870 # Important security check.
871 if (-e "$config{destdir}/$dest" && ! $config{rebuild} &&
872 ! grep { $_ eq $dest } (@{$renderedfiles{$page}}, @{$oldrenderedfiles{$page}}, @{$wikistate{editpage}{previews}})) {
873 error("$config{destdir}/$dest independently created, not overwriting with version from $page");
876 if (! $clear || $cleared{$page}) {
877 $renderedfiles{$page}=[$dest, grep { $_ ne $dest } @{$renderedfiles{$page}}];
879 else {
880 foreach my $old (@{$renderedfiles{$page}}) {
881 delete $destsources{$old};
883 $renderedfiles{$page}=[$dest];
884 $cleared{$page}=1;
886 $destsources{$dest}=$page;
888 return 1;
891 sub bestlink ($$) {
892 my $page=shift;
893 my $link=shift;
895 my $cwd=$page;
896 if ($link=~s/^\/+//) {
897 # absolute links
898 $cwd="";
900 $link=~s/\/$//;
902 do {
903 my $l=$cwd;
904 $l.="/" if length $l;
905 $l.=$link;
907 if (exists $pagesources{$l}) {
908 return $l;
910 elsif (exists $pagecase{lc $l}) {
911 return $pagecase{lc $l};
913 } while $cwd=~s{/?[^/]+$}{};
915 if (length $config{userdir}) {
916 my $l = "$config{userdir}/".lc($link);
917 if (exists $pagesources{$l}) {
918 return $l;
920 elsif (exists $pagecase{lc $l}) {
921 return $pagecase{lc $l};
925 #print STDERR "warning: page $page, broken link: $link\n";
926 return "";
929 sub isinlinableimage ($) {
930 my $file=shift;
932 return $file =~ /\.(png|gif|jpg|jpeg)$/i;
935 sub pagetitle ($;$) {
936 my $page=shift;
937 my $unescaped=shift;
939 if ($unescaped) {
940 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : chr($2)/eg;
942 else {
943 $page=~s/(__(\d+)__|_)/$1 eq '_' ? ' ' : "&#$2;"/eg;
946 return $page;
949 sub titlepage ($) {
950 my $title=shift;
951 # support use w/o %config set
952 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
953 $title=~s/([^$chars]|_)/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
954 return $title;
957 sub linkpage ($) {
958 my $link=shift;
959 my $chars = defined $config{wiki_file_chars} ? $config{wiki_file_chars} : "-[:alnum:]+/.:_";
960 $link=~s/([^$chars])/$1 eq ' ' ? '_' : "__".ord($1)."__"/eg;
961 return $link;
964 sub cgiurl (@) {
965 my %params=@_;
967 my $cgiurl=$config{cgiurl};
968 if (exists $params{cgiurl}) {
969 $cgiurl=$params{cgiurl};
970 delete $params{cgiurl};
972 return $cgiurl."?".
973 join("&amp;", map $_."=".uri_escape_utf8($params{$_}), keys %params);
976 sub baseurl (;$) {
977 my $page=shift;
979 return "$config{url}/" if ! defined $page;
981 $page=htmlpage($page);
982 $page=~s/[^\/]+$//;
983 $page=~s/[^\/]+\//..\//g;
984 return $page;
987 sub abs2rel ($$) {
988 # Work around very innefficient behavior in File::Spec if abs2rel
989 # is passed two relative paths. It's much faster if paths are
990 # absolute! (Debian bug #376658; fixed in debian unstable now)
991 my $path="/".shift;
992 my $base="/".shift;
994 require File::Spec;
995 my $ret=File::Spec->abs2rel($path, $base);
996 $ret=~s/^// if defined $ret;
997 return $ret;
1000 sub displaytime ($;$) {
1001 # Plugins can override this function to mark up the time to
1002 # display.
1003 return '<span class="date">'.formattime(@_).'</span>';
1006 sub formattime ($;$) {
1007 # Plugins can override this function to format the time.
1008 my $time=shift;
1009 my $format=shift;
1010 if (! defined $format) {
1011 $format=$config{timeformat};
1014 # strftime doesn't know about encodings, so make sure
1015 # its output is properly treated as utf8
1016 return decode_utf8(POSIX::strftime($format, localtime($time)));
1019 sub beautify_urlpath ($) {
1020 my $url=shift;
1022 # Ensure url is not an empty link, and if necessary,
1023 # add ./ to avoid colon confusion.
1024 if ($url !~ /^\// && $url !~ /^\.\.?\//) {
1025 $url="./$url";
1028 if ($config{usedirs}) {
1029 $url =~ s!/index.$config{htmlext}$!/!;
1032 return $url;
1035 sub urlto ($$;$) {
1036 my $to=shift;
1037 my $from=shift;
1038 my $absolute=shift;
1040 if (! length $to) {
1041 return beautify_urlpath(baseurl($from)."index.$config{htmlext}");
1044 if (! $destsources{$to}) {
1045 $to=htmlpage($to);
1048 if ($absolute) {
1049 return $config{url}.beautify_urlpath("/".$to);
1052 my $link = abs2rel($to, dirname(htmlpage($from)));
1054 return beautify_urlpath($link);
1057 sub htmllink ($$$;@) {
1058 my $lpage=shift; # the page doing the linking
1059 my $page=shift; # the page that will contain the link (different for inline)
1060 my $link=shift;
1061 my %opts=@_;
1063 $link=~s/\/$//;
1065 my $bestlink;
1066 if (! $opts{forcesubpage}) {
1067 $bestlink=bestlink($lpage, $link);
1069 else {
1070 $bestlink="$lpage/".lc($link);
1073 my $linktext;
1074 if (defined $opts{linktext}) {
1075 $linktext=$opts{linktext};
1077 else {
1078 $linktext=pagetitle(basename($link));
1081 return "<span class=\"selflink\">$linktext</span>"
1082 if length $bestlink && $page eq $bestlink &&
1083 ! defined $opts{anchor};
1085 if (! $destsources{$bestlink}) {
1086 $bestlink=htmlpage($bestlink);
1088 if (! $destsources{$bestlink}) {
1089 return $linktext unless length $config{cgiurl};
1090 return "<span class=\"createlink\"><a href=\"".
1091 cgiurl(
1092 do => "create",
1093 page => lc($link),
1094 from => $lpage
1096 "\" rel=\"nofollow\">?</a>$linktext</span>"
1100 $bestlink=abs2rel($bestlink, dirname(htmlpage($page)));
1101 $bestlink=beautify_urlpath($bestlink);
1103 if (! $opts{noimageinline} && isinlinableimage($bestlink)) {
1104 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
1107 if (defined $opts{anchor}) {
1108 $bestlink.="#".$opts{anchor};
1111 my @attrs;
1112 foreach my $attr (qw{rel class title}) {
1113 if (defined $opts{$attr}) {
1114 push @attrs, " $attr=\"$opts{$attr}\"";
1118 return "<a href=\"$bestlink\"@attrs>$linktext</a>";
1121 sub userpage ($) {
1122 my $user=shift;
1123 return length $config{userdir} ? "$config{userdir}/$user" : $user;
1126 sub openiduser ($) {
1127 my $user=shift;
1129 if ($user =~ m!^https?://! &&
1130 eval q{use Net::OpenID::VerifiedIdentity; 1} && !$@) {
1131 my $display;
1133 if (Net::OpenID::VerifiedIdentity->can("DisplayOfURL")) {
1134 $display = Net::OpenID::VerifiedIdentity::DisplayOfURL($user);
1136 else {
1137 # backcompat with old version
1138 my $oid=Net::OpenID::VerifiedIdentity->new(identity => $user);
1139 $display=$oid->display;
1142 # Convert "user.somehost.com" to "user [somehost.com]"
1143 # (also "user.somehost.co.uk")
1144 if ($display !~ /\[/) {
1145 $display=~s/^([-a-zA-Z0-9]+?)\.([-.a-zA-Z0-9]+\.[a-z]+)$/$1 [$2]/;
1147 # Convert "http://somehost.com/user" to "user [somehost.com]".
1148 # (also "https://somehost.com/user/")
1149 if ($display !~ /\[/) {
1150 $display=~s/^https?:\/\/(.+)\/([^\/#?]+)\/?(?:[#?].*)?$/$2 [$1]/;
1152 $display=~s!^https?://!!; # make sure this is removed
1153 eval q{use CGI 'escapeHTML'};
1154 error($@) if $@;
1155 return escapeHTML($display);
1157 return;
1160 sub htmlize ($$$$) {
1161 my $page=shift;
1162 my $destpage=shift;
1163 my $type=shift;
1164 my $content=shift;
1166 my $oneline = $content !~ /\n/;
1168 if (exists $hooks{htmlize}{$type}) {
1169 $content=$hooks{htmlize}{$type}{call}->(
1170 page => $page,
1171 content => $content,
1174 else {
1175 error("htmlization of $type not supported");
1178 run_hooks(sanitize => sub {
1179 $content=shift->(
1180 page => $page,
1181 destpage => $destpage,
1182 content => $content,
1186 if ($oneline) {
1187 # hack to get rid of enclosing junk added by markdown
1188 # and other htmlizers/sanitizers
1189 $content=~s/^<p>//i;
1190 $content=~s/<\/p>\n*$//i;
1193 return $content;
1196 sub linkify ($$$) {
1197 my $page=shift;
1198 my $destpage=shift;
1199 my $content=shift;
1201 run_hooks(linkify => sub {
1202 $content=shift->(
1203 page => $page,
1204 destpage => $destpage,
1205 content => $content,
1209 return $content;
1212 our %preprocessing;
1213 our $preprocess_preview=0;
1214 sub preprocess ($$$;$$) {
1215 my $page=shift; # the page the data comes from
1216 my $destpage=shift; # the page the data will appear in (different for inline)
1217 my $content=shift;
1218 my $scan=shift;
1219 my $preview=shift;
1221 # Using local because it needs to be set within any nested calls
1222 # of this function.
1223 local $preprocess_preview=$preview if defined $preview;
1225 my $handle=sub {
1226 my $escape=shift;
1227 my $prefix=shift;
1228 my $command=shift;
1229 my $params=shift;
1230 $params="" if ! defined $params;
1232 if (length $escape) {
1233 return "[[$prefix$command $params]]";
1235 elsif (exists $hooks{preprocess}{$command}) {
1236 return "" if $scan && ! $hooks{preprocess}{$command}{scan};
1237 # Note: preserve order of params, some plugins may
1238 # consider it significant.
1239 my @params;
1240 while ($params =~ m{
1241 (?:([-\w]+)=)? # 1: named parameter key?
1243 """(.*?)""" # 2: triple-quoted value
1245 "([^"]*?)" # 3: single-quoted value
1247 (\S+) # 4: unquoted value
1249 (?:\s+|$) # delimiter to next param
1250 }sgx) {
1251 my $key=$1;
1252 my $val;
1253 if (defined $2) {
1254 $val=$2;
1255 $val=~s/\r\n/\n/mg;
1256 $val=~s/^\n+//g;
1257 $val=~s/\n+$//g;
1259 elsif (defined $3) {
1260 $val=$3;
1262 elsif (defined $4) {
1263 $val=$4;
1266 if (defined $key) {
1267 push @params, $key, $val;
1269 else {
1270 push @params, $val, '';
1273 if ($preprocessing{$page}++ > 3) {
1274 # Avoid loops of preprocessed pages preprocessing
1275 # other pages that preprocess them, etc.
1276 return "[[!$command <span class=\"error\">".
1277 sprintf(gettext("preprocessing loop detected on %s at depth %i"),
1278 $page, $preprocessing{$page}).
1279 "</span>]]";
1281 my $ret;
1282 if (! $scan) {
1283 $ret=eval {
1284 $hooks{preprocess}{$command}{call}->(
1285 @params,
1286 page => $page,
1287 destpage => $destpage,
1288 preview => $preprocess_preview,
1291 if ($@) {
1292 my $error=$@;
1293 chomp $error;
1294 $ret="[[!$command <span class=\"error\">".
1295 gettext("Error").": $error"."</span>]]";
1298 else {
1299 # use void context during scan pass
1300 eval {
1301 $hooks{preprocess}{$command}{call}->(
1302 @params,
1303 page => $page,
1304 destpage => $destpage,
1305 preview => $preprocess_preview,
1308 $ret="";
1310 $preprocessing{$page}--;
1311 return $ret;
1313 else {
1314 return "[[$prefix$command $params]]";
1318 my $regex;
1319 if ($config{prefix_directives}) {
1320 $regex = qr{
1321 (\\?) # 1: escape?
1322 \[\[(!) # directive open; 2: prefix
1323 ([-\w]+) # 3: command
1324 ( # 4: the parameters..
1325 \s+ # Must have space if parameters present
1327 (?:[-\w]+=)? # named parameter key?
1329 """.*?""" # triple-quoted value
1331 "[^"]*?" # single-quoted value
1333 [^"\s\]]+ # unquoted value
1335 \s* # whitespace or end
1336 # of directive
1338 *)? # 0 or more parameters
1339 \]\] # directive closed
1340 }sx;
1342 else {
1343 $regex = qr{
1344 (\\?) # 1: escape?
1345 \[\[(!?) # directive open; 2: optional prefix
1346 ([-\w]+) # 3: command
1348 ( # 4: the parameters..
1350 (?:[-\w]+=)? # named parameter key?
1352 """.*?""" # triple-quoted value
1354 "[^"]*?" # single-quoted value
1356 [^"\s\]]+ # unquoted value
1358 \s* # whitespace or end
1359 # of directive
1361 *) # 0 or more parameters
1362 \]\] # directive closed
1363 }sx;
1366 $content =~ s{$regex}{$handle->($1, $2, $3, $4)}eg;
1367 return $content;
1370 sub filter ($$$) {
1371 my $page=shift;
1372 my $destpage=shift;
1373 my $content=shift;
1375 run_hooks(filter => sub {
1376 $content=shift->(page => $page, destpage => $destpage,
1377 content => $content);
1380 return $content;
1383 sub indexlink () {
1384 return "<a href=\"$config{url}\">$config{wikiname}</a>";
1387 sub check_canedit ($$$;$) {
1388 my $page=shift;
1389 my $q=shift;
1390 my $session=shift;
1391 my $nonfatal=shift;
1393 my $canedit;
1394 run_hooks(canedit => sub {
1395 return if defined $canedit;
1396 my $ret=shift->($page, $q, $session);
1397 if (defined $ret) {
1398 if ($ret eq "") {
1399 $canedit=1;
1401 elsif (ref $ret eq 'CODE') {
1402 $ret->() unless $nonfatal;
1403 $canedit=0;
1405 elsif (defined $ret) {
1406 error($ret) unless $nonfatal;
1407 $canedit=0;
1411 return defined $canedit ? $canedit : 1;
1414 sub check_content (@) {
1415 my %params=@_;
1417 return 1 if ! exists $hooks{checkcontent}; # optimisation
1419 if (exists $pagesources{$params{page}}) {
1420 my @diff;
1421 my %old=map { $_ => 1 }
1422 split("\n", readfile(srcfile($pagesources{$params{page}})));
1423 foreach my $line (split("\n", $params{content})) {
1424 push @diff, $line if ! exists $old{$line};
1426 $params{diff}=join("\n", @diff);
1429 my $ok;
1430 run_hooks(checkcontent => sub {
1431 return if defined $ok;
1432 my $ret=shift->(%params);
1433 if (defined $ret) {
1434 if ($ret eq "") {
1435 $ok=1;
1437 elsif (ref $ret eq 'CODE') {
1438 $ret->() unless $params{nonfatal};
1439 $ok=0;
1441 elsif (defined $ret) {
1442 error($ret) unless $params{nonfatal};
1443 $ok=0;
1448 return defined $ok ? $ok : 1;
1451 my $wikilock;
1453 sub lockwiki () {
1454 # Take an exclusive lock on the wiki to prevent multiple concurrent
1455 # run issues. The lock will be dropped on program exit.
1456 if (! -d $config{wikistatedir}) {
1457 mkdir($config{wikistatedir});
1459 open($wikilock, '>', "$config{wikistatedir}/lockfile") ||
1460 error ("cannot write to $config{wikistatedir}/lockfile: $!");
1461 if (! flock($wikilock, 2)) { # LOCK_EX
1462 error("failed to get lock");
1464 return 1;
1467 sub unlockwiki () {
1468 POSIX::close($ENV{IKIWIKI_CGILOCK_FD}) if exists $ENV{IKIWIKI_CGILOCK_FD};
1469 return close($wikilock) if $wikilock;
1470 return;
1473 my $commitlock;
1475 sub commit_hook_enabled () {
1476 open($commitlock, '+>', "$config{wikistatedir}/commitlock") ||
1477 error("cannot write to $config{wikistatedir}/commitlock: $!");
1478 if (! flock($commitlock, 1 | 4)) { # LOCK_SH | LOCK_NB to test
1479 close($commitlock) || error("failed closing commitlock: $!");
1480 return 0;
1482 close($commitlock) || error("failed closing commitlock: $!");
1483 return 1;
1486 sub disable_commit_hook () {
1487 open($commitlock, '>', "$config{wikistatedir}/commitlock") ||
1488 error("cannot write to $config{wikistatedir}/commitlock: $!");
1489 if (! flock($commitlock, 2)) { # LOCK_EX
1490 error("failed to get commit lock");
1492 return 1;
1495 sub enable_commit_hook () {
1496 return close($commitlock) if $commitlock;
1497 return;
1500 sub loadindex () {
1501 %oldrenderedfiles=%pagectime=();
1502 if (! $config{rebuild}) {
1503 %pagesources=%pagemtime=%oldlinks=%links=%depends=
1504 %destsources=%renderedfiles=%pagecase=%pagestate=
1505 %depends_simple=();
1507 my $in;
1508 if (! open ($in, "<", "$config{wikistatedir}/indexdb")) {
1509 if (-e "$config{wikistatedir}/index") {
1510 system("ikiwiki-transition", "indexdb", $config{srcdir});
1511 open ($in, "<", "$config{wikistatedir}/indexdb") || return;
1513 else {
1514 return;
1518 my $index=Storable::fd_retrieve($in);
1519 if (! defined $index) {
1520 return 0;
1523 my $pages;
1524 if (exists $index->{version} && ! ref $index->{version}) {
1525 $pages=$index->{page};
1526 %wikistate=%{$index->{state}};
1528 else {
1529 $pages=$index;
1530 %wikistate=();
1533 foreach my $src (keys %$pages) {
1534 my $d=$pages->{$src};
1535 my $page=pagename($src);
1536 $pagectime{$page}=$d->{ctime};
1537 if (! $config{rebuild}) {
1538 $pagesources{$page}=$src;
1539 $pagemtime{$page}=$d->{mtime};
1540 $renderedfiles{$page}=$d->{dest};
1541 if (exists $d->{links} && ref $d->{links}) {
1542 $links{$page}=$d->{links};
1543 $oldlinks{$page}=[@{$d->{links}}];
1545 if (ref $d->{depends_simple} eq 'ARRAY') {
1546 # old format
1547 $depends_simple{$page}={
1548 map { $_ => 1 } @{$d->{depends_simple}}
1551 elsif (exists $d->{depends_simple}) {
1552 $depends_simple{$page}=$d->{depends_simple};
1554 if (exists $d->{dependslist}) {
1555 # old format
1556 $depends{$page}={
1557 map { $_ => $DEPEND_CONTENT }
1558 @{$d->{dependslist}}
1561 elsif (exists $d->{depends} && ! ref $d->{depends}) {
1562 # old format
1563 $depends{$page}={$d->{depends} => $DEPEND_CONTENT };
1565 elsif (exists $d->{depends}) {
1566 $depends{$page}=$d->{depends};
1568 if (exists $d->{state}) {
1569 $pagestate{$page}=$d->{state};
1572 $oldrenderedfiles{$page}=[@{$d->{dest}}];
1574 foreach my $page (keys %pagesources) {
1575 $pagecase{lc $page}=$page;
1577 foreach my $page (keys %renderedfiles) {
1578 $destsources{$_}=$page foreach @{$renderedfiles{$page}};
1580 return close($in);
1583 sub saveindex () {
1584 run_hooks(savestate => sub { shift->() });
1586 my %hookids;
1587 foreach my $type (keys %hooks) {
1588 $hookids{$_}=1 foreach keys %{$hooks{$type}};
1590 my @hookids=keys %hookids;
1592 if (! -d $config{wikistatedir}) {
1593 mkdir($config{wikistatedir});
1595 my $newfile="$config{wikistatedir}/indexdb.new";
1596 my $cleanup = sub { unlink($newfile) };
1597 open (my $out, '>', $newfile) || error("cannot write to $newfile: $!", $cleanup);
1599 my %index;
1600 foreach my $page (keys %pagemtime) {
1601 next unless $pagemtime{$page};
1602 my $src=$pagesources{$page};
1604 $index{page}{$src}={
1605 ctime => $pagectime{$page},
1606 mtime => $pagemtime{$page},
1607 dest => $renderedfiles{$page},
1608 links => $links{$page},
1611 if (exists $depends{$page}) {
1612 $index{page}{$src}{depends} = $depends{$page};
1615 if (exists $depends_simple{$page}) {
1616 $index{page}{$src}{depends_simple} = $depends_simple{$page};
1619 if (exists $pagestate{$page}) {
1620 foreach my $id (@hookids) {
1621 foreach my $key (keys %{$pagestate{$page}{$id}}) {
1622 $index{page}{$src}{state}{$id}{$key}=$pagestate{$page}{$id}{$key};
1628 $index{state}={};
1629 foreach my $id (@hookids) {
1630 foreach my $key (keys %{$wikistate{$id}}) {
1631 $index{state}{$id}{$key}=$wikistate{$id}{$key};
1635 $index{version}="3";
1636 my $ret=Storable::nstore_fd(\%index, $out);
1637 return if ! defined $ret || ! $ret;
1638 close $out || error("failed saving to $newfile: $!", $cleanup);
1639 rename($newfile, "$config{wikistatedir}/indexdb") ||
1640 error("failed renaming $newfile to $config{wikistatedir}/indexdb", $cleanup);
1642 return 1;
1645 sub template_file ($) {
1646 my $template=shift;
1648 foreach my $dir ($config{templatedir}, @{$config{templatedirs}},
1649 "$installdir/share/ikiwiki/templates") {
1650 return "$dir/$template" if -e "$dir/$template";
1652 return;
1655 sub template_params (@) {
1656 my $filename=template_file(shift);
1658 if (! defined $filename) {
1659 return if wantarray;
1660 return "";
1663 my @ret=(
1664 filter => sub {
1665 my $text_ref = shift;
1666 ${$text_ref} = decode_utf8(${$text_ref});
1668 filename => $filename,
1669 loop_context_vars => 1,
1670 die_on_bad_params => 0,
1673 return wantarray ? @ret : {@ret};
1676 sub template ($;@) {
1677 require HTML::Template;
1678 return HTML::Template->new(template_params(@_));
1681 sub misctemplate ($$;@) {
1682 my $title=shift;
1683 my $pagebody=shift;
1685 my $template=template("misc.tmpl");
1686 $template->param(
1687 title => $title,
1688 indexlink => indexlink(),
1689 wikiname => $config{wikiname},
1690 pagebody => $pagebody,
1691 baseurl => baseurl(),
1694 run_hooks(pagetemplate => sub {
1695 shift->(page => "", destpage => "", template => $template);
1697 return $template->output;
1700 sub hook (@) {
1701 my %param=@_;
1703 if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
1704 error 'hook requires type, call, and id parameters';
1707 return if $param{no_override} && exists $hooks{$param{type}}{$param{id}};
1709 $hooks{$param{type}}{$param{id}}=\%param;
1710 return 1;
1713 sub run_hooks ($$) {
1714 # Calls the given sub for each hook of the given type,
1715 # passing it the hook function to call.
1716 my $type=shift;
1717 my $sub=shift;
1719 if (exists $hooks{$type}) {
1720 my (@first, @middle, @last);
1721 foreach my $id (keys %{$hooks{$type}}) {
1722 if ($hooks{$type}{$id}{first}) {
1723 push @first, $id;
1725 elsif ($hooks{$type}{$id}{last}) {
1726 push @last, $id;
1728 else {
1729 push @middle, $id;
1732 foreach my $id (@first, @middle, @last) {
1733 $sub->($hooks{$type}{$id}{call});
1737 return 1;
1740 sub rcs_update () {
1741 $hooks{rcs}{rcs_update}{call}->(@_);
1744 sub rcs_prepedit ($) {
1745 $hooks{rcs}{rcs_prepedit}{call}->(@_);
1748 sub rcs_commit ($$$;$$) {
1749 $hooks{rcs}{rcs_commit}{call}->(@_);
1752 sub rcs_commit_staged ($$$) {
1753 $hooks{rcs}{rcs_commit_staged}{call}->(@_);
1756 sub rcs_add ($) {
1757 $hooks{rcs}{rcs_add}{call}->(@_);
1760 sub rcs_remove ($) {
1761 $hooks{rcs}{rcs_remove}{call}->(@_);
1764 sub rcs_rename ($$) {
1765 $hooks{rcs}{rcs_rename}{call}->(@_);
1768 sub rcs_recentchanges ($) {
1769 $hooks{rcs}{rcs_recentchanges}{call}->(@_);
1772 sub rcs_diff ($) {
1773 $hooks{rcs}{rcs_diff}{call}->(@_);
1776 sub rcs_getctime ($) {
1777 $hooks{rcs}{rcs_getctime}{call}->(@_);
1780 sub rcs_receive () {
1781 $hooks{rcs}{rcs_receive}{call}->();
1784 sub add_depends ($$;$) {
1785 my $page=shift;
1786 my $pagespec=shift;
1787 my $deptype=shift || $DEPEND_CONTENT;
1789 # Is the pagespec a simple page name?
1790 if ($pagespec =~ /$config{wiki_file_regexp}/ &&
1791 $pagespec !~ /[\s*?()!]/) {
1792 $depends_simple{$page}{lc $pagespec} |= $deptype;
1793 return 1;
1796 # Add explicit dependencies for influences.
1797 my $sub=pagespec_translate($pagespec);
1798 return unless defined $sub;
1799 foreach my $p (keys %pagesources) {
1800 my $r=$sub->($p, location => $page);
1801 my $i=$r->influences;
1802 foreach my $k (keys %$i) {
1803 $depends_simple{$page}{lc $k} |= $i->{$k};
1805 last if $r->influences_static;
1808 $depends{$page}{$pagespec} |= $deptype;
1809 return 1;
1812 sub deptype (@) {
1813 my $deptype=0;
1814 foreach my $type (@_) {
1815 if ($type eq 'presence') {
1816 $deptype |= $DEPEND_PRESENCE;
1818 elsif ($type eq 'links') {
1819 $deptype |= $DEPEND_LINKS;
1821 elsif ($type eq 'content') {
1822 $deptype |= $DEPEND_CONTENT;
1825 return $deptype;
1828 my $file_prune_regexp;
1829 sub file_pruned ($;$) {
1830 my $file=shift;
1831 if (@_) {
1832 require File::Spec;
1833 $file=File::Spec->canonpath($file);
1834 my $base=File::Spec->canonpath(shift);
1835 return if $file eq $base;
1836 $file =~ s#^\Q$base\E/+##;
1839 if (defined $config{include} && length $config{include}) {
1840 return 0 if $file =~ m/$config{include}/;
1843 if (! defined $file_prune_regexp) {
1844 $file_prune_regexp='('.join('|', @{$config{wiki_file_prune_regexps}}).')';
1845 $file_prune_regexp=qr/$file_prune_regexp/;
1847 return $file =~ m/$file_prune_regexp/;
1850 sub define_gettext () {
1851 # If translation is needed, redefine the gettext function to do it.
1852 # Otherwise, it becomes a quick no-op.
1853 my $gettext_obj;
1854 my $getobj;
1855 if ((exists $ENV{LANG} && length $ENV{LANG}) ||
1856 (exists $ENV{LC_ALL} && length $ENV{LC_ALL}) ||
1857 (exists $ENV{LC_MESSAGES} && length $ENV{LC_MESSAGES})) {
1858 $getobj=sub {
1859 $gettext_obj=eval q{
1860 use Locale::gettext q{textdomain};
1861 Locale::gettext->domain('ikiwiki')
1866 no warnings 'redefine';
1867 *gettext=sub {
1868 $getobj->() if $getobj;
1869 if ($gettext_obj) {
1870 $gettext_obj->get(shift);
1872 else {
1873 return shift;
1876 *ngettext=sub {
1877 $getobj->() if $getobj;
1878 if ($gettext_obj) {
1879 $gettext_obj->nget(@_);
1881 else {
1882 return ($_[2] == 1 ? $_[0] : $_[1])
1887 sub gettext {
1888 define_gettext();
1889 gettext(@_);
1892 sub ngettext {
1893 define_gettext();
1894 ngettext(@_);
1897 sub yesno ($) {
1898 my $val=shift;
1900 return (defined $val && (lc($val) eq gettext("yes") || lc($val) eq "yes" || $val eq "1"));
1903 sub inject {
1904 # Injects a new function into the symbol table to replace an
1905 # exported function.
1906 my %params=@_;
1908 # This is deep ugly perl foo, beware.
1909 no strict;
1910 no warnings;
1911 if (! defined $params{parent}) {
1912 $params{parent}='::';
1913 $params{old}=\&{$params{name}};
1914 $params{name}=~s/.*:://;
1916 my $parent=$params{parent};
1917 foreach my $ns (grep /^\w+::/, keys %{$parent}) {
1918 $ns = $params{parent} . $ns;
1919 inject(%params, parent => $ns) unless $ns eq '::main::';
1920 *{$ns . $params{name}} = $params{call}
1921 if exists ${$ns}{$params{name}} &&
1922 \&{${$ns}{$params{name}}} == $params{old};
1924 use strict;
1925 use warnings;
1928 sub add_link ($$) {
1929 my $page=shift;
1930 my $link=shift;
1932 push @{$links{$page}}, $link
1933 unless grep { $_ eq $link } @{$links{$page}};
1936 sub pagespec_translate ($) {
1937 my $spec=shift;
1939 # Convert spec to perl code.
1940 my $code="";
1941 my @data;
1942 while ($spec=~m{
1943 \s* # ignore whitespace
1944 ( # 1: match a single word
1945 \! # !
1947 \( # (
1949 \) # )
1951 \w+\([^\)]*\) # command(params)
1953 [^\s()]+ # any other text
1955 \s* # ignore whitespace
1956 }gx) {
1957 my $word=$1;
1958 if (lc $word eq 'and') {
1959 $code.=' &';
1961 elsif (lc $word eq 'or') {
1962 $code.=' |';
1964 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
1965 $code.=' '.$word;
1967 elsif ($word =~ /^(\w+)\((.*)\)$/) {
1968 if (exists $IkiWiki::PageSpec::{"match_$1"}) {
1969 push @data, $2;
1970 $code.="IkiWiki::PageSpec::match_$1(\$page, \$data[$#data], \@_)";
1972 else {
1973 push @data, qq{unknown function in pagespec "$word"};
1974 $code.="IkiWiki::ErrorReason->new(\$data[$#data])";
1977 else {
1978 push @data, $word;
1979 $code.=" IkiWiki::PageSpec::match_glob(\$page, \$data[$#data], \@_)";
1983 if (! length $code) {
1984 $code="IkiWiki::FailReason->new('empty pagespec')";
1987 no warnings;
1988 return eval 'sub { my $page=shift; '.$code.' }';
1991 sub pagespec_match ($$;@) {
1992 my $page=shift;
1993 my $spec=shift;
1994 my @params=@_;
1996 # Backwards compatability with old calling convention.
1997 if (@params == 1) {
1998 unshift @params, 'location';
2001 my $sub=pagespec_translate($spec);
2002 return IkiWiki::ErrorReason->new("syntax error in pagespec \"$spec\"")
2003 if ! defined $sub;
2004 return $sub->($page, @params);
2007 sub pagespec_match_list ($$;@) {
2008 my $page=shift;
2009 my $pagespec=shift;
2010 my %params=@_;
2012 # Backwards compatability with old calling convention.
2013 if (ref $page) {
2014 print STDERR "warning: a plugin (".caller().") is using pagespec_match_list in an obsolete way, and needs to be updated\n";
2015 $params{list}=$page;
2016 $page=$params{location}; # ugh!
2019 my $sub=pagespec_translate($pagespec);
2020 error "syntax error in pagespec \"$pagespec\""
2021 if ! defined $sub;
2023 my @candidates;
2024 if (exists $params{list}) {
2025 @candidates=exists $params{filter}
2026 ? grep { ! $params{filter}->($_) } @{$params{list}}
2027 : @{$params{list}};
2029 else {
2030 @candidates=exists $params{filter}
2031 ? grep { ! $params{filter}->($_) } keys %pagesources
2032 : keys %pagesources;
2035 if (defined $params{sort}) {
2036 my $f;
2037 if ($params{sort} eq 'title') {
2038 $f=sub { pagetitle(basename($a)) cmp pagetitle(basename($b)) };
2040 elsif ($params{sort} eq 'title_natural') {
2041 eval q{use Sort::Naturally};
2042 if ($@) {
2043 error(gettext("Sort::Naturally needed for title_natural sort"));
2045 $f=sub { Sort::Naturally::ncmp(pagetitle(basename($a)), pagetitle(basename($b))) };
2047 elsif ($params{sort} eq 'mtime') {
2048 $f=sub { $pagemtime{$b} <=> $pagemtime{$a} };
2050 elsif ($params{sort} eq 'age') {
2051 $f=sub { $pagectime{$b} <=> $pagectime{$a} };
2053 else {
2054 error sprintf(gettext("unknown sort type %s"), $params{sort});
2056 @candidates = sort { &$f } @candidates;
2059 @candidates=reverse(@candidates) if $params{reverse};
2061 $depends{$page}{$pagespec} |= ($params{deptype} || $DEPEND_CONTENT);
2063 # clear params, remainder is passed to pagespec
2064 my $num=$params{num};
2065 delete @params{qw{num deptype reverse sort filter list}};
2067 my @matches;
2068 my $firstfail;
2069 my $count=0;
2070 my $accum=IkiWiki::SuccessReason->new();
2071 foreach my $p (@candidates) {
2072 my $r=$sub->($p, %params, location => $page);
2073 error(sprintf(gettext("cannot match pages: %s"), $r))
2074 if $r->isa("IkiWiki::ErrorReason");
2075 $accum |= $r;
2076 if ($r) {
2077 push @matches, $p;
2078 last if defined $num && ++$count == $num;
2082 # Add simple dependencies for accumulated influences.
2083 my $i=$accum->influences;
2084 foreach my $k (keys %$i) {
2085 $depends_simple{$page}{lc $k} |= $i->{$k};
2088 return @matches;
2091 sub pagespec_valid ($) {
2092 my $spec=shift;
2094 return defined pagespec_translate($spec);
2097 sub glob2re ($) {
2098 my $re=quotemeta(shift);
2099 $re=~s/\\\*/.*/g;
2100 $re=~s/\\\?/./g;
2101 return $re;
2104 package IkiWiki::FailReason;
2106 use overload (
2107 '""' => sub { $_[0][0] },
2108 '0+' => sub { 0 },
2109 '!' => sub { bless $_[0], 'IkiWiki::SuccessReason'},
2110 '&' => sub { $_[0]->merge_influences($_[1], 1); $_[0] },
2111 '|' => sub { $_[1]->merge_influences($_[0]); $_[1] },
2112 fallback => 1,
2115 our @ISA = 'IkiWiki::SuccessReason';
2117 package IkiWiki::SuccessReason;
2119 use overload (
2120 '""' => sub { $_[0][0] },
2121 '0+' => sub { 1 },
2122 '!' => sub { bless $_[0], 'IkiWiki::FailReason'},
2123 '&' => sub { $_[1]->merge_influences($_[0], 1); $_[1] },
2124 '|' => sub { $_[0]->merge_influences($_[1]); $_[0] },
2125 fallback => 1,
2128 sub new {
2129 my $class = shift;
2130 my $value = shift;
2131 return bless [$value, {@_}], $class;
2134 sub influences {
2135 my $this=shift;
2136 $this->[1]={@_} if @_;
2137 my %i=%{$this->[1]};
2138 delete $i{""};
2139 return \%i;
2142 sub influences_static {
2143 return ! $_[0][1]->{""};
2146 sub merge_influences {
2147 my $this=shift;
2148 my $other=shift;
2149 my $anded=shift;
2151 if (! $anded || (($this || %{$this->[1]}) &&
2152 ($other || %{$other->[1]}))) {
2153 foreach my $influence (keys %{$other->[1]}) {
2154 $this->[1]{$influence} |= $other->[1]{$influence};
2157 else {
2158 # influence blocker
2159 $this->[1]={};
2163 package IkiWiki::ErrorReason;
2165 our @ISA = 'IkiWiki::FailReason';
2167 package IkiWiki::PageSpec;
2169 sub derel ($$) {
2170 my $path=shift;
2171 my $from=shift;
2173 if ($path =~ m!^\./!) {
2174 $from=~s#/?[^/]+$## if defined $from;
2175 $path=~s#^\./##;
2176 $path="$from/$path" if length $from;
2179 return $path;
2182 sub match_glob ($$;@) {
2183 my $page=shift;
2184 my $glob=shift;
2185 my %params=@_;
2187 $glob=derel($glob, $params{location});
2189 my $regexp=IkiWiki::glob2re($glob);
2190 if ($page=~/^$regexp$/i) {
2191 if (! IkiWiki::isinternal($page) || $params{internal}) {
2192 return IkiWiki::SuccessReason->new("$glob matches $page");
2194 else {
2195 return IkiWiki::FailReason->new("$glob matches $page, but the page is an internal page");
2198 else {
2199 return IkiWiki::FailReason->new("$glob does not match $page");
2203 sub match_internal ($$;@) {
2204 return match_glob($_[0], $_[1], @_, internal => 1)
2207 sub match_link ($$;@) {
2208 my $page=shift;
2209 my $link=lc(shift);
2210 my %params=@_;
2212 $link=derel($link, $params{location});
2213 my $from=exists $params{location} ? $params{location} : '';
2215 my $links = $IkiWiki::links{$page};
2216 return IkiWiki::FailReason->new("$page has no links", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2217 unless $links && @{$links};
2218 my $bestlink = IkiWiki::bestlink($from, $link);
2219 foreach my $p (@{$links}) {
2220 if (length $bestlink) {
2221 return IkiWiki::SuccessReason->new("$page links to $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2222 if $bestlink eq IkiWiki::bestlink($page, $p);
2224 else {
2225 return IkiWiki::SuccessReason->new("$page links to page $p matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2226 if match_glob($p, $link, %params);
2227 my ($p_rel)=$p=~/^\/?(.*)/;
2228 $link=~s/^\///;
2229 return IkiWiki::SuccessReason->new("$page links to page $p_rel matching $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1)
2230 if match_glob($p_rel, $link, %params);
2233 return IkiWiki::FailReason->new("$page does not link to $link", $page => $IkiWiki::DEPEND_LINKS, "" => 1);
2236 sub match_backlink ($$;@) {
2237 my $ret=match_link($_[1], $_[0], @_);
2238 $ret->influences($_[1] => $IkiWiki::DEPEND_LINKS);
2239 return $ret;
2242 sub match_created_before ($$;@) {
2243 my $page=shift;
2244 my $testpage=shift;
2245 my %params=@_;
2247 $testpage=derel($testpage, $params{location});
2249 if (exists $IkiWiki::pagectime{$testpage}) {
2250 if ($IkiWiki::pagectime{$page} < $IkiWiki::pagectime{$testpage}) {
2251 return IkiWiki::SuccessReason->new("$page created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2253 else {
2254 return IkiWiki::FailReason->new("$page not created before $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2257 else {
2258 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2262 sub match_created_after ($$;@) {
2263 my $page=shift;
2264 my $testpage=shift;
2265 my %params=@_;
2267 $testpage=derel($testpage, $params{location});
2269 if (exists $IkiWiki::pagectime{$testpage}) {
2270 if ($IkiWiki::pagectime{$page} > $IkiWiki::pagectime{$testpage}) {
2271 return IkiWiki::SuccessReason->new("$page created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2273 else {
2274 return IkiWiki::FailReason->new("$page not created after $testpage", $testpage => $IkiWiki::DEPEND_PRESENCE);
2277 else {
2278 return IkiWiki::ErrorReason->new("$testpage does not exist", $testpage => $IkiWiki::DEPEND_PRESENCE);
2282 sub match_creation_day ($$;@) {
2283 if ((gmtime($IkiWiki::pagectime{shift()}))[3] == shift) {
2284 return IkiWiki::SuccessReason->new('creation_day matched');
2286 else {
2287 return IkiWiki::FailReason->new('creation_day did not match');
2291 sub match_creation_month ($$;@) {
2292 if ((gmtime($IkiWiki::pagectime{shift()}))[4] + 1 == shift) {
2293 return IkiWiki::SuccessReason->new('creation_month matched');
2295 else {
2296 return IkiWiki::FailReason->new('creation_month did not match');
2300 sub match_creation_year ($$;@) {
2301 if ((gmtime($IkiWiki::pagectime{shift()}))[5] + 1900 == shift) {
2302 return IkiWiki::SuccessReason->new('creation_year matched');
2304 else {
2305 return IkiWiki::FailReason->new('creation_year did not match');
2309 sub match_user ($$;@) {
2310 shift;
2311 my $user=shift;
2312 my %params=@_;
2314 my $regexp=IkiWiki::glob2re($user);
2316 if (! exists $params{user}) {
2317 return IkiWiki::ErrorReason->new("no user specified");
2320 if (defined $params{user} && $params{user}=~/^$regexp$/i) {
2321 return IkiWiki::SuccessReason->new("user is $user");
2323 elsif (! defined $params{user}) {
2324 return IkiWiki::FailReason->new("not logged in");
2326 else {
2327 return IkiWiki::FailReason->new("user is $params{user}, not $user");
2331 sub match_admin ($$;@) {
2332 shift;
2333 shift;
2334 my %params=@_;
2336 if (! exists $params{user}) {
2337 return IkiWiki::ErrorReason->new("no user specified");
2340 if (defined $params{user} && IkiWiki::is_admin($params{user})) {
2341 return IkiWiki::SuccessReason->new("user is an admin");
2343 elsif (! defined $params{user}) {
2344 return IkiWiki::FailReason->new("not logged in");
2346 else {
2347 return IkiWiki::FailReason->new("user is not an admin");
2351 sub match_ip ($$;@) {
2352 shift;
2353 my $ip=shift;
2354 my %params=@_;
2356 if (! exists $params{ip}) {
2357 return IkiWiki::ErrorReason->new("no IP specified");
2360 if (defined $params{ip} && lc $params{ip} eq lc $ip) {
2361 return IkiWiki::SuccessReason->new("IP is $ip");
2363 else {
2364 return IkiWiki::FailReason->new("IP is $params{ip}, not $ip");