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