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