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