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