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