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