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