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