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