blib/lib/CGI/SHTML.pm

filter: Statementstmt 77.7% 7 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 83.3% 10 / 12 CC 1 SCAR 0.9
CC
1
Cov
78%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
↑ Summary
1 $VERSION = "1.29";
2 package CGI::SHTML;
3 our $VERSION = "1.29";
4  
5 # -*- Perl -*- Wed May 19 13:09:58 CDT 2004
6 #############################################################################
7 # Written by Tim Skirvin <tskirvin@ks.uiuc.edu>
8 # Copyright 2001-2004, Tim Skirvin and UIUC Board of Trustees.
9 # Redistribution terms are below.
10 #############################################################################
11  
12 =head1 NAME
13  
14 CGI::SHTML - a CGI module for parsing SSI
15  
16 =head1 SYNOPSIS
17  
18 use CGI::SHTML;
19 my $cgi = new CGI::SHTML;
20  
21 # Print a full page worth of info
22 print $cgi->header();
23 print $cgi->start_html('internal', -title=>"SAMPLE PAGE");
24 # Insert content here
25 print $cgi->end_html('internal', -author=>"Webmaster",
26 -address=>'webserver@ks.uiuc.edu');
27  
28 # Just parse some SSI text
29 my @text = '<!--#echo var="TITLE"-->';
30 print CGI::SHTML->parse_shtml(@text);
31  
32 # Use a different configuration file
33 BEGIN { $CGI::SHTML::CONFIG = "/home/tskirvin/shtml.pm"; }
34 use CGI::SHTML;
35  
36 Further functionality is documented with the CGI module.
37  
38 =head1 DESCRIPTION
39  
40 In order to parse SSI, you generally have to configure your scripts to be
41 re-parsed through Apache itself. This module eliminates that need by
42 parsing SSI headers itself, as best it can.
43  
44 Some information on SSI is available at
45 B<http://www.cclabs.missouri.edu/things/instruction/www/html/xssi.shtml>.
46  
47 =head2 VARIABLES
48  
49 =over 2
50  
51 =item $CGI::SHTML::CONFIG
52  
53 Defines a file that has further configuration for your web site. This is
54 useful to allow the module to be installed system-wide without actually
55 requiring changes to be internal to the file. Note that you'll need to
56 reset this value *before* loading CGI::SHTML if you want it to actually
57 make any difference; it's loaded when you load the module.
58  
59 =back
60  
61 =cut
62  
63 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
64 1 ▶use Time::Local;
Subroutine BEGIN: called CC=1 SCAR=0.0
65 0 ▶use CGI;
Subroutine BEGIN: called CC=1 SCAR=2.6
66 use warnings;
67 use vars qw( @ISA $EMPTY $ROOTDIR %REPLACE %CONFIG %HEADER %FOOTER $CONFIG );
68 use vars qw( $IF $NOPRINT );
69  
70 ### User Defined Variables ####################################################
71 $CONFIG ||= "/home/webserver/conf/shtml.pm";
72 $ROOTDIR = $ENV{'DOCUMENT_ROOT'} || "/Common/WebRoot";
73 $EMPTY = ""; # Edit this for debugging
74 %REPLACE = ( );
75 %CONFIG = ( 'timefmt' => "%D",);
76 %HEADER = (
77 'internal' => '/include/header-info.shtml',
78 'generic' => '/include/header-generic.shtml',
79 );
80 %FOOTER = (
81 'internal' => '/include/footer-info.shtml',
82 'generic' => '/include/footer-generic.shtml',
83 );
84 ###############################################################################
85  
86 # Set some environment variables that are important for SSI
87 $ENV{'DATE_GMT'} = gmtime(time);
88 $ENV{'DATE_LOCAL'} = localtime(time);
89 $ENV{'DOCUMENT_URI'} = join('', "http://",
90 $ENV{'SERVER_NAME'} || "localhost",
91 $ENV{'SCRIPT_NAME'} || $0 ) ;
92 $ENV{'LAST_MODIFIED'} = CGI::SHTML->_flastmod( $ENV{'SCRIPT_FILENAME'} || $0 );
93 delete $ENV{'PATH'};
94  
95 @ISA = "CGI";
96  
97 if ( -r $CONFIG ) { do $CONFIG }
98  
99 =head2 SUBROUTINES
100  
101 =over 2
102  
103 =item new ()
104  
105 Invokes CGI's new() command, but blesses with the local class. Also
106 performs the various local functions that are necessary.
107  
108 =cut
109  
110 sub new {
111 my $item = CGI::new(@_);
112 $$item{'NOPRINT'} = [];
113 $$item{'IFDONE'} = [];
114 $$item{'IF'} = 0;
115 bless $item, shift; $item;
116 }
117  
118 =item parse_shtml ( LINE [, LINE [, LINE ]] )
119  
120 Parses C<LINE> as if it were an SHTML file. Returns the parsed set of
121 lines, either in an array context or as a single string suitable for
122 printing. All of the work is actually done by C<ssi()>.
123  
124 =cut
125  
126 sub parse_shtml {
127 my ($self, @lines) = @_;
128 map { chomp } @lines; my $line = join("\n", @lines);
129 my @parts = split m/(<!--#.*?-->)/s, $line;
130  
131 my @return;
132 while (@parts) {
133 my @ssi = ();
134 my $text = shift @parts || "";
135 unless ($self->_noprint) {
136 push @return, $text if defined $text && $text ne '';
137 }
138 if (scalar @parts && $parts[0] =~ /^<!--#(\w+)\s*(.*)?-->\s*$/m) {
139 @ssi = ($1, $2); shift @parts;
140 }
141 my $ssival = $ssi[0] ? $self->ssi(@ssi) : undef;
142 unless ($self->_noprint) {
143 push @return, $ssival if defined $ssival && $ssival ne '';
144 }
145 }
146  
147 my $final = join("\n", @return);
148 $final;
149 }
150  
151 sub _ifdone { shift->_arrayset('IFDONE', @_) }
152 sub _noprint { shift->_arrayset('NOPRINT', @_) }
153  
154 sub _arrayset {
155 my ($self, $key, $val) = @_;
156 my $array = $$self{$key};
157 my $if = $$self{'IF'} - 1;
158 if (defined $val) { $$array[$if] = $val }
159 $$array[$if] || 0;
160 }
161  
162 =item ssi ( COMMAND, ARGS )
163  
164 Does the work of parsing an SSI statement. C<COMMAND> is one of the
165 standard SSI "tags" - 'echo', 'include', 'fsize', 'flastmod', 'exec',
166 'set', 'config', 'odbc', 'email', 'if', 'goto', 'label', and 'break'.
167 C<ARGS> is a string containing the rest of the SSI command - it is parsed
168 by this function.
169  
170 Note: not all commands are implemented. In fact, all that is implemented
171 is 'echo', 'include', 'fsize', 'flastmod', 'exec', 'if/elif/else/endif',
172 and 'set'. These are all the ones that I've actually had to use to this
173 point.
174  
175 =cut
176  
177 sub ssi {
178 my ($self, $command, $args) = @_;
179 my %hash = ();
180  
181 while ($args) { # Parse $args
182 $args =~ s/^(\w+)=(\"[^\"]*\"|'.*'|\S+)\s*//;
183 last unless defined($1);
184 my $item = lc $1; my $val = $2;
185 $val =~ s/^\"|\"$//g;
186 $hash{$item} = $val if defined($val);
187 }
188  
189 my $orig = $self->_noprint;
190 my $if = $$self{'IF'};
191 if (lc $command eq 'if' or lc $command eq 'elif') {
192 if (lc $command eq 'if') { $$self{'IF'}++; $if = $$self{'IF'}; }
193 if ($self->_ifdone) { $self->_noprint(1); return "" }
194 my $val = _ssieval(\%hash);
195 if ($val) { $self->_noprint(0); $self->_ifdone(1); }
196 else { $self->_noprint(1); }
197
198 my $noprint = $self->_noprint;
199 return "";
200  
201 } elsif (lc $command eq 'else') {
202 if ($self->_ifdone) { $self->_noprint(1); }
203 else { $self->_noprint(0); $self->_ifdone(1); }
204 my $noprint = $self->_noprint;
205 return "";
206  
207 } elsif (lc $command eq 'endif') {
208 my $noprint = $self->_noprint(0);
209 my $ifdone = $self->_ifdone(0);
210 $$self{'IF'}--;
211 return "";
212 }
213  
214 if (lc $command eq 'include') {
215 if ( defined $hash{'virtual'} ) { $self->_file(_vfile( $hash{'virtual'} )) }
216 elsif ( defined $hash{'file'} ) { $self->_file( $hash{'file'} ) }
217 else { return "No filename offered" };
218 } elsif (lc $command eq 'set') {
219 my $var = $hash{'var'} || return "No variable to set";
220 my $value = $hash{'value'} || "";
221 $value =~ s/\{(.*)\}/$1/g;
222 $value =~ s/^\$(\S+)/$ENV{$1} || $EMPTY/egx;
223 $ENV{$var} = $value;
224 # Should do something with "config"
225 return "";
226 } elsif (lc $command eq 'echo') {
227 $hash{'var'} =~ s/\{(.*)\}/$1/g;
228 return $ENV{$hash{'var'}} || $EMPTY;
229 } elsif (lc $command eq 'exec') {
230 if ( defined $hash{'cmd'} ) { $self->_execute( $hash{'cmd'} ) || "" }
231 elsif ( defined $hash{'cgi'} ) { $self->_execute( _vfile($hash{'cgi'}) ) }
232 else { return "No filename offered" };
233 } elsif (lc $command eq 'fsize') {
234 if ( defined $hash{'virtual'}) { $self->_fsize(_vfile($hash{'virtual'}))}
235 elsif ( defined $hash{'file'}) { $self->_fsize( $hash{'file'} ) }
236 else { return "No filename offered" };
237 } elsif (lc $command eq 'flastmod') {
238 if (defined $hash{'virtual'}) { $self->_flastmod(_vfile($hash{'virtual'}))}
239 elsif ( defined $hash{'file'}) { $self->_flastmod( $hash{'file'} ) }
240 else { return "No filename offered" };
241 } else { return "" }
242 }
243  
244 =item start_html ( TYPE, OPTIONS )
245  
246 Invokes C<CGI::start_html>, and includes the appropriate header file.
247 C<OPTIONS> is passed directly into C<CGI::start_html>, after being parsed
248 for the 'title' field (which is specially set). C<TYPE> is used to decide
249 which header file is being used; the possibilities are in
250 C<$CGI::SHTML::HEADER>.
251  
252 =cut
253  
254 sub start_html {
255 my ($self, $type, %hash) = @_;
256 $type = lc $type; $type ||= 'default';
257
258 foreach my $key (keys %hash) {
259 if (lc $key eq '-title') { $ENV{'TITLE'} = $hash{$key} }
260 }
261
262 my $command = "<!--#include virtual=\"$HEADER{$type}\"-->";
263  
264 return join("\n", CGI->start_html(\%hash), $self->parse_shtml($command) );
265 }
266  
267 =item end_html ( TYPE, OPTIONS )
268  
269 Loads the appropriate footer file out of C<$CGI::SHTML::FOOTER>, and invokes
270 C<CGI::end_html>.
271  
272 =cut
273  
274 sub end_html {
275 my ($self, $type, %hash) = @_;
276 $type = lc $type; $type ||= 'default';
277
278 my $command = "<!--#include virtual=\"$FOOTER{$type}\"-->";
279  
280 join("\n", $self->parse_shtml($command), CGI->end_html(\%hash));
281 }
282  
283 =back
284  
285 =cut
286  
287 ###############################################################################
288 ### Internal Functions ########################################################
289 ###############################################################################
290  
291 ### _vfile ( FILENAME )
292 # Gets the virtual filename out of FILENAME, based on ROOTDIR. Also
293 # performs the substitutions in C<REPLACE>.
294  
295 sub _vfile {
296 my $filename = shift || return undef;
297  
298 # If it starts with a '$' sign, then get the value out first
299 if ($filename =~ /^\$\{?(\S+)\}?$/) { $filename = $ENV{$1} || ""; }
300  
301 my $hostname = $ENV{'HTTP_HOST'} || $ENV{'HOSTNAME'};
302 foreach my $replace (keys %REPLACE) {
303 next if ($hostname =~ /^www/); # Hack
304 $filename =~ s%$replace%$REPLACE{$replace}%g;
305 }
306 my $newname;
307 if ($filename =~ m%^~(\w+)/(.*)$%) { $newname = "/home/$1/public_html/$2"; }
308 elsif ( $filename =~ m%^[^/]% ) {
309 my ($directory, $program) = $0 =~ m%^(.*)/(.*)$%;
310 $newname = "$directory/$filename"
311 }
312 else { $newname = "$ROOTDIR/$filename" }
313 $newname =~ s%/+%/%g; # Remove doubled-up /'s
314 $newname;
315 }
316  
317 ## _file( FILE )
318 # Open a file and parse it with parse_shtml().
319 sub _file {
320 my ($self, $file) = @_;
321 open( FILE, "<$file" ) or warn "Couldn't open $file: $!\n" && return "";
322 my @list = <FILE>;
323 close (FILE);
324 map { chomp } @list;
325 return $self->parse_shtml(@list);
326 }
327  
328 ## _execute( CMD )
329 # Run a command and get the information about it out. This isn't as
330 # secure as we'd like it to be...
331 sub _execute {
332 my ($self, $cmd) = @_;
333 foreach (qw( IFS CDPATH ENV BASH_ENV PATH ) ) { $ENV{$_} = ""; }
334 my ($command) = $cmd =~ /^(.*)$/; # Not particularly secure
335 open ( COMMAND, "$command |" ) or warn "Couldn't open $command\n";
336 my @list = <COMMAND>;
337 close (COMMAND);
338 map { chomp } @list;
339 return "" unless scalar(@list) > 0; # Didn't return anything
340 # Take out the "Content-type:" part, if it's a CGI - note, THIS IS A HACK
341 if ( scalar(@list) > 1 && $list[0] =~ /^Content-type: (.*)$/i) {
342 shift @list; shift @list;
343 }
344 wantarray ? @list : join("\n", @list);
345 }
346  
347 ## _flastmod( FILE )
348 ## _fsize( FILE )
349 # Last modification and file size of the given FILE, respectively.
350 sub _flastmod { localtime( (stat($_[1]))[9] || 0 ); }
351 sub _fsize {
352 my $size = ((stat($_[1]))[7]) || 0;
353 if ($size >= 1048576) {
354 sprintf("%4.1fMB", $size / 1048576);
355 } elsif ($size >= 1024) {
356 sprintf("%4.1fKB", $size / 1024);
357 } else {
358 sprintf("%4d bytes", $size);
359 }
360 }
361  
362 ## _ssieval( HASHREF )
363 # Evaluates the expression with 'var' or 'expr'. Meant for use with
364 # if/elif clauses. This actually more-or-less works! It's also very
365 # dangerous, though, since it uses 'eval'. Then again, given that we're
366 # already giving the user the capacity to invoke random pieces of code,
367 # it's not realy that much of a stretch...
368 sub _ssieval {
369 my $hash = shift;
370 if (my $var = $$hash{'var'}) { return $var ? 1 : 0 }
371 if (my $eval = $$hash{'expr'}) {
372 $eval =~ s/\s*\$(?:\{(\S+?)\}|(\S+?))\s*
373 / join('', "'", $ENV{$1 || $2} || "", "'" ) /egx;
374 my $val = eval($eval);
375 return $val ? 1 : 0; # Need to do more here.
376 }
377 0
378 }
379  
380 1;
381  
382 ###############################################################################
383 ### Further Documentation #####################################################
384 ###############################################################################
385  
386 =head1 NOTES
387  
388 This module was generated for a single research group at UIUC. Its goal
389 was simple: parse the SSI header and footers that were being used for the
390 rest of the web site, so that they wouldn't have to be re-implemented
391 later. Ideally, we would liked to just have Apache take care of this, but
392 it wasn't an option at the time (and as far as I know it still isn't one.)
393  
394 I mention the above because it's worth understanding the problem before
395 you think about its limitations. This script will not offer particularly
396 high performance for reasonably-sized sites that use a lot of CGI; I doubt
397 it would work at all well with mod_perl, for instance. But it has done
398 the job just fine for our research group, however; and if you want to copy
399 our general website layout, you're going to need something like this to
400 help you out.
401  
402 Also of note is that this has been designed for use so that if headers and
403 footers are not being included, you can generally fall back to the default
404 CGI.pm fairly easily enough.
405  
406 Also of note are the security issues. There are lots of ways for the user
407 to run arbitrary code with this module; however, there were already plenty
408 of ways for them to do it if you're giving them unfettered SSI access.
409 This isn't a change. So make sure that the user that your webserver runs
410 as isn't a particularly priveleged user, and *never* run code through this
411 that came from the outside! You would be a fool to do otherwise.
412  
413 =head1 SEE ALSO
414  
415 C<CGI.pm>
416  
417 =head1 TODO
418  
419 There are still a few functions that should be better implemented (format
420 strings for flastmod(), for instance). It might be nice to make this more
421 object-oriented as well; as it stands this wouldn't stand a chance with
422 mod_perl.
423  
424 =head1 AUTHOR
425  
426 Tim Skirvin <tskirvin@ks.uiuc.edu>
427  
428 =head1 HOMEPAGE
429  
430 B<http://www.ks.uiuc.edu/Development/MDTools/cgi-shtml/>
431  
432 =head1 LICENSE
433  
434 This code is distributed under the University of Illinois Open Source
435 License. See
436 B<http://www.ks.uiuc.edu/Development/MDTools/uiuclicense.html> for
437 details.
438  
439 =head1 COPYRIGHT
440  
441 Copyright 2000-2004 by the University of Illinois Board of Trustees and
442 Tim Skirvin <tskirvin@ks.uiuc.edu>.
443  
444 =cut
445  
446 ###############################################################################
447 ### Version History ###########################################################
448 ###############################################################################
449 # v1.0 Thu Apr 13 13:30:30 CDT 2000
450 ### Documented it, and put this module into its proper home.
451 # v1.1 Thu Apr 20 09:25:28 CDT 2000
452 ### Updated for new page layout, included better counter capabilities, and
453 ### put in the possiblity of hooks for when we need to update this for all
454 ### of the web pages.
455 # v1.11 Thu Apr 20 13:48:28 CDT 2000
456 ### Further updates, added NOCOUNTER flag for error messages
457 # v1.12 Tue Apr 25 13:28:15 CDT 2000
458 ### More updates of the header/footer files
459 # v1.2 Tue Jun 13 09:42:11 CDT 2000
460 ### Now just parses the header/footer files from the main directory, and
461 ### includes a "parse_shtml" function set. Hopefully at some point I'll
462 ### finish off parse_shtml to do all SSI functions.
463 # v1.21 Wed Jun 28 10:56:26 CDT 2000
464 ### Fixed the CGI handlings to trim out the Content-type header.
465 # v1.22 Wed Oct 31 09:46:16 CST 2001
466 ### Fixed _vfile() to do local directory checks properly.
467 ### Changed execute() behaviour to not worry about tainting - probably a
468 ### bad idea, but necessary for now.
469 # v1.23 Mon Dec 10 11:58:25 CST 2001
470 ### Created $EMPTY. Updated 'set' to use variables in its code.
471 # v1.24 Tue Apr 2 13:05:12 CST 2002
472 ### Changed parse_shtml() to remove a warning
473 # v1.25 Tue Mar 11 10:47:36 CST 2003
474 ### Updated to be a more generic name - CGI::SHTML. This will make things
475 ### a lot easier to distribute. Have to make a real package now. Eliminated
476 ### the COUNTER stuff, because it's not in use and was silly anyway. Put
477 ### in 'default' values in the headers/footers
478 # v1.26 Thu Apr 22 15:00:51 CDT 2004
479 ### Making fsize(), flastmod(), etc into internal functions.
480 # v1.26.01 Thu Apr 22 23:32:57 CDT 2004
481 ### Forgot to turn off some debugging information.
482 # v1.27 Thu May 06 10:52:32 CDT 2004
483 ### Added if/elif/else/endif functionality. This was challenging.
484 ### Documentation chanes came with it.
485 # v1.28 Mon May 17 15:15:22 CDT 2004
486 ### Put back old environment variables after an execute.
487 # v1.28 Wed May 19 11:37:06 CDT 2004
488 ### Parsing information is accurate again with parse_shtml - doesn't lose
489 ### newlines. Setting blank versions of those environment variables.
↑ Summary