]> sipb.mit.edu Git - ikiwiki.git/blob - IkiWiki.pm
560647e067f224bd62d2c9cd49b9c17359933b9f
[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_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=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                         return $l;
251                 }
252                 elsif (exists $pagecase{lc $l}) {
253                         return $pagecase{lc $l};
254                 }
255         } while $cwd=~s!/?[^/]+$!!;
256
257         #print STDERR "warning: page $page, broken link: $link\n";
258         return "";
259 } #}}}
260
261 sub isinlinableimage ($) { #{{{
262         my $file=shift;
263         
264         $file=~/\.(png|gif|jpg|jpeg)$/i;
265 } #}}}
266
267 sub pagetitle ($) { #{{{
268         my $page=shift;
269         $page=~s/__(\d+)__/&#$1;/g;
270         $page=~y/_/ /;
271         return $page;
272 } #}}}
273
274 sub titlepage ($) { #{{{
275         my $title=shift;
276         $title=~y/ /_/;
277         $title=~s/([^-[:alnum:]_:+\/.])/"__".ord($1)."__"/eg;
278         return $title;
279 } #}}}
280
281 sub cgiurl (@) { #{{{
282         my %params=@_;
283
284         return $config{cgiurl}."?".join("&amp;", map "$_=$params{$_}", keys %params);
285 } #}}}
286
287 sub styleurl (;$) { #{{{
288         my $page=shift;
289
290         return "$config{url}/style.css" if ! defined $page;
291         
292         $page=~s/[^\/]+$//;
293         $page=~s/[^\/]+\//..\//g;
294         return $page."style.css";
295 } #}}}
296
297 sub abs2rel ($$) { #{{{
298         # Work around very innefficient behavior in File::Spec if abs2rel
299         # is passed two relative paths. It's much faster if paths are
300         # absolute!
301         my $path="/".shift;
302         my $base="/".shift;
303
304         require File::Spec;
305         my $ret=File::Spec->abs2rel($path, $base);
306         $ret=~s/^// if defined $ret;
307         return $ret;
308 } #}}}
309
310 sub htmllink ($$$;$$$) { #{{{
311         my $lpage=shift; # the page doing the linking
312         my $page=shift; # the page that will contain the link (different for inline)
313         my $link=shift;
314         my $noimageinline=shift; # don't turn links into inline html images
315         my $forcesubpage=shift; # force a link to a subpage
316         my $linktext=shift; # set to force the link text to something
317
318         my $bestlink;
319         if (! $forcesubpage) {
320                 $bestlink=bestlink($lpage, $link);
321         }
322         else {
323                 $bestlink="$lpage/".lc($link);
324         }
325
326         $linktext=pagetitle(basename($link)) unless defined $linktext;
327         
328         return $linktext if length $bestlink && $page eq $bestlink;
329         
330         # TODO BUG: %renderedfiles may not have it, if the linked to page
331         # was also added and isn't yet rendered! Note that this bug is
332         # masked by the bug that makes all new files be rendered twice.
333         if (! grep { $_ eq $bestlink } values %renderedfiles) {
334                 $bestlink=htmlpage($bestlink);
335         }
336         if (! grep { $_ eq $bestlink } values %renderedfiles) {
337                 return "<span><a href=\"".
338                         cgiurl(do => "create", page => lc($link), from => $page).
339                         "\">?</a>$linktext</span>"
340         }
341         
342         $bestlink=abs2rel($bestlink, dirname($page));
343         
344         if (! $noimageinline && isinlinableimage($bestlink)) {
345                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
346         }
347         return "<a href=\"$bestlink\">$linktext</a>";
348 } #}}}
349
350 sub indexlink () { #{{{
351         return "<a href=\"$config{url}\">$config{wikiname}</a>";
352 } #}}}
353
354 sub lockwiki () { #{{{
355         # Take an exclusive lock on the wiki to prevent multiple concurrent
356         # run issues. The lock will be dropped on program exit.
357         if (! -d $config{wikistatedir}) {
358                 mkdir($config{wikistatedir});
359         }
360         open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
361                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
362         if (! flock(WIKILOCK, 2 | 4)) {
363                 debug("wiki seems to be locked, waiting for lock");
364                 my $wait=600; # arbitrary, but don't hang forever to 
365                               # prevent process pileup
366                 for (1..600) {
367                         return if flock(WIKILOCK, 2 | 4);
368                         sleep 1;
369                 }
370                 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
371         }
372 } #}}}
373
374 sub unlockwiki () { #{{{
375         close WIKILOCK;
376 } #}}}
377
378 sub loadindex () { #{{{
379         open (IN, "$config{wikistatedir}/index") || return;
380         while (<IN>) {
381                 $_=possibly_foolish_untaint($_);
382                 chomp;
383                 my %items;
384                 $items{link}=[];
385                 foreach my $i (split(/ /, $_)) {
386                         my ($item, $val)=split(/=/, $i, 2);
387                         push @{$items{$item}}, decode_entities($val);
388                 }
389
390                 next unless exists $items{src}; # skip bad lines for now
391
392                 my $page=pagename($items{src}[0]);
393                 if (! $config{rebuild}) {
394                         $pagesources{$page}=$items{src}[0];
395                         $oldpagemtime{$page}=$items{mtime}[0];
396                         $oldlinks{$page}=[@{$items{link}}];
397                         $links{$page}=[@{$items{link}}];
398                         $depends{$page}=$items{depends}[0] if exists $items{depends};
399                         $renderedfiles{$page}=$items{dest}[0];
400                         $pagecase{lc $page}=$page;
401                 }
402                 $pagectime{$page}=$items{ctime}[0];
403         }
404         close IN;
405 } #}}}
406
407 sub saveindex () { #{{{
408         run_hooks(savestate => sub { shift->() });
409
410         if (! -d $config{wikistatedir}) {
411                 mkdir($config{wikistatedir});
412         }
413         open (OUT, ">$config{wikistatedir}/index") || 
414                 error("cannot write to $config{wikistatedir}/index: $!");
415         foreach my $page (keys %oldpagemtime) {
416                 next unless $oldpagemtime{$page};
417                 my $line="mtime=$oldpagemtime{$page} ".
418                         "ctime=$pagectime{$page} ".
419                         "src=$pagesources{$page} ".
420                         "dest=$renderedfiles{$page}";
421                 $line.=" link=$_" foreach @{$links{$page}};
422                 if (exists $depends{$page}) {
423                         $line.=" depends=".encode_entities($depends{$page}, " \t\n");
424                 }
425                 print OUT $line."\n";
426         }
427         close OUT;
428 } #}}}
429
430 sub template_params (@) { #{{{
431         my $filename=shift;
432         
433         require HTML::Template;
434         return filter => sub {
435                         my $text_ref = shift;
436                         $$text_ref=&Encode::decode_utf8($$text_ref);
437                 },
438                 filename => "$config{templatedir}/$filename",
439                 loop_context_vars => 1,
440                 die_on_bad_params => 0,
441                 @_;
442 } #}}}
443
444 sub template ($;@) { #{{{
445         HTML::Template->new(template_params(@_));
446 } #}}}
447
448 sub misctemplate ($$) { #{{{
449         my $title=shift;
450         my $pagebody=shift;
451         
452         my $template=template("misc.tmpl");
453         $template->param(
454                 title => $title,
455                 indexlink => indexlink(),
456                 wikiname => $config{wikiname},
457                 pagebody => $pagebody,
458                 styleurl => styleurl(),
459                 baseurl => "$config{url}/",
460         );
461         return $template->output;
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 sub run_hooks ($$) { # {{{
475         # Calls the given sub for each hook of the given type,
476         # passing it the hook function to call.
477         my $type=shift;
478         my $sub=shift;
479
480         if (exists $hooks{$type}) {
481                 foreach my $id (keys %{$hooks{$type}}) {
482                         $sub->($hooks{$type}{$id}{call});
483                 }
484         }
485 } #}}}
486
487 sub globlist_to_pagespec ($) { #{{{
488         my @globlist=split(' ', shift);
489
490         my (@spec, @skip);
491         foreach my $glob (@globlist) {
492                 if ($glob=~/^!(.*)/) {
493                         push @skip, $glob;
494                 }
495                 else {
496                         push @spec, $glob;
497                 }
498         }
499
500         my $spec=join(" or ", @spec);
501         if (@skip) {
502                 my $skip=join(" and ", @skip);
503                 if (length $spec) {
504                         $spec="$skip and ($spec)";
505                 }
506                 else {
507                         $spec=$skip;
508                 }
509         }
510         return $spec;
511 } #}}}
512
513 sub is_globlist ($) { #{{{
514         my $s=shift;
515         $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
516 } #}}}
517
518 sub safequote ($) { #{{{
519         my $s=shift;
520         $s=~s/[{}]//g;
521         return "q{$s}";
522 } #}}}
523
524 sub pagespec_merge ($$) { #{{{
525         my $a=shift;
526         my $b=shift;
527
528         # Support for old-style GlobLists.
529         if (is_globlist($a)) {
530                 $a=globlist_to_pagespec($a);
531         }
532         if (is_globlist($b)) {
533                 $b=globlist_to_pagespec($b);
534         }
535
536         return "($a) or ($b)";
537 } #}}}
538
539 sub pagespec_translate ($) { #{{{
540         # This assumes that $page is in scope in the function
541         # that evalulates the translated pagespec code.
542         my $spec=shift;
543
544         # Support for old-style GlobLists.
545         if (is_globlist($spec)) {
546                 $spec=globlist_to_pagespec($spec);
547         }
548
549         # Convert spec to perl code.
550         my $code="";
551         while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
552                 my $word=$1;
553                 if (lc $word eq "and") {
554                         $code.=" &&";
555                 }
556                 elsif (lc $word eq "or") {
557                         $code.=" ||";
558                 }
559                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
560                         $code.=" ".$word;
561                 }
562                 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
563                         $code.=" match_$1(\$page, ".safequote($2).")";
564                 }
565                 else {
566                         $code.=" match_glob(\$page, ".safequote($word).")";
567                 }
568         }
569
570         return $code;
571 } #}}}
572
573 sub pagespec_match ($$) { #{{{
574         my $page=shift;
575         my $spec=shift;
576
577         return eval pagespec_translate($spec);
578 } #}}}
579
580 sub match_glob ($$) { #{{{
581         my $page=shift;
582         my $glob=shift;
583
584         # turn glob into safe regexp
585         $glob=quotemeta($glob);
586         $glob=~s/\\\*/.*/g;
587         $glob=~s/\\\?/./g;
588
589         return $page=~/^$glob$/i;
590 } #}}}
591
592 sub match_link ($$) { #{{{
593         my $page=shift;
594         my $link=lc(shift);
595
596         my $links = $links{$page} or return undef;
597         foreach my $p (@$links) {
598                 return 1 if lc $p eq $link;
599         }
600         return 0;
601 } #}}}
602
603 sub match_backlink ($$) { #{{{
604         match_link(pop, pop);
605 } #}}}
606
607 sub match_created_before ($$) { #{{{
608         my $page=shift;
609         my $testpage=shift;
610
611         if (exists $pagectime{$testpage}) {
612                 return $pagectime{$page} < $pagectime{$testpage};
613         }
614         else {
615                 return 0;
616         }
617 } #}}}
618
619 sub match_created_after ($$) { #{{{
620         my $page=shift;
621         my $testpage=shift;
622
623         if (exists $pagectime{$testpage}) {
624                 return $pagectime{$page} > $pagectime{$testpage};
625         }
626         else {
627                 return 0;
628         }
629 } #}}}
630
631 sub match_creation_day ($$) { #{{{
632         return ((gmtime($pagectime{shift()}))[3] == shift);
633 } #}}}
634
635 sub match_creation_month ($$) { #{{{
636         return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
637 } #}}}
638
639 sub match_creation_year ($$) { #{{{
640         return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);
641 } #}}}
642
643 1