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