* Display an error message if /usr/bin/markdown can't be loaded.
[ikiwiki] / 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/|\.\.|^\.|\/\.|\.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=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                 loop_context_vars => 1,
437                 @_;
438 } #}}}
439
440 sub template ($;@) { #{{{
441         HTML::Template->new(template_params(@_));
442 } #}}}
443
444 sub misctemplate ($$) { #{{{
445         my $title=shift;
446         my $pagebody=shift;
447         
448         my $template=template("misc.tmpl");
449         $template->param(
450                 title => $title,
451                 indexlink => indexlink(),
452                 wikiname => $config{wikiname},
453                 pagebody => $pagebody,
454                 styleurl => styleurl(),
455                 baseurl => "$config{url}/",
456         );
457         return $template->output;
458 }#}}}
459
460 sub hook (@) { # {{{
461         my %param=@_;
462         
463         if (! exists $param{type} || ! ref $param{call} || ! exists $param{id}) {
464                 error "hook requires type, call, and id parameters";
465         }
466         
467         $hooks{$param{type}}{$param{id}}=\%param;
468 } # }}}
469
470 sub run_hooks ($$) { # {{{
471         # Calls the given sub for each hook of the given type,
472         # passing it the hook function to call.
473         my $type=shift;
474         my $sub=shift;
475
476         if (exists $hooks{$type}) {
477                 foreach my $id (keys %{$hooks{$type}}) {
478                         $sub->($hooks{$type}{$id}{call});
479                 }
480         }
481 } #}}}
482
483 sub globlist_to_pagespec ($) { #{{{
484         my @globlist=split(' ', shift);
485
486         my (@spec, @skip);
487         foreach my $glob (@globlist) {
488                 if ($glob=~/^!(.*)/) {
489                         push @skip, $glob;
490                 }
491                 else {
492                         push @spec, $glob;
493                 }
494         }
495
496         my $spec=join(" or ", @spec);
497         if (@skip) {
498                 my $skip=join(" and ", @skip);
499                 if (length $spec) {
500                         $spec="$skip and ($spec)";
501                 }
502                 else {
503                         $spec=$skip;
504                 }
505         }
506         return $spec;
507 } #}}}
508
509 sub is_globlist ($) { #{{{
510         my $s=shift;
511         $s=~/[^\s]+\s+([^\s]+)/ && $1 ne "and" && $1 ne "or";
512 } #}}}
513
514 sub safequote ($) { #{{{
515         my $s=shift;
516         $s=~s/[{}]//g;
517         return "q{$s}";
518 } #}}}
519
520 sub pagespec_merge ($$) { #{{{
521         my $a=shift;
522         my $b=shift;
523
524         # Support for old-style GlobLists.
525         if (is_globlist($a)) {
526                 $a=globlist_to_pagespec($a);
527         }
528         if (is_globlist($b)) {
529                 $b=globlist_to_pagespec($b);
530         }
531
532         return "($a) or ($b)";
533 } #}}}
534
535 sub pagespec_translate ($) { #{{{
536         # This assumes that $page is in scope in the function
537         # that evalulates the translated pagespec code.
538         my $spec=shift;
539
540         # Support for old-style GlobLists.
541         if (is_globlist($spec)) {
542                 $spec=globlist_to_pagespec($spec);
543         }
544
545         # Convert spec to perl code.
546         my $code="";
547         while ($spec=~m/\s*(\!|\(|\)|\w+\([^\)]+\)|[^\s()]+)\s*/ig) {
548                 my $word=$1;
549                 if (lc $word eq "and") {
550                         $code.=" &&";
551                 }
552                 elsif (lc $word eq "or") {
553                         $code.=" ||";
554                 }
555                 elsif ($word eq "(" || $word eq ")" || $word eq "!") {
556                         $code.=" ".$word;
557                 }
558                 elsif ($word =~ /^(link|backlink|created_before|created_after|creation_month|creation_year|creation_day)\((.+)\)$/) {
559                         $code.=" match_$1(\$page, ".safequote($2).")";
560                 }
561                 else {
562                         $code.=" match_glob(\$page, ".safequote($word).")";
563                 }
564         }
565
566         return $code;
567 } #}}}
568
569 sub pagespec_match ($$) { #{{{
570         my $page=shift;
571         my $spec=shift;
572
573         return eval pagespec_translate($spec);
574 } #}}}
575
576 sub match_glob ($$) { #{{{
577         my $page=shift;
578         my $glob=shift;
579
580         # turn glob into safe regexp
581         $glob=quotemeta($glob);
582         $glob=~s/\\\*/.*/g;
583         $glob=~s/\\\?/./g;
584
585         return $page=~/^$glob$/i;
586 } #}}}
587
588 sub match_link ($$) { #{{{
589         my $page=shift;
590         my $link=shift;
591
592         my $links = $links{$page} or return undef;
593         foreach my $p (@$links) {
594                 return 1 if lc $p eq $link;
595         }
596         return 0;
597 } #}}}
598
599 sub match_backlink ($$) { #{{{
600         match_link(pop, pop);
601 } #}}}
602
603 sub match_created_before ($$) { #{{{
604         my $page=shift;
605         my $testpage=shift;
606
607         if (exists $pagectime{$testpage}) {
608                 return $pagectime{$page} < $pagectime{$testpage};
609         }
610         else {
611                 return 0;
612         }
613 } #}}}
614
615 sub match_created_after ($$) { #{{{
616         my $page=shift;
617         my $testpage=shift;
618
619         if (exists $pagectime{$testpage}) {
620                 return $pagectime{$page} > $pagectime{$testpage};
621         }
622         else {
623                 return 0;
624         }
625 } #}}}
626
627 sub match_creation_day ($$) { #{{{
628         return ((gmtime($pagectime{shift()}))[3] == shift);
629 } #}}}
630
631 sub match_creation_month ($$) { #{{{
632         return ((gmtime($pagectime{shift()}))[4] + 1 == shift);
633 } #}}}
634
635 sub match_creation_year ($$) { #{{{
636         return ((gmtime($pagectime{shift()}))[5] + 1900 == shift);
637 } #}}}
638
639 1