]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki.pm
remove the blog_list sub, only used one place and simplifies code to do
[ikiwiki.git] / IkiWiki.pm
1 #!/usr/bin/perl
2
3 package IkiWiki;
4 use warnings;
5 use strict;
6
7 use vars qw{%config %links %oldlinks %oldpagemtime %pagectime
8             %renderedfiles %pagesources %depends %hooks};
9
10 sub defaultconfig () { #{{{
11         wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.html?$|\.rss$)},
12         wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]]+)\]\]/,
13         wiki_processor_regexp => qr/\[\[(\w+)\s+([^\]]*)\]\]/,
14         wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
15         verbose => 0,
16         wikiname => "wiki",
17         default_pageext => ".mdwn",
18         cgi => 0,
19         rcs => 'svn',
20         notify => 0,
21         url => '',
22         cgiurl => '',
23         historyurl => '',
24         diffurl => '',
25         anonok => 0,
26         rss => 0,
27         discussion => 1,
28         rebuild => 0,
29         refresh => 0,
30         getctime => 0,
31         wrapper => undef,
32         wrappermode => undef,
33         svnrepo => undef,
34         svnpath => "trunk",
35         srcdir => undef,
36         destdir => undef,
37         pingurl => [],
38         templatedir => "/usr/share/ikiwiki/templates",
39         underlaydir => "/usr/share/ikiwiki/basewiki",
40         setup => undef,
41         adminuser => undef,
42         adminemail => undef,
43         plugin => [qw{inline htmlscrubber}],
44         timeformat => '%c',
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         if (! $binary) {
166                 binmode(IN, ":utf8");
167         }
168         else {
169                 binmode(IN);
170         }
171         my $ret=<IN>;
172         close IN;
173         return $ret;
174 } #}}}
175
176 sub writefile ($$$;$) { #{{{
177         my $file=shift; # can include subdirs
178         my $destdir=shift; # directory to put file in
179         my $content=shift;
180         my $binary=shift;
181         
182         my $test=$file;
183         while (length $test) {
184                 if (-l "$destdir/$test") {
185                         error("cannot write to a symlink ($test)");
186                 }
187                 $test=dirname($test);
188         }
189
190         my $dir=dirname("$destdir/$file");
191         if (! -d $dir) {
192                 my $d="";
193                 foreach my $s (split(m!/+!, $dir)) {
194                         $d.="$s/";
195                         if (! -d $d) {
196                                 mkdir($d) || error("failed to create directory $d: $!");
197                         }
198                 }
199         }
200         
201         open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
202         if (! $binary) {
203                 binmode(OUT, ":utf8");
204         }
205         else {
206                 binmode(OUT);
207         }
208         print OUT $content;
209         close OUT;
210 } #}}}
211
212 sub bestlink ($$) { #{{{
213         # Given a page and the text of a link on the page, determine which
214         # existing page that link best points to. Prefers pages under a
215         # subdirectory with the same name as the source page, failing that
216         # goes down the directory tree to the base looking for matching
217         # pages.
218         my $page=shift;
219         my $link=lc(shift);
220         
221         my $cwd=$page;
222         do {
223                 my $l=$cwd;
224                 $l.="/" if length $l;
225                 $l.=$link;
226
227                 if (exists $links{$l}) {
228                         #debug("for $page, \"$link\", use $l");
229                         return $l;
230                 }
231         } while $cwd=~s!/?[^/]+$!!;
232
233         #print STDERR "warning: page $page, broken link: $link\n";
234         return "";
235 } #}}}
236
237 sub isinlinableimage ($) { #{{{
238         my $file=shift;
239         
240         $file=~/\.(png|gif|jpg|jpeg)$/i;
241 } #}}}
242
243 sub pagetitle ($) { #{{{
244         my $page=shift;
245         $page=~s/__(\d+)__/&#$1;/g;
246         $page=~y/_/ /;
247         return $page;
248 } #}}}
249
250 sub titlepage ($) { #{{{
251         my $title=shift;
252         $title=~y/ /_/;
253         $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
254         return $title;
255 } #}}}
256
257 sub cgiurl (@) { #{{{
258         my %params=@_;
259
260         return $config{cgiurl}."?".join("&amp;", map "$_=$params{$_}", keys %params);
261 } #}}}
262
263 sub styleurl (;$) { #{{{
264         my $page=shift;
265
266         return "$config{url}/style.css" if ! defined $page;
267         
268         $page=~s/[^\/]+$//;
269         $page=~s/[^\/]+\//..\//g;
270         return $page."style.css";
271 } #}}}
272
273 sub htmllink ($$$;$$$) { #{{{
274         my $lpage=shift; # the page doing the linking
275         my $page=shift; # the page that will contain the link (different for inline)
276         my $link=shift;
277         my $noimageinline=shift; # don't turn links into inline html images
278         my $forcesubpage=shift; # force a link to a subpage
279         my $linktext=shift; # set to force the link text to something
280
281         my $bestlink;
282         if (! $forcesubpage) {
283                 $bestlink=bestlink($lpage, $link);
284         }
285         else {
286                 $bestlink="$lpage/".lc($link);
287         }
288
289         $linktext=pagetitle(basename($link)) unless defined $linktext;
290         
291         return $linktext if length $bestlink && $page eq $bestlink;
292         
293         # TODO BUG: %renderedfiles may not have it, if the linked to page
294         # was also added and isn't yet rendered! Note that this bug is
295         # masked by the bug that makes all new files be rendered twice.
296         if (! grep { $_ eq $bestlink } values %renderedfiles) {
297                 $bestlink=htmlpage($bestlink);
298         }
299         if (! grep { $_ eq $bestlink } values %renderedfiles) {
300                 return "<span><a href=\"".
301                         cgiurl(do => "create", page => $link, from => $page).
302                         "\">?</a>$linktext</span>"
303         }
304         
305         require File::Spec;
306         $bestlink=File::Spec->abs2rel($bestlink, dirname($page));
307         
308         if (! $noimageinline && isinlinableimage($bestlink)) {
309                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
310         }
311         return "<a href=\"$bestlink\">$linktext</a>";
312 } #}}}
313
314 sub indexlink () { #{{{
315         return "<a href=\"$config{url}\">$config{wikiname}</a>";
316 } #}}}
317
318 sub lockwiki () { #{{{
319         # Take an exclusive lock on the wiki to prevent multiple concurrent
320         # run issues. The lock will be dropped on program exit.
321         if (! -d $config{wikistatedir}) {
322                 mkdir($config{wikistatedir});
323         }
324         open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
325                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
326         if (! flock(WIKILOCK, 2 | 4)) {
327                 debug("wiki seems to be locked, waiting for lock");
328                 my $wait=600; # arbitrary, but don't hang forever to 
329                               # prevent process pileup
330                 for (1..600) {
331                         return if flock(WIKILOCK, 2 | 4);
332                         sleep 1;
333                 }
334                 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
335         }
336 } #}}}
337
338 sub unlockwiki () { #{{{
339         close WIKILOCK;
340 } #}}}
341
342 sub loadindex () { #{{{
343         open (IN, "$config{wikistatedir}/index") || return;
344         while (<IN>) {
345                 $_=possibly_foolish_untaint($_);
346                 chomp;
347                 my %items;
348                 $items{link}=[];
349                 foreach my $i (split(/ /, $_)) {
350                         my ($item, $val)=split(/=/, $i, 2);
351                         push @{$items{$item}}, $val;
352                 }
353
354                 next unless exists $items{src}; # skip bad lines for now
355
356                 my $page=pagename($items{src}[0]);
357                 if (! $config{rebuild}) {
358                         $pagesources{$page}=$items{src}[0];
359                         $oldpagemtime{$page}=$items{mtime}[0];
360                         $oldlinks{$page}=[@{$items{link}}];
361                         $links{$page}=[@{$items{link}}];
362                         $depends{$page}=join(" ", @{$items{depends}})
363                                 if exists $items{depends};
364                         $renderedfiles{$page}=$items{dest}[0];
365                 }
366                 $pagectime{$page}=$items{ctime}[0];
367         }
368         close IN;
369 } #}}}
370
371 sub saveindex () { #{{{
372         if (! -d $config{wikistatedir}) {
373                 mkdir($config{wikistatedir});
374         }
375         open (OUT, ">$config{wikistatedir}/index") || 
376                 error("cannot write to $config{wikistatedir}/index: $!");
377         foreach my $page (keys %oldpagemtime) {
378                 next unless $oldpagemtime{$page};
379                 my $line="mtime=$oldpagemtime{$page} ".
380                         "ctime=$pagectime{$page} ".
381                         "src=$pagesources{$page} ".
382                         "dest=$renderedfiles{$page}";
383                 $line.=" link=$_" foreach @{$links{$page}};
384                 if (exists $depends{$page}) {
385                         $line.=" depends=$_" foreach split " ", $depends{$page};
386                 }
387                 print OUT $line."\n";
388         }
389         close OUT;
390 } #}}}
391
392 sub template_params (@) { #{{{
393         my $filename=shift;
394         
395         require Encode;
396         require HTML::Template;
397         return filter => \&Encode::decode_utf8,
398                 filename => "$config{templatedir}/$filename", @_;
399 } #}}}
400
401 sub template ($;@) { #{{{
402         HTML::Template->new(template_params(@_));
403 } #}}}
404
405 sub misctemplate ($$) { #{{{
406         my $title=shift;
407         my $pagebody=shift;
408         
409         my $template=template("misc.tmpl");
410         $template->param(
411                 title => $title,
412                 indexlink => indexlink(),
413                 wikiname => $config{wikiname},
414                 pagebody => $pagebody,
415                 styleurl => styleurl(),
416                 baseurl => "$config{url}/",
417         );
418         return $template->output;
419 }#}}}
420
421 sub glob_match ($$) { #{{{
422         my $page=shift;
423         my $glob=shift;
424
425         if ($glob =~ /^link\((.+)\)$/) {
426                 my $rev = $links{$page} or return undef;
427                 foreach my $p (@$rev) {
428                         return 1 if lc $p eq $1;
429                 }
430                 return 0;
431         } elsif ($glob =~ /^backlink\((.+)\)$/) {
432                 my $rev = $links{$1} or return undef;
433                 foreach my $p (@$rev) {
434                         return 1 if lc $p eq $page;
435                 }
436                 return 0;
437         } else {
438                 # turn glob into safe regexp
439                 $glob=quotemeta($glob);
440                 $glob=~s/\\\*/.*/g;
441                 $glob=~s/\\\?/./g;
442                 $glob=~s!\\/!/!g;
443                 
444                 return $page=~/^$glob$/i;
445         }
446 } #}}}
447
448 sub globlist_match ($$) { #{{{
449         my $page=shift;
450         my @globlist=split(" ", shift);
451
452         # check any negated globs first
453         foreach my $glob (@globlist) {
454                 return 0 if $glob=~/^!(.*)/ && glob_match($page, $1);
455         }
456
457         foreach my $glob (@globlist) {
458                 return 1 if glob_match($page, $glob);
459         }
460         
461         return 0;
462 } #}}}
463
464 sub hook (@) { # {{{
465         my %param=@_;
466         
467         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
468                 error "hook requires type, call, and id parameters";
469         }
470         
471         $hooks{$param{type}}{$param{id}}=\%param;
472 } # }}}
473
474 1