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