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