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