last minute fix from faidon
[ikiwiki] / IkiWiki.pm
1 #!/usr/bin/perl
2
3 package IkiWiki;
4 use warnings;
5 use strict;
6 use Encode;
7 use open qw{:utf8 :std};
8
9 # Optimisation.
10 use Memoize;
11 memoize("abs2rel");
12
13 use vars qw{%config %links %oldlinks %oldpagemtime %pagectime
14             %renderedfiles %pagesources %depends %hooks};
15
16 sub defaultconfig () { #{{{
17         wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.html?$|\.rss$)},
18         wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]]+)\]\]/,
19         wiki_processor_regexp => qr/\[\[(\w+)\s+([^\]]*)\]\]/,
20         wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
21         verbose => 0,
22         wikiname => "wiki",
23         default_pageext => "mdwn",
24         cgi => 0,
25         rcs => 'svn',
26         notify => 0,
27         url => '',
28         cgiurl => '',
29         historyurl => '',
30         diffurl => '',
31         anonok => 0,
32         rss => 0,
33         discussion => 1,
34         rebuild => 0,
35         refresh => 0,
36         getctime => 0,
37         w3mmode => 0,
38         wrapper => undef,
39         wrappermode => undef,
40         svnrepo => undef,
41         svnpath => "trunk",
42         srcdir => undef,
43         destdir => undef,
44         pingurl => [],
45         templatedir => "/usr/share/ikiwiki/templates",
46         underlaydir => "/usr/share/ikiwiki/basewiki",
47         setup => undef,
48         adminuser => undef,
49         adminemail => undef,
50         plugin => [qw{mdwn inline htmlscrubber}],
51         timeformat => '%c',
52         locale => undef,
53 } #}}}
54    
55 sub checkconfig () { #{{{
56         # locale stuff; avoid LC_ALL since it overrides everything
57         if (defined $ENV{LC_ALL}) {
58                 $ENV{LANG} = $ENV{LC_ALL};
59                 delete $ENV{LC_ALL};
60         }
61         if (defined $config{locale}) {
62                 eval q{use POSIX};
63                 $ENV{LANG} = $config{locale}
64                         if POSIX::setlocale(&POSIX::LC_TIME, $config{locale});
65         }
66
67         if ($config{w3mmode}) {
68                 eval q{use Cwd q{abs_path}};
69                 $config{srcdir}=possibly_foolish_untaint(abs_path($config{srcdir}));
70                 $config{destdir}=possibly_foolish_untaint(abs_path($config{destdir}));
71                 $config{cgiurl}="file:///\$LIB/ikiwiki-w3m.cgi/".$config{cgiurl}
72                         unless $config{cgiurl} =~ m!file:///!;
73                 $config{url}="file://".$config{destdir};
74         }
75
76         if ($config{cgi} && ! length $config{url}) {
77                 error("Must specify url to wiki with --url when using --cgi\n");
78         }
79         if ($config{rss} && ! length $config{url}) {
80                 error("Must specify url to wiki with --url when using --rss\n");
81         }
82         
83         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
84                 unless exists $config{wikistatedir};
85         
86         if ($config{rcs}) {
87                 eval qq{require IkiWiki::Rcs::$config{rcs}};
88                 if ($@) {
89                         error("Failed to load RCS module IkiWiki::Rcs::$config{rcs}: $@");
90                 }
91         }
92         else {
93                 require IkiWiki::Rcs::Stub;
94         }
95
96         if (exists $hooks{checkconfig}) {
97                 foreach my $id (keys %{$hooks{checkconfig}}) {
98                         $hooks{checkconfig}{$id}{call}->();
99                 }
100         }
101 } #}}}
102
103 sub loadplugins () { #{{{
104         foreach my $plugin (@{$config{plugin}}) {
105                 my $mod="IkiWiki::Plugin::".possibly_foolish_untaint($plugin);
106                 eval qq{use $mod};
107                 if ($@) {
108                         error("Failed to load plugin $mod: $@");
109                 }
110         }
111 } #}}}
112
113 sub error ($) { #{{{
114         if ($config{cgi}) {
115                 print "Content-type: text/html\n\n";
116                 print misctemplate("Error", "<p>Error: @_</p>");
117         }
118         die @_;
119 } #}}}
120
121 sub debug ($) { #{{{
122         return unless $config{verbose};
123         if (! $config{cgi}) {
124                 print "@_\n";
125         }
126         else {
127                 print STDERR "@_\n";
128         }
129 } #}}}
130
131 sub possibly_foolish_untaint ($) { #{{{
132         my $tainted=shift;
133         my ($untainted)=$tainted=~/(.*)/;
134         return $untainted;
135 } #}}}
136
137 sub basename ($) { #{{{
138         my $file=shift;
139
140         $file=~s!.*/+!!;
141         return $file;
142 } #}}}
143
144 sub dirname ($) { #{{{
145         my $file=shift;
146
147         $file=~s!/*[^/]+$!!;
148         return $file;
149 } #}}}
150
151 sub pagetype ($) { #{{{
152         my $page=shift;
153         
154         if ($page =~ /\.([^.]+)$/) {
155                 return $1 if exists $hooks{htmlize}{$1};
156         }
157         return undef;
158 } #}}}
159
160 sub pagename ($) { #{{{
161         my $file=shift;
162
163         my $type=pagetype($file);
164         my $page=$file;
165         $page=~s/\Q.$type\E*$// if defined $type;
166         return $page;
167 } #}}}
168
169 sub htmlpage ($) { #{{{
170         my $page=shift;
171
172         return $page.".html";
173 } #}}}
174
175 sub srcfile ($) { #{{{
176         my $file=shift;
177
178         return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
179         return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
180         error("internal error: $file cannot be found");
181 } #}}}
182
183 sub readfile ($;$) { #{{{
184         my $file=shift;
185         my $binary=shift;
186
187         if (-l $file) {
188                 error("cannot read a symlink ($file)");
189         }
190         
191         local $/=undef;
192         open (IN, $file) || error("failed to read $file: $!");
193         binmode(IN) if ($binary);
194         my $ret=<IN>;
195         close IN;
196         return $ret;
197 } #}}}
198
199 sub writefile ($$$;$) { #{{{
200         my $file=shift; # can include subdirs
201         my $destdir=shift; # directory to put file in
202         my $content=shift;
203         my $binary=shift;
204         
205         my $test=$file;
206         while (length $test) {
207                 if (-l "$destdir/$test") {
208                         error("cannot write to a symlink ($test)");
209                 }
210                 $test=dirname($test);
211         }
212
213         my $dir=dirname("$destdir/$file");
214         if (! -d $dir) {
215                 my $d="";
216                 foreach my $s (split(m!/+!, $dir)) {
217                         $d.="$s/";
218                         if (! -d $d) {
219                                 mkdir($d) || error("failed to create directory $d: $!");
220                         }
221                 }
222         }
223         
224         open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
225         binmode(OUT) if ($binary);
226         print OUT $content;
227         close OUT;
228 } #}}}
229
230 sub bestlink ($$) { #{{{
231         # Given a page and the text of a link on the page, determine which
232         # existing page that link best points to. Prefers pages under a
233         # subdirectory with the same name as the source page, failing that
234         # goes down the directory tree to the base looking for matching
235         # pages.
236         my $page=shift;
237         my $link=lc(shift);
238         
239         my $cwd=$page;
240         do {
241                 my $l=$cwd;
242                 $l.="/" if length $l;
243                 $l.=$link;
244
245                 if (exists $links{$l}) {
246                         #debug("for $page, \"$link\", use $l");
247                         return $l;
248                 }
249         } while $cwd=~s!/?[^/]+$!!;
250
251         #print STDERR "warning: page $page, broken link: $link\n";
252         return "";
253 } #}}}
254
255 sub isinlinableimage ($) { #{{{
256         my $file=shift;
257         
258         $file=~/\.(png|gif|jpg|jpeg)$/i;
259 } #}}}
260
261 sub pagetitle ($) { #{{{
262         my $page=shift;
263         $page=~s/__(\d+)__/&#$1;/g;
264         $page=~y/_/ /;
265         return $page;
266 } #}}}
267
268 sub titlepage ($) { #{{{
269         my $title=shift;
270         $title=~y/ /_/;
271         $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
272         return $title;
273 } #}}}
274
275 sub cgiurl (@) { #{{{
276         my %params=@_;
277
278         return $config{cgiurl}."?".join("&amp;", map "$_=$params{$_}", keys %params);
279 } #}}}
280
281 sub styleurl (;$) { #{{{
282         my $page=shift;
283
284         return "$config{url}/style.css" if ! defined $page;
285         
286         $page=~s/[^\/]+$//;
287         $page=~s/[^\/]+\//..\//g;
288         return $page."style.css";
289 } #}}}
290
291 sub abs2rel ($$) {
292         # Work around very innefficient behavior in File::Spec if abs2rel
293         # is passed two relative paths. It's much faster if paths are
294         # absolute!
295         my $path="/".shift;
296         my $base="/".shift;
297
298         require File::Spec;
299         my $ret=File::Spec->abs2rel($path, $base);
300         $ret=~s/^// if defined $ret;
301         return $ret;
302 }
303
304 sub htmllink ($$$;$$$) { #{{{
305         my $lpage=shift; # the page doing the linking
306         my $page=shift; # the page that will contain the link (different for inline)
307         my $link=shift;
308         my $noimageinline=shift; # don't turn links into inline html images
309         my $forcesubpage=shift; # force a link to a subpage
310         my $linktext=shift; # set to force the link text to something
311
312         my $bestlink;
313         if (! $forcesubpage) {
314                 $bestlink=bestlink($lpage, $link);
315         }
316         else {
317                 $bestlink="$lpage/".lc($link);
318         }
319
320         $linktext=pagetitle(basename($link)) unless defined $linktext;
321         
322         return $linktext if length $bestlink && $page eq $bestlink;
323         
324         # TODO BUG: %renderedfiles may not have it, if the linked to page
325         # was also added and isn't yet rendered! Note that this bug is
326         # masked by the bug that makes all new files be rendered twice.
327         if (! grep { $_ eq $bestlink } values %renderedfiles) {
328                 $bestlink=htmlpage($bestlink);
329         }
330         if (! grep { $_ eq $bestlink } values %renderedfiles) {
331                 return "<span><a href=\"".
332                         cgiurl(do => "create", page => $link, from => $page).
333                         "\">?</a>$linktext</span>"
334         }
335         
336         $bestlink=abs2rel($bestlink, dirname($page));
337         
338         if (! $noimageinline && isinlinableimage($bestlink)) {
339                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
340         }
341         return "<a href=\"$bestlink\">$linktext</a>";
342 } #}}}
343
344 sub indexlink () { #{{{
345         return "<a href=\"$config{url}\">$config{wikiname}</a>";
346 } #}}}
347
348 sub lockwiki () { #{{{
349         # Take an exclusive lock on the wiki to prevent multiple concurrent
350         # run issues. The lock will be dropped on program exit.
351         if (! -d $config{wikistatedir}) {
352                 mkdir($config{wikistatedir});
353         }
354         open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
355                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
356         if (! flock(WIKILOCK, 2 | 4)) {
357                 debug("wiki seems to be locked, waiting for lock");
358                 my $wait=600; # arbitrary, but don't hang forever to 
359                               # prevent process pileup
360                 for (1..600) {
361                         return if flock(WIKILOCK, 2 | 4);
362                         sleep 1;
363                 }
364                 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
365         }
366 } #}}}
367
368 sub unlockwiki () { #{{{
369         close WIKILOCK;
370 } #}}}
371
372 sub loadindex () { #{{{
373         open (IN, "$config{wikistatedir}/index") || return;
374         while (<IN>) {
375                 $_=possibly_foolish_untaint($_);
376                 chomp;
377                 my %items;
378                 $items{link}=[];
379                 foreach my $i (split(/ /, $_)) {
380                         my ($item, $val)=split(/=/, $i, 2);
381                         push @{$items{$item}}, $val;
382                 }
383
384                 next unless exists $items{src}; # skip bad lines for now
385
386                 my $page=pagename($items{src}[0]);
387                 if (! $config{rebuild}) {
388                         $pagesources{$page}=$items{src}[0];
389                         $oldpagemtime{$page}=$items{mtime}[0];
390                         $oldlinks{$page}=[@{$items{link}}];
391                         $links{$page}=[@{$items{link}}];
392                         $depends{$page}=join(" ", @{$items{depends}})
393                                 if exists $items{depends};
394                         $renderedfiles{$page}=$items{dest}[0];
395                 }
396                 $pagectime{$page}=$items{ctime}[0];
397         }
398         close IN;
399 } #}}}
400
401 sub saveindex () { #{{{
402         if (! -d $config{wikistatedir}) {
403                 mkdir($config{wikistatedir});
404         }
405         open (OUT, ">$config{wikistatedir}/index") || 
406                 error("cannot write to $config{wikistatedir}/index: $!");
407         foreach my $page (keys %oldpagemtime) {
408                 next unless $oldpagemtime{$page};
409                 my $line="mtime=$oldpagemtime{$page} ".
410                         "ctime=$pagectime{$page} ".
411                         "src=$pagesources{$page} ".
412                         "dest=$renderedfiles{$page}";
413                 $line.=" link=$_" foreach @{$links{$page}};
414                 if (exists $depends{$page}) {
415                         $line.=" depends=$_" foreach split " ", $depends{$page};
416                 }
417                 print OUT $line."\n";
418         }
419         close OUT;
420 } #}}}
421
422 sub template_params (@) { #{{{
423         my $filename=shift;
424         
425         require HTML::Template;
426         return filter => sub {
427                         my $text_ref = shift;
428                         $$text_ref=&Encode::decode_utf8($$text_ref);
429                 },
430                 filename => "$config{templatedir}/$filename", @_;
431 } #}}}
432
433 sub template ($;@) { #{{{
434         HTML::Template->new(template_params(@_));
435 } #}}}
436
437 sub misctemplate ($$) { #{{{
438         my $title=shift;
439         my $pagebody=shift;
440         
441         my $template=template("misc.tmpl");
442         $template->param(
443                 title => $title,
444                 indexlink => indexlink(),
445                 wikiname => $config{wikiname},
446                 pagebody => $pagebody,
447                 styleurl => styleurl(),
448                 baseurl => "$config{url}/",
449         );
450         return $template->output;
451 }#}}}
452
453 sub glob_match ($$) { #{{{
454         my $page=shift;
455         my $glob=shift;
456
457         if ($glob =~ /^link\((.+)\)$/) {
458                 my $rev = $links{$page} or return undef;
459                 foreach my $p (@$rev) {
460                         return 1 if lc $p eq $1;
461                 }
462                 return 0;
463         } elsif ($glob =~ /^backlink\((.+)\)$/) {
464                 my $rev = $links{$1} or return undef;
465                 foreach my $p (@$rev) {
466                         return 1 if lc $p eq $page;
467                 }
468                 return 0;
469         } else {
470                 # turn glob into safe regexp
471                 $glob=quotemeta($glob);
472                 $glob=~s/\\\*/.*/g;
473                 $glob=~s/\\\?/./g;
474                 $glob=~s!\\/!/!g;
475                 
476                 return $page=~/^$glob$/i;
477         }
478 } #}}}
479
480 sub globlist_match ($$) { #{{{
481         my $page=shift;
482         my @globlist=split(" ", shift);
483
484         # check any negated globs first
485         foreach my $glob (@globlist) {
486                 return 0 if $glob=~/^!(.*)/ && glob_match($page, $1);
487         }
488
489         foreach my $glob (@globlist) {
490                 return 1 if glob_match($page, $glob);
491         }
492         
493         return 0;
494 } #}}}
495
496 sub hook (@) { # {{{
497         my %param=@_;
498         
499         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
500                 error "hook requires type, call, and id parameters";
501         }
502         
503         $hooks{$param{type}}{$param{id}}=\%param;
504 } # }}}
505
506 1