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