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