added --hyperestraier switch, which turns on search support
[ikiwiki] / ikiwiki
1 #!/usr/bin/perl -T
2 $ENV{PATH}="/usr/local/bin:/usr/bin:/bin";
3
4 package IkiWiki;
5 use warnings;
6 use strict;
7 use File::Spec;
8 use HTML::Template;
9 use lib '.'; # For use without installation, removed by Makefile.
10
11 use vars qw{%config %links %oldlinks %oldpagemtime %pagectime
12             %renderedfiles %pagesources %inlinepages};
13
14 sub usage () { #{{{
15         die "usage: ikiwiki [options] source dest\n";
16 } #}}}
17
18 sub getconfig () { #{{{
19         if (! exists $ENV{WRAPPED_OPTIONS}) {
20                 %config=(
21                         wiki_file_prune_regexp => qr{((^|/).svn/|\.\.|^\.|\/\.|\.html?$|\.rss$)},
22                         wiki_link_regexp => qr/\[\[(?:([^\s\]\|]+)\|)?([^\s\]]+)\]\]/,
23                         wiki_processor_regexp => qr/\[\[(\w+)\s+([^\]]+)\]\]/,
24                         wiki_file_regexp => qr/(^[-A-Za-z0-9_.:\/+]+$)/,
25                         verbose => 0,
26                         wikiname => "wiki",
27                         default_pageext => ".mdwn",
28                         cgi => 0,
29                         svn => 1,
30                         url => '',
31                         cgiurl => '',
32                         historyurl => '',
33                         diffurl => '',
34                         anonok => 0,
35                         rss => 0,
36                         rebuild => 0,
37                         refresh => 0,
38                         getctime => 0,
39                         hyperestraier => 0,
40                         wrapper => undef,
41                         wrappermode => undef,
42                         srcdir => undef,
43                         destdir => undef,
44                         templatedir => "/usr/share/ikiwiki/templates",
45                         underlaydir => "/usr/share/ikiwiki/basewiki",
46                         setup => undef,
47                         adminuser => undef,
48                 );
49
50                 eval q{use Getopt::Long};
51                 GetOptions(
52                         "setup|s=s" => \$config{setup},
53                         "wikiname=s" => \$config{wikiname},
54                         "verbose|v!" => \$config{verbose},
55                         "rebuild!" => \$config{rebuild},
56                         "refresh!" => \$config{refresh},
57                         "getctime" => \$config{getctime},
58                         "wrappermode=i" => \$config{wrappermode},
59                         "svn!" => \$config{svn},
60                         "anonok!" => \$config{anonok},
61                         "hyperestraier" => \$config{hyperestraier},
62                         "rss!" => \$config{rss},
63                         "cgi!" => \$config{cgi},
64                         "url=s" => \$config{url},
65                         "cgiurl=s" => \$config{cgiurl},
66                         "historyurl=s" => \$config{historyurl},
67                         "diffurl=s" => \$config{diffurl},
68                         "exclude=s@" => sub {
69                                 $config{wiki_file_prune_regexp}=qr/$config{wiki_file_prune_regexp}|$_[1]/;
70                         },
71                         "adminuser=s@" => sub {
72                                 push @{$config{adminuser}}, $_[1]
73                         },
74                         "templatedir=s" => sub {
75                                 $config{templatedir}=possibly_foolish_untaint($_[1])
76                         },
77                         "underlaydir=s" => sub {
78                                 $config{underlaydir}=possibly_foolish_untaint($_[1])
79                         },
80                         "wrapper:s" => sub {
81                                 $config{wrapper}=$_[1] ? $_[1] : "ikiwiki-wrap"
82                         },
83                 ) || usage();
84
85                 if (! $config{setup}) {
86                         usage() unless @ARGV == 2;
87                         $config{srcdir} = possibly_foolish_untaint(shift @ARGV);
88                         $config{destdir} = possibly_foolish_untaint(shift @ARGV);
89                         checkconfig();
90                 }
91         }
92         else {
93                 # wrapper passes a full config structure in the environment
94                 # variable
95                 eval possibly_foolish_untaint($ENV{WRAPPED_OPTIONS});
96                 checkconfig();
97         }
98 } #}}}
99
100 sub checkconfig () { #{{{
101         if ($config{cgi} && ! length $config{url}) {
102                 error("Must specify url to wiki with --url when using --cgi\n");
103         }
104         if ($config{rss} && ! length $config{url}) {
105                 error("Must specify url to wiki with --url when using --rss\n");
106         }
107         if ($config{hyperestraier} && ! length $config{url}) {
108                 error("Must specify --url when using --hyperestraier\n");
109         }
110         
111         $config{wikistatedir}="$config{srcdir}/.ikiwiki"
112                 unless exists $config{wikistatedir};
113         
114         if ($config{svn}) {
115                 require IkiWiki::Rcs::SVN;
116                 $config{rcs}=1;
117         }
118         else {
119                 require IkiWiki::Rcs::Stub;
120                 $config{rcs}=0;
121         }
122 } #}}}
123
124 sub error ($) { #{{{
125         if ($config{cgi}) {
126                 print "Content-type: text/html\n\n";
127                 print misctemplate("Error", "<p>Error: @_</p>");
128         }
129         die @_;
130 } #}}}
131
132 sub possibly_foolish_untaint ($) { #{{{
133         my $tainted=shift;
134         my ($untainted)=$tainted=~/(.*)/;
135         return $untainted;
136 } #}}}
137
138 sub debug ($) { #{{{
139         return unless $config{verbose};
140         if (! $config{cgi}) {
141                 print "@_\n";
142         }
143         else {
144                 print STDERR "@_\n";
145         }
146 } #}}}
147
148 sub basename ($) { #{{{
149         my $file=shift;
150
151         $file=~s!.*/!!;
152         return $file;
153 } #}}}
154
155 sub dirname ($) { #{{{
156         my $file=shift;
157
158         $file=~s!/?[^/]+$!!;
159         return $file;
160 } #}}}
161
162 sub pagetype ($) { #{{{
163         my $page=shift;
164         
165         if ($page =~ /\.mdwn$/) {
166                 return ".mdwn";
167         }
168         else {
169                 return "unknown";
170         }
171 } #}}}
172
173 sub pagename ($) { #{{{
174         my $file=shift;
175
176         my $type=pagetype($file);
177         my $page=$file;
178         $page=~s/\Q$type\E*$// unless $type eq 'unknown';
179         return $page;
180 } #}}}
181
182 sub htmlpage ($) { #{{{
183         my $page=shift;
184
185         return $page.".html";
186 } #}}}
187
188 sub srcfile ($) { #{{{
189         my $file=shift;
190
191         return "$config{srcdir}/$file" if -e "$config{srcdir}/$file";
192         return "$config{underlaydir}/$file" if -e "$config{underlaydir}/$file";
193         error("internal error: $file cannot be found");
194 } #}}}
195
196 sub readfile ($) { #{{{
197         my $file=shift;
198
199         if (-l $file) {
200                 error("cannot read a symlink ($file)");
201         }
202         
203         local $/=undef;
204         open (IN, "$file") || error("failed to read $file: $!");
205         my $ret=<IN>;
206         close IN;
207         return $ret;
208 } #}}}
209
210 sub writefile ($$$) { #{{{
211         my $file=shift; # can include subdirs
212         my $destdir=shift; # directory to put file in
213         my $content=shift;
214         
215         my $test=$file;
216         while (length $test) {
217                 if (-l "$destdir/$test") {
218                         error("cannot write to a symlink ($test)");
219                 }
220                 $test=dirname($test);
221         }
222
223         my $dir=dirname("$destdir/$file");
224         if (! -d $dir) {
225                 my $d="";
226                 foreach my $s (split(m!/+!, $dir)) {
227                         $d.="$s/";
228                         if (! -d $d) {
229                                 mkdir($d) || error("failed to create directory $d: $!");
230                         }
231                 }
232         }
233         
234         open (OUT, ">$destdir/$file") || error("failed to write $destdir/$file: $!");
235         print OUT $content;
236         close OUT;
237 } #}}}
238
239 sub bestlink ($$) { #{{{
240         # Given a page and the text of a link on the page, determine which
241         # existing page that link best points to. Prefers pages under a
242         # subdirectory with the same name as the source page, failing that
243         # goes down the directory tree to the base looking for matching
244         # pages.
245         my $page=shift;
246         my $link=lc(shift);
247         
248         my $cwd=$page;
249         do {
250                 my $l=$cwd;
251                 $l.="/" if length $l;
252                 $l.=$link;
253
254                 if (exists $links{$l}) {
255                         #debug("for $page, \"$link\", use $l");
256                         return $l;
257                 }
258         } while $cwd=~s!/?[^/]+$!!;
259
260         #print STDERR "warning: page $page, broken link: $link\n";
261         return "";
262 } #}}}
263
264 sub isinlinableimage ($) { #{{{
265         my $file=shift;
266         
267         $file=~/\.(png|gif|jpg|jpeg)$/i;
268 } #}}}
269
270 sub pagetitle ($) { #{{{
271         my $page=shift;
272         $page=~s/__(\d+)__/&#$1;/g;
273         $page=~y/_/ /;
274         return $page;
275 } #}}}
276
277 sub titlepage ($) { #{{{
278         my $title=shift;
279         $title=~y/ /_/;
280         $title=~s/([^-A-Za-z0-9_:+\/.])/"__".ord($1)."__"/eg;
281         return $title;
282 } #}}}
283
284 sub cgiurl (@) { #{{{
285         my %params=@_;
286
287         return $config{cgiurl}."?".join("&amp;", map "$_=$params{$_}", keys %params);
288 } #}}}
289
290 sub styleurl (;$) { #{{{
291         my $page=shift;
292
293         return "$config{url}/style.css" if ! defined $page;
294         
295         $page=~s/[^\/]+$//;
296         $page=~s/[^\/]+\//..\//g;
297         return $page."style.css";
298 } #}}}
299
300 sub htmllink ($$;$$$) { #{{{
301         my $page=shift;
302         my $link=shift;
303         my $noimageinline=shift; # don't turn links into inline html images
304         my $forcesubpage=shift; # force a link to a subpage
305         my $linktext=shift; # set to force the link text to something
306
307         my $bestlink;
308         if (! $forcesubpage) {
309                 $bestlink=bestlink($page, $link);
310         }
311         else {
312                 $bestlink="$page/".lc($link);
313         }
314
315         $linktext=pagetitle(basename($link)) unless defined $linktext;
316         
317         return $linktext if length $bestlink && $page eq $bestlink;
318         
319         # TODO BUG: %renderedfiles may not have it, if the linked to page
320         # was also added and isn't yet rendered! Note that this bug is
321         # masked by the bug mentioned below that makes all new files
322         # be rendered twice.
323         if (! grep { $_ eq $bestlink } values %renderedfiles) {
324                 $bestlink=htmlpage($bestlink);
325         }
326         if (! grep { $_ eq $bestlink } values %renderedfiles) {
327                 return "<span><a href=\"".
328                         cgiurl(do => "create", page => $link, from =>$page).
329                         "\">?</a>$linktext</span>"
330         }
331         
332         $bestlink=File::Spec->abs2rel($bestlink, dirname($page));
333         
334         if (! $noimageinline && isinlinableimage($bestlink)) {
335                 return "<img src=\"$bestlink\" alt=\"$linktext\" />";
336         }
337         return "<a href=\"$bestlink\">$linktext</a>";
338 } #}}}
339
340 sub indexlink () { #{{{
341         return "<a href=\"$config{url}\">$config{wikiname}</a>";
342 } #}}}
343
344 sub lockwiki () { #{{{
345         # Take an exclusive lock on the wiki to prevent multiple concurrent
346         # run issues. The lock will be dropped on program exit.
347         if (! -d $config{wikistatedir}) {
348                 mkdir($config{wikistatedir});
349         }
350         open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
351                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
352         if (! flock(WIKILOCK, 2 | 4)) {
353                 debug("wiki seems to be locked, waiting for lock");
354                 my $wait=600; # arbitrary, but don't hang forever to 
355                               # prevent process pileup
356                 for (1..600) {
357                         return if flock(WIKILOCK, 2 | 4);
358                         sleep 1;
359                 }
360                 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
361         }
362 } #}}}
363
364 sub unlockwiki () { #{{{
365         close WIKILOCK;
366 } #}}}
367
368 sub loadindex () { #{{{
369         open (IN, "$config{wikistatedir}/index") || return;
370         while (<IN>) {
371                 $_=possibly_foolish_untaint($_);
372                 chomp;
373                 my %items;
374                 $items{link}=[];
375                 foreach my $i (split(/ /, $_)) {
376                         my ($item, $val)=split(/=/, $i, 2);
377                         push @{$items{$item}}, $val;
378                 }
379
380                 next unless exists $items{src}; # skip bad lines for now
381
382                 my $page=pagename($items{src}[0]);
383                 if (! $config{rebuild}) {
384                         $pagesources{$page}=$items{src}[0];
385                         $oldpagemtime{$page}=$items{mtime}[0];
386                         $oldlinks{$page}=[@{$items{link}}];
387                         $links{$page}=[@{$items{link}}];
388                         $inlinepages{$page}=join(" ", @{$items{inlinepage}})
389                                 if exists $items{inlinepage};
390                         $renderedfiles{$page}=$items{dest}[0];
391                 }
392                 $pagectime{$page}=$items{ctime}[0];
393         }
394         close IN;
395 } #}}}
396
397 sub saveindex () { #{{{
398         if (! -d $config{wikistatedir}) {
399                 mkdir($config{wikistatedir});
400         }
401         open (OUT, ">$config{wikistatedir}/index") || 
402                 error("cannot write to $config{wikistatedir}/index: $!");
403         foreach my $page (keys %oldpagemtime) {
404                 next unless $oldpagemtime{$page};
405                 my $line="mtime=$oldpagemtime{$page} ".
406                         "ctime=$pagectime{$page} ".
407                         "src=$pagesources{$page} ".
408                         "dest=$renderedfiles{$page}";
409                 $line.=" link=$_" foreach @{$links{$page}};
410                 if (exists $inlinepages{$page}) {
411                         $line.=" inlinepage=$_" foreach split " ", $inlinepages{$page};
412                 }
413                 print OUT $line."\n";
414         }
415         close OUT;
416 } #}}}
417
418 sub misctemplate ($$) { #{{{
419         my $title=shift;
420         my $pagebody=shift;
421         
422         my $template=HTML::Template->new(
423                 filename => "$config{templatedir}/misc.tmpl"
424         );
425         $template->param(
426                 title => $title,
427                 indexlink => indexlink(),
428                 wikiname => $config{wikiname},
429                 pagebody => $pagebody,
430                 styleurl => styleurl(),
431         );
432         return $template->output;
433 }#}}}
434
435 sub userinfo_get ($$) { #{{{
436         my $user=shift;
437         my $field=shift;
438
439         eval q{use Storable};
440         my $userdata=eval{ Storable::lock_retrieve("$config{wikistatedir}/userdb") };
441         if (! defined $userdata || ! ref $userdata || 
442             ! exists $userdata->{$user} || ! ref $userdata->{$user} ||
443             ! exists $userdata->{$user}->{$field}) {
444                 return "";
445         }
446         return $userdata->{$user}->{$field};
447 } #}}}
448
449 sub userinfo_set ($$$) { #{{{
450         my $user=shift;
451         my $field=shift;
452         my $value=shift;
453         
454         eval q{use Storable};
455         my $userdata=eval{ Storable::lock_retrieve("$config{wikistatedir}/userdb") };
456         if (! defined $userdata || ! ref $userdata || 
457             ! exists $userdata->{$user} || ! ref $userdata->{$user}) {
458                 return "";
459         }
460         
461         $userdata->{$user}->{$field}=$value;
462         my $oldmask=umask(077);
463         my $ret=Storable::lock_store($userdata, "$config{wikistatedir}/userdb");
464         umask($oldmask);
465         return $ret;
466 } #}}}
467
468 sub userinfo_setall ($$) { #{{{
469         my $user=shift;
470         my $info=shift;
471         
472         eval q{use Storable};
473         my $userdata=eval{ Storable::lock_retrieve("$config{wikistatedir}/userdb") };
474         if (! defined $userdata || ! ref $userdata) {
475                 $userdata={};
476         }
477         $userdata->{$user}=$info;
478         my $oldmask=umask(077);
479         my $ret=Storable::lock_store($userdata, "$config{wikistatedir}/userdb");
480         umask($oldmask);
481         return $ret;
482 } #}}}
483
484 sub is_admin ($) { #{{{
485         my $user_name=shift;
486
487         return grep { $_ eq $user_name } @{$config{adminuser}};
488 } #}}}
489
490 sub glob_match ($$) { #{{{
491         my $page=shift;
492         my $glob=shift;
493
494         # turn glob into safe regexp
495         $glob=quotemeta($glob);
496         $glob=~s/\\\*/.*/g;
497         $glob=~s/\\\?/./g;
498         $glob=~s!\\/!/!g;
499         
500         $page=~/^$glob$/i;
501 } #}}}
502
503 sub globlist_match ($$) { #{{{
504         my $page=shift;
505         my @globlist=split(" ", shift);
506
507         # check any negated globs first
508         foreach my $glob (@globlist) {
509                 return 0 if $glob=~/^!(.*)/ && glob_match($page, $1);
510         }
511
512         foreach my $glob (@globlist) {
513                 return 1 if glob_match($page, $glob);
514         }
515         
516         return 0;
517 } #}}}
518
519 sub main () { #{{{
520         getconfig();
521         
522         if ($config{cgi}) {
523                 lockwiki();
524                 loadindex();
525                 require IkiWiki::CGI;
526                 cgi();
527         }
528         elsif ($config{setup}) {
529                 require IkiWiki::Setup;
530                 setup();
531         }
532         elsif ($config{wrapper}) {
533                 lockwiki();
534                 require IkiWiki::Wrapper;
535                 gen_wrapper();
536         }
537         else {
538                 lockwiki();
539                 loadindex();
540                 require IkiWiki::Render;
541                 rcs_update();
542                 rcs_getctime() if $config{getctime};
543                 refresh();
544                 saveindex();
545         }
546 } #}}}
547
548 main;