support arbitrary characters in page titles, via some ugly use of unicode
[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 @ARGV);
74                         $config{destdir} = possibly_foolish_untaint(shift @ARGV);
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 pagetitle ($) { #{{{
238         my $page=shift;
239         $page=~s/__(\d+)__/&#$1;/g;
240         $page=~y/_/ /;
241         return $page;
242 } #}}}
243
244 sub htmllink ($$;$$) { #{{{
245         my $page=shift;
246         my $link=shift;
247         my $noimageinline=shift; # don't turn links into inline html images
248         my $forcesubpage=shift; # force a link to a subpage
249
250         my $bestlink;
251         if (! $forcesubpage) {
252                 $bestlink=bestlink($page, $link);
253         }
254         else {
255                 $bestlink="$page/".lc($link);
256         }
257
258         my $linktext=pagetitle($link);
259         
260         return $linktext if length $bestlink && $page eq $bestlink;
261         
262         # TODO BUG: %renderedfiles may not have it, if the linked to page
263         # was also added and isn't yet rendered! Note that this bug is
264         # masked by the bug mentioned below that makes all new files
265         # be rendered twice.
266         if (! grep { $_ eq $bestlink } values %renderedfiles) {
267                 $bestlink=htmlpage($bestlink);
268         }
269         if (! grep { $_ eq $bestlink } values %renderedfiles) {
270                 return "<a href=\"$config{cgiurl}?do=create&page=$link&from=$page\">?</a>$linktext"
271         }
272         
273         $bestlink=File::Spec->abs2rel($bestlink, dirname($page));
274         
275         if (! $noimageinline && isinlinableimage($bestlink)) {
276                 return "<img src=\"$bestlink\">";
277         }
278         return "<a href=\"$bestlink\">$linktext</a>";
279 } #}}}
280
281 sub indexlink () { #{{{
282         return "<a href=\"$config{url}\">$config{wikiname}</a>";
283 } #}}}
284
285 sub lockwiki () { #{{{
286         # Take an exclusive lock on the wiki to prevent multiple concurrent
287         # run issues. The lock will be dropped on program exit.
288         if (! -d $config{wikistatedir}) {
289                 mkdir($config{wikistatedir});
290         }
291         open(WIKILOCK, ">$config{wikistatedir}/lockfile") ||
292                 error ("cannot write to $config{wikistatedir}/lockfile: $!");
293         if (! flock(WIKILOCK, 2 | 4)) {
294                 debug("wiki seems to be locked, waiting for lock");
295                 my $wait=600; # arbitrary, but don't hang forever to 
296                               # prevent process pileup
297                 for (1..600) {
298                         return if flock(WIKILOCK, 2 | 4);
299                         sleep 1;
300                 }
301                 error("wiki is locked; waited $wait seconds without lock being freed (possible stuck process or stale lock?)");
302         }
303 } #}}}
304
305 sub unlockwiki () { #{{{
306         close WIKILOCK;
307 } #}}}
308
309 sub loadindex () { #{{{
310         open (IN, "$config{wikistatedir}/index") || return;
311         while (<IN>) {
312                 $_=possibly_foolish_untaint($_);
313                 chomp;
314                 my ($mtime, $file, $rendered, @links)=split(' ', $_);
315                 my $page=pagename($file);
316                 $pagesources{$page}=$file;
317                 $oldpagemtime{$page}=$mtime;
318                 $oldlinks{$page}=[@links];
319                 $links{$page}=[@links];
320                 $renderedfiles{$page}=$rendered;
321         }
322         close IN;
323 } #}}}
324
325 sub saveindex () { #{{{
326         if (! -d $config{wikistatedir}) {
327                 mkdir($config{wikistatedir});
328         }
329         open (OUT, ">$config{wikistatedir}/index") || 
330                 error("cannot write to $config{wikistatedir}/index: $!");
331         foreach my $page (keys %oldpagemtime) {
332                 print OUT "$oldpagemtime{$page} $pagesources{$page} $renderedfiles{$page} ".
333                         join(" ", @{$links{$page}})."\n"
334                                 if $oldpagemtime{$page};
335         }
336         close OUT;
337 } #}}}
338
339 sub misctemplate ($$) { #{{{
340         my $title=shift;
341         my $pagebody=shift;
342         
343         my $template=HTML::Template->new(
344                 filename => "$config{templatedir}/misc.tmpl"
345         );
346         $template->param(
347                 title => $title,
348                 indexlink => indexlink(),
349                 wikiname => $config{wikiname},
350                 pagebody => $pagebody,
351         );
352         return $template->output;
353 }#}}}
354
355 sub userinfo_get ($$) { #{{{
356         my $user=shift;
357         my $field=shift;
358
359         eval q{use Storable};
360         my $userdata=eval{ Storable::lock_retrieve("$config{wikistatedir}/userdb") };
361         if (! defined $userdata || ! ref $userdata || 
362             ! exists $userdata->{$user} || ! ref $userdata->{$user} ||
363             ! exists $userdata->{$user}->{$field}) {
364                 return "";
365         }
366         return $userdata->{$user}->{$field};
367 } #}}}
368
369 sub userinfo_set ($$$) { #{{{
370         my $user=shift;
371         my $field=shift;
372         my $value=shift;
373         
374         eval q{use Storable};
375         my $userdata=eval{ Storable::lock_retrieve("$config{wikistatedir}/userdb") };
376         if (! defined $userdata || ! ref $userdata || 
377             ! exists $userdata->{$user} || ! ref $userdata->{$user}) {
378                 return "";
379         }
380         
381         $userdata->{$user}->{$field}=$value;
382         my $oldmask=umask(077);
383         my $ret=Storable::lock_store($userdata, "$config{wikistatedir}/userdb");
384         umask($oldmask);
385         return $ret;
386 } #}}}
387
388 sub userinfo_setall ($$) { #{{{
389         my $user=shift;
390         my $info=shift;
391         
392         eval q{use Storable};
393         my $userdata=eval{ Storable::lock_retrieve("$config{wikistatedir}/userdb") };
394         if (! defined $userdata || ! ref $userdata) {
395                 $userdata={};
396         }
397         $userdata->{$user}=$info;
398         my $oldmask=umask(077);
399         my $ret=Storable::lock_store($userdata, "$config{wikistatedir}/userdb");
400         umask($oldmask);
401         return $ret;
402 } #}}}
403
404 sub is_admin ($) { #{{{
405         my $user_name=shift;
406
407         return grep { $_ eq $user_name } @{$config{adminuser}};
408 } #}}}
409
410 sub glob_match ($$) { #{{{
411         my $page=shift;
412         my $glob=shift;
413
414         # turn glob into safe regexp
415         $glob=quotemeta($glob);
416         $glob=~s/\\\*/.*/g;
417         $glob=~s/\\\?/./g;
418         $glob=~s!\\/!/!g;
419         
420         $page=~/^$glob$/i;
421 } #}}}
422
423 sub globlist_match ($$) { #{{{
424         my $page=shift;
425         my @globlist=split(" ", shift);
426
427         # check any negated globs first
428         foreach my $glob (@globlist) {
429                 return 0 if $glob=~/^!(.*)/ && glob_match($page, $1);
430         }
431
432         foreach my $glob (@globlist) {
433                 return 1 if glob_match($page, $glob);
434         }
435         
436         return 0;
437 } #}}}
438
439 sub main () { #{{{
440         getconfig();
441         
442         if ($config{setup}) {
443                 require IkiWiki::Setup;
444                 setup();
445         }
446         elsif ($config{wrapper}) {
447                 lockwiki();
448                 require IkiWiki::Wrapper;
449                 gen_wrapper();
450         }
451         elsif ($config{cgi}) {
452                 lockwiki();
453                 require IkiWiki::CGI;
454                 cgi();
455         }
456         else {
457                 lockwiki();
458                 loadindex() unless $config{rebuild};
459                 require IkiWiki::Render;
460                 rcs_update();
461                 refresh();
462                 saveindex();
463         }
464 } #}}}
465
466 main;