Add external config support via BLOSXOM_CONFIG_DIR and BLOSXOM_CONFIG_FILE env variables.
[matthijs/upstream/blosxom.git] / blosxom.cgi
1 #!/usr/bin/perl
2
3 # Blosxom
4 # Author: Rael Dornfest <rael@oreilly.com>
5 # Version: 2.0.2
6 # Home/Docs/Licensing: http://blosxom.sourceforge.net/
7 # Development/Downloads: http://sourceforge.net/projects/blosxom
8
9 package blosxom;
10
11 # --- Configurable variables -----
12
13 # What's this blog's title?
14 $blog_title = "My Weblog";
15
16 # What's this blog's description (for outgoing RSS feed)?
17 $blog_description = "Yet another Blosxom weblog.";
18
19 # What's this blog's primary language (for outgoing RSS feed)?
20 $blog_language = "en";
21
22 # Where are this blog's entries kept?
23 $datadir = "/Library/WebServer/Documents/blosxom";
24
25 # What's my preferred base URL for this blog (leave blank for automatic)?
26 $url = "";
27
28 # Should I stick only to the datadir for items or travel down the
29 # directory hierarchy looking for items?  If so, to what depth?
30 # 0 = infinite depth (aka grab everything), 1 = datadir only, n = n levels down
31 $depth = 0;
32
33 # How many entries should I show on the home page?
34 $num_entries = 40;
35
36 # What file extension signifies a blosxom entry?
37 $file_extension = "txt";
38
39 # What is the default flavour?
40 $default_flavour = "html";
41
42 # Should I show entries from the future (i.e. dated after now)?
43 $show_future_entries = 0;
44
45 # --- Plugins (Optional) -----
46
47 # Where are my plugins kept?
48 $plugin_dir = "";
49
50 # Where should my modules keep their state information?
51 $plugin_state_dir = "$plugin_dir/state";
52
53 # --- Static Rendering -----
54
55 # Where are this blog's static files to be created?
56 $static_dir = "/Library/WebServer/Documents/blog";
57
58 # What's my administrative password (you must set this for static rendering)?
59 $static_password = "";
60
61 # What flavours should I generate statically?
62 @static_flavours = qw/html rss/;
63
64 # Should I statically generate individual entries?
65 # 0 = no, 1 = yes
66 $static_entries = 0;
67
68 # --------------------------------
69
70 use vars qw! $version $blog_title $blog_description $blog_language $datadir $url %template $template $depth $num_entries $file_extension $default_flavour $static_or_dynamic $config_dir $plugin_dir $plugin_state_dir @plugins %plugins $static_dir $static_password @static_flavours $static_entries $path_info $path_info_yr $path_info_mo $path_info_da $path_info_mo_num $flavour $static_or_dynamic %month2num @num2month $interpolate $entries $output $header $show_future_entries %files %indexes %others !;
71
72 use strict;
73 use FileHandle;
74 use File::Find;
75 use File::stat;
76 use Time::localtime;
77 use CGI qw/:standard :netscape/;
78
79 $version = "2.0.2";
80
81 # Load configuration from $ENV{BLOSXOM_CONFIG_DIR}/blosxom.conf, if it exists
82 my $blosxom_config;
83 if ($ENV{BLOSXOM_CONFIG_FILE} && -r $ENV{BLOSXOM_CONFIG_FILE}) {
84   $blosxom_config = $ENV{BLOSXOM_CONFIG_FILE};
85   ($config_dir = $blosxom_config) =~ s! / [^/]* $ !!x;                          
86 }
87 else {
88   for my $blosxom_config_dir ($ENV{BLOSXOM_CONFIG_DIR}, '/etc/blosxom', '/etc') {
89     if (-r "$blosxom_config_dir/blosxom.conf") {
90       $config_dir = $blosxom_config_dir;
91       $blosxom_config = "$blosxom_config_dir/blosxom.conf";
92       last;
93     }
94   }
95 }
96 # Load $blosxom_config
97 if ($blosxom_config) { 
98   if (-r $blosxom_config) {
99     eval { require $blosxom_config } or
100       warn "Error reading blosxom config file '$blosxom_config'" . ($@ ? ": $@" : '');
101   }
102   else {
103     warn "Cannot find or read blosxom config file '$blosxom_config'";
104   }
105 }
106
107 my $fh = new FileHandle;
108
109 %month2num = (nil=>'00', Jan=>'01', Feb=>'02', Mar=>'03', Apr=>'04', May=>'05', Jun=>'06', Jul=>'07', Aug=>'08', Sep=>'09', Oct=>'10', Nov=>'11', Dec=>'12');
110 @num2month = sort { $month2num{$a} <=> $month2num{$b} } keys %month2num;
111
112 # Use the stated preferred URL or figure it out automatically
113 $url ||= url(-path_info => 1);
114 $url =~ s/^included:/http:/ if $ENV{SERVER_PROTOCOL} eq 'INCLUDED';
115
116 # NOTE: Since v3.12, it looks as if CGI.pm misbehaves for SSIs and
117 # always appends path_info to the url. To fix this, we always
118 # request an url with path_info, and always remove it from the end of the
119 # string.
120 my $pi_len = length $ENV{PATH_INFO};
121 my $might_be_pi = substr($url, -$pi_len);
122 substr($url, -length $ENV{PATH_INFO}) = '' if $might_be_pi eq $ENV{PATH_INFO};
123
124 $url =~ s!/$!!;
125
126 # Drop ending any / from dir settings
127 $datadir =~ s!/$!!; $plugin_dir =~ s!/$!!; $static_dir =~ s!/$!!;
128   
129 # Fix depth to take into account datadir's path
130 $depth and $depth += ($datadir =~ tr[/][]) - 1;
131
132 # Global variable to be used in head/foot.{flavour} templates
133 $path_info = '';
134
135 $static_or_dynamic = (!$ENV{GATEWAY_INTERFACE} and param('-password') and $static_password and param('-password') eq $static_password) ? 'static' : 'dynamic';
136 $static_or_dynamic eq 'dynamic' and param(-name=>'-quiet', -value=>1);
137
138 # Path Info Magic
139 # Take a gander at HTTP's PATH_INFO for optional blog name, archive yr/mo/day
140 my @path_info = split m{/}, path_info() || param('path'); 
141 shift @path_info;
142
143 while ($path_info[0] and $path_info[0] =~ /^[a-zA-Z].*$/ and $path_info[0] !~ /(.*)\.(.*)/) { $path_info .= '/' . shift @path_info; }
144
145 # Flavour specified by ?flav={flav} or index.{flav}
146 $flavour = '';
147
148 if ( $path_info[$#path_info] =~ /(.+)\.(.+)$/ ) {
149   $flavour = $2;
150   $1 ne 'index' and $path_info .= "/$1.$2";
151   pop @path_info;
152 } else {
153   $flavour = param('flav') || $default_flavour;
154 }
155
156 # Strip spurious slashes
157 $path_info =~ s!(^/*)|(/*$)!!g;
158
159 # Date fiddling
160 ($path_info_yr,$path_info_mo,$path_info_da) = @path_info;
161 $path_info_mo_num = $path_info_mo ? ( $path_info_mo =~ /\d{2}/ ? $path_info_mo : ($month2num{ucfirst(lc $path_info_mo)} || undef) ) : undef;
162
163 # Define standard template subroutine, plugin-overridable at Plugins: Template
164 $template = 
165   sub {
166     my ($path, $chunk, $flavour) = @_;
167
168     do {
169       return join '', <$fh> if $fh->open("< $datadir/$path/$chunk.$flavour");
170     } while ($path =~ s/(\/*[^\/]*)$// and $1);
171
172     # Check for definedness, since flavour can be the empty string
173     if (defined $template{$flavour}{$chunk}) {
174         return $template{$flavour}{$chunk};
175     } elsif (defined $template{error}{$chunk}) {
176         return $template{error}{$chunk} 
177     } else {
178         return '';
179     }
180   };
181 # Bring in the templates
182 %template = ();
183 while (<DATA>) {
184   last if /^(__END__)$/;
185   my($ct, $comp, $txt) = /^(\S+)\s(\S+)(?:\s(.*))?$/ or next;
186   $txt =~ s/\\n/\n/mg;
187   $template{$ct}{$comp} .= $txt . "\n";
188 }
189
190 # Plugins: Start
191 if ( $plugin_dir and opendir PLUGINS, $plugin_dir ) {
192   unshift @INC, $plugin_dir;
193   foreach my $plugin ( grep { /^[\w:]+$/ && -f "$plugin_dir/$_"  } sort readdir(PLUGINS) ) {
194     next if ($plugin =~ /~$/);   # Ignore emacs backups
195     my($plugin_name, $off) = $plugin =~ /^\d*([\w:]+?)(_?)$/;
196     my $on_off = $off eq '_' ? -1 : 1;
197     # Allow perl module plugins
198     if ($plugin =~ m/::/ && -z "$plugin_dir/$plugin") {
199       # For Blosxom::Plugin::Foo style plugins, we need to use a string require
200       eval "require $plugin_name";
201     }
202     else {
203       eval { require $plugin };
204     }
205     $@ and warn "error finding or loading blosxom plugin $plugin_name - skipping\n" and next;
206     $plugin_name->start() and ( $plugins{$plugin_name} = $on_off ) and push @plugins, $plugin_name;
207   }
208   shift @INC;
209   closedir PLUGINS;
210 }
211
212 # Plugins: Template
213 # Allow for the first encountered plugin::template subroutine to override the
214 # default built-in template subroutine
215 my $tmp; foreach my $plugin ( @plugins ) { $plugins{$plugin} > 0 and $plugin->can('template') and defined($tmp = $plugin->template()) and $template = $tmp and last; }
216
217 # Provide backward compatibility for Blosxom < 2.0rc1 plug-ins
218 sub load_template {
219   return &$template(@_);
220 }
221
222 # Define default entries subroutine
223 $entries =
224   sub {
225     my(%files, %indexes, %others);
226     find(
227       sub {
228         my $d; 
229         my $curr_depth = $File::Find::dir =~ tr[/][]; 
230         return if $depth and $curr_depth > $depth; 
231      
232         if ( 
233           # a match
234           $File::Find::name =~ m!^$datadir/(?:(.*)/)?(.+)\.$file_extension$!
235           # not an index, .file, and is readable
236           and $2 ne 'index' and $2 !~ /^\./ and (-r $File::Find::name)
237         ) {
238
239             # to show or not to show future entries
240             ( 
241               $show_future_entries
242               or stat($File::Find::name)->mtime < time 
243             )
244
245               # add the file and its associated mtime to the list of files
246               and $files{$File::Find::name} = stat($File::Find::name)->mtime
247
248                 # static rendering bits
249                 and (
250                   param('-all') 
251                   or !-f "$static_dir/$1/index." . $static_flavours[0]
252                   or stat("$static_dir/$1/index." . $static_flavours[0])->mtime < stat($File::Find::name)->mtime
253                 )
254                   and $indexes{$1} = 1
255                     and $d = join('/', (nice_date($files{$File::Find::name}))[5,2,3])
256   
257                       and $indexes{$d} = $d
258                         and $static_entries and $indexes{ ($1 ? "$1/" : '') . "$2.$file_extension" } = 1
259
260             } 
261             else {
262               !-d $File::Find::name and -r $File::Find::name and $others{$File::Find::name} = stat($File::Find::name)->mtime
263             }
264       }, $datadir
265     );
266
267     return (\%files, \%indexes, \%others);
268   };
269
270 # Plugins: Entries
271 # Allow for the first encountered plugin::entries subroutine to override the
272 # default built-in entries subroutine
273 my $tmp; foreach my $plugin ( @plugins ) { $plugins{$plugin} > 0 and $plugin->can('entries') and defined($tmp = $plugin->entries()) and $entries = $tmp and last; }
274
275 my ($files, $indexes, $others) = &$entries();
276 %indexes = %$indexes;
277
278 # Static
279 if (!$ENV{GATEWAY_INTERFACE} and param('-password') and $static_password and param('-password') eq $static_password) {
280
281   param('-quiet') or print "Blosxom is generating static index pages...\n";
282
283   # Home Page and Directory Indexes
284   my %done;
285   foreach my $path ( sort keys %indexes) {
286     my $p = '';
287     foreach ( ('', split /\//, $path) ) {
288       $p .= "/$_";
289       $p =~ s!^/!!;
290       $done{$p}++ and next;
291       (-d "$static_dir/$p" or $p =~ /\.$file_extension$/) or mkdir "$static_dir/$p", 0755;
292       foreach $flavour ( @static_flavours ) {
293         my $content_type = (&$template($p,'content_type',$flavour));
294         $content_type =~ s!\n.*!!s;
295         my $fn = $p =~ m!^(.+)\.$file_extension$! ? $1 : "$p/index";
296         param('-quiet') or print "$fn.$flavour\n";
297         my $fh_w = new FileHandle "> $static_dir/$fn.$flavour" or die "Couldn't open $static_dir/$p for writing: $!";  
298         $output = '';
299         if ($indexes{$path} == 1) {
300           # category
301           $path_info = $p;
302           # individual story
303           $path_info =~ s!\.$file_extension$!\.$flavour!;
304           print $fh_w &generate('static', $path_info, '', $flavour, $content_type);
305         } else {
306           # date
307           local ($path_info_yr,$path_info_mo,$path_info_da, $path_info) = 
308               split /\//, $p, 4;
309           unless (defined $path_info) {$path_info = ""};
310           print $fh_w &generate('static', '', $p, $flavour, $content_type);
311         }
312         $fh_w->close;
313       }
314     }
315   }
316 }
317
318 # Dynamic
319 else {
320   my $content_type = (&$template($path_info,'content_type',$flavour));
321   $content_type =~ s!\n.*!!s;
322
323   $header = {-type=>$content_type};
324
325   print generate('dynamic', $path_info, "$path_info_yr/$path_info_mo_num/$path_info_da", $flavour, $content_type);
326 }
327
328 # Plugins: End
329 foreach my $plugin ( @plugins ) { $plugins{$plugin} > 0 and $plugin->can('end') and $entries = $plugin->end() }
330
331 # Generate 
332 sub generate {
333   my($static_or_dynamic, $currentdir, $date, $flavour, $content_type) = @_;
334
335   %files = %$files; %others = ref $others ? %$others : ();
336
337   # Plugins: Filter
338   foreach my $plugin ( @plugins ) { $plugins{$plugin} > 0 and $plugin->can('filter') and $entries = $plugin->filter(\%files, \%others) }
339
340   my %f = %files;
341
342   # Plugins: Skip
343   # Allow plugins to decide if we can cut short story generation
344   my $skip; foreach my $plugin ( @plugins ) { $plugins{$plugin} > 0 and $plugin->can('skip') and defined($tmp = $plugin->skip()) and $skip = $tmp and last; }
345   
346   # Define default interpolation subroutine
347   $interpolate = 
348     sub {
349       package blosxom;
350       my $template = shift;
351       $template =~ 
352         s/(\$\w+(?:::)?\w*)/"defined $1 ? $1 : ''"/gee;
353       return $template;
354     };  
355
356   unless (defined($skip) and $skip) {
357
358     # Plugins: Interpolate
359     # Allow for the first encountered plugin::interpolate subroutine to 
360     # override the default built-in interpolate subroutine
361     my $tmp; foreach my $plugin ( @plugins ) { $plugins{$plugin} > 0 and $plugin->can('interpolate') and defined($tmp = $plugin->interpolate()) and $interpolate = $tmp and last; }
362         
363     # Head
364     my $head = (&$template($currentdir,'head',$flavour));
365   
366     # Plugins: Head
367     foreach my $plugin ( @plugins ) { $plugins{$plugin} > 0 and $plugin->can('head') and $entries = $plugin->head($currentdir, \$head) }
368   
369     $head = &$interpolate($head);
370   
371     $output .= $head;
372     
373     # Stories
374     my $curdate = '';
375     my $ne = $num_entries;
376
377     if ( $currentdir =~ /(.*?)([^\/]+)\.(.+)$/ and $2 ne 'index' ) {
378       $currentdir = "$1$2.$file_extension";
379       $files{"$datadir/$1$2.$file_extension"} and %f = ( "$datadir/$1$2.$file_extension" => $files{"$datadir/$1$2.$file_extension"} );
380     } 
381     else { 
382       $currentdir =~ s!/index\..+$!!;
383     }
384
385     # Define a default sort subroutine
386     my $sort = sub {
387       my($files_ref) = @_;
388       return sort { $files_ref->{$b} <=> $files_ref->{$a} } keys %$files_ref;
389     };
390   
391     # Plugins: Sort
392     # Allow for the first encountered plugin::sort subroutine to override the
393     # default built-in sort subroutine
394     my $tmp; foreach my $plugin ( @plugins ) { $plugins{$plugin} > 0 and $plugin->can('sort') and defined($tmp = $plugin->sort()) and $sort = $tmp and last; }
395   
396     foreach my $path_file ( &$sort(\%f, \%others) ) {
397       last if $ne <= 0 && $date !~ /\d/;
398       use vars qw/ $path $fn /;
399       ($path,$fn) = $path_file =~ m!^$datadir/(?:(.*)/)?(.*)\.$file_extension!;
400   
401       # Only stories in the right hierarchy
402       $path =~ /^$currentdir/ or $path_file eq "$datadir/$currentdir" or next;
403   
404       # Prepend a slash for use in templates only if a path exists
405       $path &&= "/$path";
406
407       # Date fiddling for by-{year,month,day} archive views
408       use vars qw/ $dw $mo $mo_num $da $ti $yr $hr $min $hr12 $ampm /;
409       ($dw,$mo,$mo_num,$da,$ti,$yr) = nice_date($files{"$path_file"});
410       ($hr,$min) = split /:/, $ti;
411       ($hr12, $ampm) = $hr >= 12 ? ($hr - 12,'pm') : ($hr, 'am'); 
412       $hr12 =~ s/^0//; $hr12 == 0 and $hr12 = 12;
413   
414       # Only stories from the right date
415       my($path_info_yr,$path_info_mo_num, $path_info_da) = split /\//, $date;
416       next if $path_info_yr && $yr != $path_info_yr; last if $path_info_yr && $yr < $path_info_yr; 
417       next if $path_info_mo_num && $mo ne $num2month[$path_info_mo_num];
418       next if $path_info_da && $da != $path_info_da; last if $path_info_da && $da < $path_info_da; 
419   
420       # Date 
421       my $date = (&$template($path,'date',$flavour));
422       
423       # Plugins: Date
424       foreach my $plugin ( @plugins ) { $plugins{$plugin} > 0 and $plugin->can('date') and $entries = $plugin->date($currentdir, \$date, $files{$path_file}, $dw,$mo,$mo_num,$da,$ti,$yr) }
425   
426       $date = &$interpolate($date);
427   
428       $curdate ne $date and $curdate = $date and $output .= $date;
429       
430       use vars qw/ $title $body $raw /;
431       if (-f "$path_file" && $fh->open("< $path_file")) {
432         chomp($title = <$fh>);
433         chomp($body = join '', <$fh>);
434         $fh->close;
435         $raw = "$title\n$body";
436       }
437       my $story = (&$template($path,'story',$flavour));
438   
439       # Plugins: Story
440       foreach my $plugin ( @plugins ) { $plugins{$plugin} > 0 and $plugin->can('story') and $entries = $plugin->story($path, $fn, \$story, \$title, \$body) }
441       
442       if ($content_type =~ m{\bxml\b}) {
443         # Escape <, >, and &, and to produce valid RSS
444         my %escape = ('<'=>'&lt;', '>'=>'&gt;', '&'=>'&amp;', '"'=>'&quot;');  
445         my $escape_re  = join '|' => keys %escape;
446         $title =~ s/($escape_re)/$escape{$1}/g;
447         $body =~ s/($escape_re)/$escape{$1}/g;
448       }
449   
450       $story = &$interpolate($story);
451     
452       $output .= $story;
453       $fh->close;
454   
455       $ne--;
456     }
457   
458     # Foot
459     my $foot = (&$template($currentdir,'foot',$flavour));
460   
461     # Plugins: Foot
462     foreach my $plugin ( @plugins ) { $plugins{$plugin} > 0 and $plugin->can('foot') and $entries = $plugin->foot($currentdir, \$foot) }
463   
464     $foot = &$interpolate($foot);
465     $output .= $foot;
466
467     # Plugins: Last
468     foreach my $plugin ( @plugins ) { $plugins{$plugin} > 0 and $plugin->can('last') and $entries = $plugin->last() }
469
470   } # End skip
471
472   # Finally, add the header, if any and running dynamically
473   $static_or_dynamic eq 'dynamic' and $header and $output = header($header) . $output;
474   
475   $output;
476 }
477
478
479 sub nice_date {
480   my($unixtime) = @_;
481   
482   my $c_time = ctime($unixtime);
483   my($dw,$mo,$da,$ti,$yr) = ( $c_time =~ /(\w{3}) +(\w{3}) +(\d{1,2}) +(\d{2}:\d{2}):\d{2} +(\d{4})$/ );
484   $da = sprintf("%02d", $da);
485   my $mo_num = $month2num{$mo};
486   
487   return ($dw,$mo,$mo_num,$da,$ti,$yr);
488 }
489
490
491 # Default HTML and RSS template bits
492 __DATA__
493 html content_type text/html
494
495 html head <html>
496 html head     <head>
497 html head         <link rel="alternate" type="type="application/rss+xml" title="RSS" href="$url/index.rss" />
498 html head         <title>$blog_title $path_info_da $path_info_mo $path_info_yr
499 html head         </title>
500 html head     </head>
501 html head     <body>
502 html head         <center>
503 html head             <font size="+3">$blog_title</font><br />
504 html head             $path_info_da $path_info_mo $path_info_yr
505 html head         </center>
506 html head         <p />
507
508 html story        <p>
509 html story            <a name="$fn"><b>$title</b></a><br />
510 html story            $body<br />
511 html story            <br />
512 html story            posted at: $ti | path: <a href="$url$path">$path </a> | <a href="$url/$yr/$mo_num/$da#$fn">permanent link to this entry</a>
513 html story        </p>
514
515 html date         <h3>$dw, $da $mo $yr</h3>
516
517 html foot
518 html foot         <p />
519 html foot         <center>
520 html foot             <a href="http://blosxom.sourceforge.net/"><img src="http://blosxom.sourceforge.net/images/pb_blosxom.gif" border="0" /></a>
521 html foot         </center>
522 html foot     </body>
523 html foot </html>
524
525 rss content_type text/xml
526
527 rss head <?xml version="1.0"?>
528 rss head <!-- name="generator" content="blosxom/$version" -->
529 rss head <!DOCTYPE rss PUBLIC "-//Netscape Communications//DTD RSS 0.91//EN" "http://my.netscape.com/publish/formats/rss-0.91.dtd">
530 rss head 
531 rss head <rss version="0.91">
532 rss head   <channel>
533 rss head     <title>$blog_title $path_info_da $path_info_mo $path_info_yr</title>
534 rss head     <link>$url</link>
535 rss head     <description>$blog_description</description>
536 rss head     <language>$blog_language</language>
537
538 rss story   <item>
539 rss story     <title>$title</title>
540 rss story     <link>$url/$yr/$mo_num/$da#$fn</link>
541 rss story     <description>$body</description>
542 rss story   </item>
543
544 rss date 
545
546 rss foot   </channel>
547 rss foot </rss>
548
549 error content_type text/html
550
551 error head <html>
552 error head <body>
553 error head     <p><font color="red">Error: I'm afraid this is the first I've heard of a "$flavour" flavoured Blosxom.  Try dropping the "/+$flavour" bit from the end of the URL.</font>
554
555
556 error story <p><b>$title</b><br />
557 error story $body <a href="$url/$yr/$mo_num/$da#fn.$default_flavour">#</a></p>
558
559 error date <h3>$dw, $da $mo $yr</h3>
560
561 error foot     </body>
562 error foot </html>
563 __END__