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