]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki.pm
b9ae74f854dab240c5e563be920d9947bad48f23
[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 %pagecase
16             %renderedfiles %pagesources %depends %hooks %forcerebuild};
17
18 sub defaultconfig () { #{{{
19         wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.x?html?$|\.rss$)},
20         wiki_link_regexp => qr/\[\[(?:([^\]\|]+)\|)?([^\s\]]+)\]\]/,
21         wiki_file_regexp => qr/(^[-[:alnum:]_.:\/+]+$)/,
22         verbose => 0,
23         syslog => 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         log_message(error => @_);
123         exit(1);
124 } #}}}
125
126 sub debug ($) { #{{{
127         return unless $config{verbose};
128         log_message(debug => @_);
129 } #}}}
130
131 my $log_open=0;
132 sub log_message ($$) { #{{{
133         my $type=shift;
134
135         if ($config{syslog}) {
136                 require Sys::Syslog;
137                 unless ($log_open) {
138                         Sys::Syslog::setlogsock('unix');
139                         Sys::Syslog::openlog('ikiwiki', '', 'user');
140                         $log_open=1;
141                 }
142                 eval {
143                         Sys::Syslog::syslog($type, join(" ", @_));
144                 }
145         }
146         elsif (! $config{cgi}) {
147                 print "@_\n";
148         }
149         else {
150                 print STDERR "@_\n";
151         }
152 } #}}}
153
154 sub possibly_foolish_untaint ($) { #{{{
155         my $tainted=shift;
156         my ($untainted)=$tainted=~/(.*)/;
157         return $untainted;
158 } #}}}
159
160 sub basename ($) { #{{{
161         my $file=shift;
162
163         $file=~s!.*/+!!;
164         return $file;
165 } #}}}
166
167 sub dirname ($) { #{{{
168         my $file=shift;
169
170         $file=~s!/*[^/]+$!!;
171         return $file;
172 } #}}}
173
174 sub pagetype ($) { #{{{
175         my $page=shift;
176         
177         if ($page =~ /\.([^.]+)$/) {
178                 return $1 if exists $hooks{htmlize}{$1};
179         }
180         return undef;
181 } #}}}
182
183 sub pagename ($) { #{{{
184         my $file=shift;
185
186         my $type=pagetype($file);
187         my $page=$file;
188         $page=~s/\Q.$type\E*$// if defined $type;
189         return $page;
190 } #}}}
191
192 sub htmlpage ($) { #{{{
193         my $page=shift;
194
195         return $page.".html";
196 } #}}}
197
198 sub srcfile ($) { #{{{
199         my $file=shift;
200
201         return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
202         return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
203         error("internal error: $file cannot be found");
204 } #}}}
205
206 sub readfile ($;$) { #{{{
207         my $file=shift;
208         my $binary=shift;
209
210         if (-l $file) {
211                 error("cannot read a symlink ($file)");
212         }
213         
214         local $/=undef;
215         open (IN, $file) || error("failed to read $file: $!");
216         binmode(IN) if ($binary);
217         my $ret=<IN>;
218         close IN;
219         return $ret;
220 } #}}}
221
222 sub writefile ($$$;$) { #{{{
223         my $file=shift; # can include subdirs
224         my $destdir=shift; # directory to put file in
225         my $content=shift;
226         my $binary=shift;
227         
228         my $test=$file;
229         while (length $test) {
230                 if (-l "$destdir/$test") {
231                         error("cannot write to a symlink ($test)");
232                 }
233                 $test=dirname($test);
234         }
235
236         my $dir=dirname("$destdir/$file");
237         if (! -d $dir) {
238                 my $d="";
239                 foreach my $s (split(m!/+!, $dir)) {
240                         $d.="$s/";
241                         if (! -d $d) {
242                                 mkdir($d) || error("failed to create directory $d: $!");
243                         }
244                 }
245         }
246         
247         open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
248         binmode(OUT) if ($binary);
249         print OUT $content;
250         close OUT;
251 } #}}}
252
253 sub bestlink ($$) { #{{{
254         # Given a page and the text of a link on the page, determine which
255         # existing page that link best points to. Prefers pages under a
256         # subdirectory with the same name as the source page, failing that
257         # goes down the directory tree to the base looking for matching
258         # pages.
259         my $page=shift;
260         my $link=shift;
261         
262         my $cwd=$page;
263         do {
264                 my $l=$cwd;
265                 $l.="/" if length $l;
266                 $l.=$link;
267
268                 if (exists $links{$l}) {
269                         return $l;
270                 }
271                 elsif (exists $pagecase{lc $l}) {
272                         return $pagecase{lc $l};
273                 }
274         } while $cwd=~s!/?[^/]+$!!;
275
276         #print STDERR "warning: page $page, broken link: $link\n";
277         return "";
278 } #}}}
279
280 sub isinlinableimage ($) { #{{{
281         my $file=shift;
282         
283         $file=~/\.(png|gif|jpg|jpeg)$/i;
284 } #}}}
285
286 sub pagetitle ($) { #{{{
287         my $page=shift;
288         $page=~s/__(\d+)__/&#$1;/g;
289         $page=~y/_/ /;
290         return $page;
291 } #}}}
292
293 sub titlepage ($) { #{{{
294         my $title=shift;
295         $title=~y/ /_/;
296         $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
297         return $title;
298 } #}}}
299
300 sub cgiurl (@) { #{{{
301         my %params=@_;
302
303         return $config{cgiurl}."?".join("&amp;", map "$_=$params{$_}", keys %params);
304 } #}}}
305
306 sub baseurl (;$) { #{{{
307         my $page=shift;
308
309         return "$config{url}/" if ! defined $page;
310         
311         $page=~s/[^\/]+$//;
312         $page=~s/[^\/]+\//..\//g;
313         return $page;
314 } #}}}
315
316 sub abs2rel ($$) { #{{{
317         # Work around very innefficient behavior in File::Spec if abs2rel
318         # is passed two relative paths. It's much faster if paths are
319         # absolute!
320         my $path="/".shift;
321         my $base="/".shift;
322
323         require File::Spec;
324         my $ret=File::Spec->abs2rel($path, $base);
325         $ret=~s/^// if defined $ret;
326         return $ret;
327 } #}}}
328
329 sub htmllink ($$$;$$$) { #{{{
330         my $lpage=shift; # the page doing the linking
331         my $page=shift; # the page that will contain the link (different for inline)
332         my $link=shift;
333         my $noimageinline=shift; # don't turn links into inline html images
334         my $forcesubpage=shift; # force a link to a subpage
335         my $linktext=shift; # set to force the link text to something
336
337         my $bestlink;
338         if (! $forcesubpage) {
339                 $bestlink=bestlink($lpage, $link);
340         }
341         else {
342                 $bestlink="$lpage/".lc($link);
343         }
344
345         $linktext=pagetitle(basename($link)) unless defined $linktext;
346         
347         return "<span class=\"selflink\">$linktext</span>"
348                 if length $bestlink && $page eq $bestlink;
349         
350         # TODO BUG: %renderedfiles may not have it, if the linked to page
351         # was also added and isn't yet rendered! Note that this bug is
352         # masked by the bug that makes all new files be rendered twice.
353         if (! grep { $_ eq $bestlink } values %renderedfiles) {
354                 $bestlink=htmlpage($bestlink);
355         }
356         if (! grep { $_ eq $bestlink } values %renderedfiles) {
357                 return "<span><a href=\"".
358                         cgiurl(do => "create", page => lc($link), from => $page).
359                         "\">?</a>$linktext</span>"
360         }
361         
362         $bestlink=abs2rel($bestlink, dirname($page));
363         
364         if (! $noimageinline && isinlinableimage($bestlink)) {
365                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
366         }
367         return "<a href=\"$bestlink\">$linktext</a>";
368 } #}}}
369
370 sub indexlink () { #{{{
371         return "<a href=\"$config{url}\">$config{wikiname}</a>";
372 } #}}}
373
374 sub lockwiki () { #{{{
375         # Take an exclusive lock on the wiki to prevent multiple concurrent
376         # run issues. The lock will be dropped on program exit.
377         if (! -d $config{wikistatedir}) {
378                 mkdir($config{wikistatedir});
379         }
380         open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
381                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
382         if (! flock(WIKILOCK, 2 | 4)) {
383                 debug("wiki seems to be locked, waiting for lock");
384                 my $wait=600; # arbitrary, but don't hang forever to 
385                               # prevent process pileup
386                 for (1..600) {
387                         return if flock(WIKILOCK, 2 | 4);
388                         sleep 1;
389                 }
390                 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
391         }
392 } #}}}
393
394 sub unlockwiki () { #{{{
395         close WIKILOCK;
396 } #}}}
397
398 sub loadindex () { #{{{
399         open (IN, "$config{wikistatedir}/index") || return;
400         while (<IN>) {
401                 $_=possibly_foolish_untaint($_);
402                 chomp;
403                 my %items;
404                 $items{link}=[];
405                 foreach my $i (split(/ /, $_)) {
406                         my ($item, $val)=split(/=/, $i, 2);
407                         push @{$items{$item}}, decode_entities($val);
408                 }
409
410                 next unless exists $items{src}; # skip bad lines for now
411
412                 my $page=pagename($items{src}[0]);
413                 if (! $config{rebuild}) {
414                         $pagesources{$page}=$items{src}[0];
415                         $oldpagemtime{$page}=$items{mtime}[0];
416                         $oldlinks{$page}=[@{$items{link}}];
417                         $links{$page}=[@{$items{link}}];
418                         $depends{$page}=$items{depends}[0] if exists $items{depends};
419                         $renderedfiles{$page}=$items{dest}[0];
420                         $pagecase{lc $page}=$page;
421                 }
422                 $pagectime{$page}=$items{ctime}[0];
423         }
424         close IN;
425 } #}}}
426
427 sub saveindex () { #{{{
428         run_hooks(savestate => sub { shift->() });
429
430         if (! -d $config{wikistatedir}) {
431                 mkdir($config{wikistatedir});
432         }
433         open (OUT, ">$config{wikistatedir}/index") || 
434                 error("cannot write to $config{wikistatedir}/index: $!");
435         foreach my $page (keys %oldpagemtime) {
436                 next unless $oldpagemtime{$page};
437                 my $line="mtime=$oldpagemtime{$page} ".
438                         "ctime=$pagectime{$page} ".
439                         "src=$pagesources{$page} ".
440                         "dest=$renderedfiles{$page}";
441                 $line.=" link=$_" foreach @{$links{$page}};
442                 if (exists $depends{$page}) {
443                         $line.=" depends=".encode_entities($depends{$page}, " \t\n");
444                 }
445                 print OUT $line."\n";
446         }
447         close OUT;
448 } #}}}
449
450 sub template_params (@) { #{{{
451         my $filename=shift;
452         
453         require HTML::Template;
454         return filter => sub {
455                         my $text_ref = shift;
456                         $$text_ref=&Encode::decode_utf8($$text_ref);
457                 },
458                 filename => "$config{templatedir}/$filename",
459                 loop_context_vars => 1,
460                 die_on_bad_params => 0,
461                 @_;
462 } #}}}
463
464 sub template ($;@) { #{{{
465         HTML::Template->new(template_params(@_));
466 } #}}}
467
468 sub misctemplate ($$) { #{{{
469         my $title=shift;
470         my $pagebody=shift;
471         
472         my $template=template("misc.tmpl");
473         $template->param(
474                 title => $title,
475                 indexlink => indexlink(),
476                 wikiname => $config{wikiname},
477                 pagebody => $pagebody,
478                 baseurl => baseurl(),
479         );
480         return $template->output;
481 }#}}}
482
483 sub hook (@) { # {{{
484         my %param=@_;
485         
486         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
487                 error "hook requires type, call, and id parameters";
488         }
489         
490         $hooks{$param{type}}{$param{id}}=\%param;
491 } # }}}
492
493 sub run_hooks ($$) { # {{{
494         # Calls the given sub for each hook of the given type,
495         # passing it the hook function to call.
496         my $type=shift;
497         my $sub=shift;
498
499         if (exists $hooks{$type}) {
500                 foreach my $id (keys %{$hooks{$type}}) {
501                         $sub->($hooks{$type}{$id}{call});
502                 }
503         }
504 } #}}}
505
506 sub globlist_to_pagespec ($) { #{{{
507         my @globlist=split(' ', shift);
508
509         my (@spec, @skip);
510         foreach my $glob (@globlist) {
511                 if ($glob=~/^!(.*)/) {
512                         push @skip, $glob;
513                 }
514                 else {
515                         push @spec, $glob;
516                 }
517         }
518
519         my $spec=join(" or ", @spec);
520         if (@skip) {
521                 my $skip=join(" and ", @skip);
522                 if (length $spec) {
523                         $spec="$skip and ($spec)";
524                 }
525                 else {
526                         $spec=$skip;
527                 }
528         }
529         return $spec;
530 } #}}}
531
532 sub is_globlist ($) { #{{{
533         my $s=shift;
534         $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
535 } #}}}
536
537 sub safequote ($) { #{{{
538         my $s=shift;
539         $s=~s/[{}]//g;
540         return "q{$s}";
541 } #}}}
542
543 sub pagespec_merge ($$) { #{{{
544         my $a=shift;
545         my $b=shift;
546
547         # Support for old-style GlobLists.
548         if (is_globlist($a)) {
549                 $a=globlist_to_pagespec($a);
550         }
551         if (is_globlist($b)) {
552                 $b=globlist_to_pagespec($b);
553         }
554
555         return "($a) or ($b)";
556 } #}}}
557
558 sub pagespec_translate ($) { #{{{
559         # This assumes that $page is in scope in the function
560         # that evalulates the translated pagespec code.
561         my $spec=shift;
562
563         # Support for old-style GlobLists.
564         if (is_globlist($spec)) {
565                 $spec=globlist_to_pagespec($spec);
566         }
567
568         # Convert spec to perl code.
569         my $code="";
570         while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
571                 my $word=$1;
572                 if (lc $word eq "and") {
573                         $code.=" &&";
574                 }
575                 elsif (lc $word eq "or") {
576                         $code.=" ||";
577                 }
578                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
579                         $code.=" ".$word;
580                 }
581                 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
582                         $code.=" match_$1(\$page, ".safequote($2).")";
583                 }
584                 else {
585                         $code.=" match_glob(\$page, ".safequote($word).")";
586                 }
587         }
588
589         return $code;
590 } #}}}
591
592 sub pagespec_match ($$) { #{{{
593         my $page=shift;
594         my $spec=shift;
595
596         return eval pagespec_translate($spec);
597 } #}}}
598
599 sub match_glob ($$) { #{{{
600         my $page=shift;
601         my $glob=shift;
602
603         # turn glob into safe regexp
604         $glob=quotemeta($glob);
605         $glob=~s/\\\*/.*/g;
606         $glob=~s/\\\?/./g;
607
608         return $page=~/^$glob$/i;
609 } #}}}
610
611 sub match_link ($$) { #{{{
612         my $page=shift;
613         my $link=lc(shift);
614
615         my $links = $links{$page} or return undef;
616         foreach my $p (@$links) {
617                 return 1 if lc $p eq $link;
618         }
619         return 0;
620 } #}}}
621
622 sub match_backlink ($$) { #{{{
623         match_link(pop, pop);
624 } #}}}
625
626 sub match_created_before ($$) { #{{{
627         my $page=shift;
628         my $testpage=shift;
629
630         if (exists $pagectime{$testpage}) {
631                 return $pagectime{$page} < $pagectime{$testpage};
632         }
633         else {
634                 return 0;
635         }
636 } #}}}
637
638 sub match_created_after ($$) { #{{{
639         my $page=shift;
640         my $testpage=shift;
641
642         if (exists $pagectime{$testpage}) {
643                 return $pagectime{$page} > $pagectime{$testpage};
644         }
645         else {
646                 return 0;
647         }
648 } #}}}
649
650 sub match_creation_day ($$) { #{{{
651         return ((gmtime($pagectime{shift()}))[3] == shift);
652 } #}}}
653
654 sub match_creation_month ($$) { #{{{
655         return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
656 } #}}}
657
658 sub match_creation_year ($$) { #{{{
659         return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);
660 } #}}}
661
662 1