blib/lib/Win32/ASP.pm untested

filter: Statementstmt 0.0% 0 / 131 Branchbran 0.0% 0 / 38 Conditioncond 0.0% 0 / 5 MC/DCmcdc 0.0% 0 / 3 Subroutinesub 0.0% 0 / 29 Podpod 0.0% 0 / 23 totaltotal 0.0% 0 / 229 CC 20 SCAR 26.7
CC
20
Cov
0%
GetFormValue
42.0
SetCookie
42.0
HTMLEncode
12.0
CRAP 14.4
1 # Win32::ASP.pm
2 #
3 # Win32::ASP - a Module for ASP (PerlScript) Programming
4 #
5 # Authors:
6 # Matt Sergeant (through 2.12)
7 # Bill Odom (2.15 and later)
8 #
9 # Revision: 2.15
10 #
11 # Changes:
12 # - Commented and reformatted code.
13 # - Removed experimental STDIN support (see sections commented out below).
14 # - Removed autosplit/autoloading (for now).
15 # - Removed END block death hook handling.
16 # - Fixed param() call.
17 # - Added LoadEnvironment().
18 # - Began cleaning up the POD.
19 #
20 # Copyright 1998 Matt Sergeant. All rights reserved.
21 #
22 # This file is distributed under the Artistic License. See
23 # http://www.ActiveState.com/corporate/artistic_license.htm or
24 # the license that comes with your perl distribution.
25 #
26
27
28 use strict;
29
30 # print overloading
31
32 package Win32::ASP::IO;
33
34 use Win32::OLE::Variant;
35
36
37 sub new
38 {
39 my $self = bless {}, shift;
40
41 # WNO: Removed experimental STDIN support.
42 #
43 # my $request = shift;
44 # $self->{input_data} = Win32::OLE::Variant->new( VT_UI1, $request->BinaryRead(
45 # $request->{TotalBytes} ) )->Value;
46 # $self->{current_pos} = 0;
47 #
48
49 $self;
50 }
51 # end sub new
52
53
54 sub print
55 {
56 my $self = shift;
57 Win32::ASP::Print(@_);
58 1;
59 }
60 # end sub print
61
62
63 sub TIEHANDLE { shift->new(@_) }
64 sub PRINT { shift->print(@_) }
65 sub PRINTF { shift->print(sprintf(@_)) }
66
67 # WNO: Removed experimental STDIN support.
68 #
69 # sub READ
70 # {
71 # my $self = shift;
72 # my $bufref;
73 #
74 # $$bufref = \$_[0];
75 #
76 # my (undef, $len, $offset) = @_;
77 #
78 # if (defined $offset)
79 # {
80 # $self->{current_pos} = $offset;
81 # }
82 #
83 # my $string = substr($self->{input_data}, $self->{current_pos}, $len);
84 #
85 # $self->{current_pos} += $len;
86 #
87 # $$bufref = $string;
88 #
89 # return length($string);
90 #
91 # }
92 # # end sub READ
93 #
94 #
95 # sub READLINE
96 # {
97 # my $self = shift;
98 # my $string;
99 # while (my $char = $self->GETC)
100 # {
101 # $string .= $char;
102 # last if $char eq "\015";
103 # }
104 # return $string;
105 # }
106 # # end sub READLINE
107 #
108 #
109 # sub GETC
110 # {
111 # my $char;
112 #
113 # return undef unless shift->READ($char, 1);
114 # return $char;
115 # }
116 # # end sub GETC
117 #
118
119 1;
120
121 # end print overloading
122
123
124
125 ## Win32::ASP Module Interface
126
127 package Win32::ASP;
128
129 use vars qw( $VERSION @ISA @EXPORT @EXPORT_OK );
130
131 BEGIN
132 {
133 require Exporter;
134 # require AutoLoader;
135
136 use vars
137 qw(
138 @ISA
139 @EXPORT
140 @EXPORT_OK
141 %EXPORT_TAGS
142
143 $Application
144 $ObjectContext
145 $Request
146 $Response
147 $Server
148 $Session
149
150 @DeathHooks
151 );
152
153 @ISA =
154 qw(
155 Exporter
156 # AutoLoader
157 );
158
159 @EXPORT =
160 qw(
161 Print
162 wprint
163 die
164 exit
165 GetFormValue
166 GetFormCount
167 param
168 );
169
170 %EXPORT_TAGS =
171 (
172 strict =>
173 [ qw(
174 Print
175 wprint
176 die
177 exit
178 GetFormValue
179 GetFormCount
180
181 $Application
182 $ObjectContext
183 $Request
184 $Response
185 $Server
186 $Session
187 ) ]
188 );
189
190 @EXPORT_OK = qw( SetCookie );
191
192 # Add all strict vars to @EXPORT_OK.
193 #
194 Exporter::export_ok_tags('strict');
195
196 # Set up the exportable ASP objects, while avoiding "only used once"
197 # warnings.
198 #
199 $Application = $::Application = $::Application;
200 $ObjectContext = $::ObjectContext = $::ObjectContext;
201 $Request = $::Request = $::Request;
202 $Response = $::Response = $::Response;
203 $Server = $::Server = $::Server;
204 $Session = $::Session = $::Session;
205
206 }
207 # end BEGIN block
208
209
210 $VERSION='2.15';
211
212 # Create tied filehandle for print overloading.
213 #
214 tie *RESPONSE_FH, 'Win32::ASP::IO';
215 select RESPONSE_FH;
216
217 # WNO: Removed experimental STDIN support.
218 #
219 # close STDIN;
220 # tie *STDIN, 'Win32::ASP::IO', $Request;
221 #
222
223
224 # Preloaded methods go here.
225
226
227 sub _END
228 {
229 my $func;
230
231 for $func (@DeathHooks)
232 {
233 $func->();
234 }
235 }
236 # end sub _END
237
238
239 # Autoload methods go after =cut, and are processed by the autosplit program.
240
241 # WNO: Commented out until I reinstate autoloading.
242
243 # 1;
244 # __END__
245
246 =head1 NAME
247
248 Win32::ASP - a module for ASP (PerlScript) Programming
249
250 =head1 SYNOPSIS
251
252 use Win32::ASP;
253
254 print "This is a test<BR><BR>";
255
256 $PageName = GetFormValue('PageName');
257
258 if ($PageName eq 'Select a page...')
259 {
260 die "Please go back and select a value from the Pages list.";
261 }
262
263 print "You selected the ", $PageName, " page.<BR>";
264
265 exit;
266
267 =head1 DESCRIPTION
268
269 I knocked these routines together one day when I was wondering
270 "Why don't my C<print> statements output to the browser?" and
271 "Why don't C<exit> and C<die> end my script?" So I started investigating how
272 I could overload the core functions. C<print> is overloaded via the C<tie>
273 mechanism (thanks to Eryq (F<eryq@zeegee.com>), Zero G Inc. for the
274 code which I ripped from IO::Scalar).
275
276 Also added recently was C<AddDeathHook>, which allows cleanup code to
277 be executed upon an C<exit> or C<die>. C<BinaryWrite> wraps up Unicode
278 conversion and C<< $Response->BinaryWrite >> in one call. Finally, I was
279 annoyed that I couldn't just develop a script using GET, then change to
280 POST for release, since ASP code handles each one differently. C<GetFormValue>
281 solves that one.
282
283 =head2 Installation instructions
284
285 Assuming the ActiveState repository is up-to-date with the latest archive
286 from CPAN, you should be able to type:
287
288 ppm install Win32-ASP
289
290 on the command line. Make sure you're connected to the Internet first.
291
292 Installing via MakeMaker is pretty standard -- just download
293 the archive from CPAN, extract it to some directory, then type in that
294 directory:
295
296 perl Makefile.PL
297 nmake
298 nmake install
299
300 Don't do C<nmake test> because the ASP objects won't be available.
301
302
303 =head1 Function Reference
304
305 =head2 Print LIST
306
307 Obsolete - use C<print> instead.
308
309 Outputs a string or comma-separated list of strings to the browser. Use
310 as if you were using C<print> in a CGI application. C<Print> handles the ASP
311 limitation of 128K per C<< $Response->Write >> call.
312
313 Note: C<print> calls C<Print>, so you can actually use either one,
314 but C<print> is more integrated with "the Perl way."
315
316 =cut
317
318 sub Print
319 {
320 for my $output (@_)
321 {
322 if (length($output) > 128000)
323 {
324 Win32::ASP::Print(unpack('a128000a*', $output));
325 }
326 else
327 {
328 $::Response->Write($output);
329 }
330 }
331 }
332 # end sub Print
333
334
335 =head2 DebugPrint LIST
336
337 The same as C<Print>, except the output is wrapped in HTML comment markers,
338 so that you can only see it by viewing the page source. C<DebugPrint> is
339 not exported, so call it as
340
341 Win32::ASP::DebugPrint($val);
342
343 This function is useful for debugging your application. For example, I
344 use it to print out SQL before it is executed.
345
346 =cut
347
348 sub DebugPrint(@)
349 {
350 Print "<!-- ", @_, " -->\n";
351 }
352 # end sub DebugPrint
353
354
355 =head2 HTMLPrint LIST
356
357 The same as C<Print>, except the output is encoded so that
358 any HTML tags appear as sent, i.e. E<lt> becomes &lt;, E<gt> becomes &gt;, etc.
359 C<HTMLPrint> is not exported, so call it as
360
361 Win32::ASP::HTMLPrint($val);
362
363 This function is useful for printing output that comes from a database
364 or a file, where you don't have total control over the input.
365
366 =cut
367
368 sub HTMLPrint(@)
369 {
370 for my $output (@_)
371 {
372 Print $::Server->HTMLEncode($output);
373 }
374 }
375 # end sub HTMLPrint
376
377
378 =head2 wprint LIST
379
380 Deprecated - use C<print> instead.
381
382 =cut
383
384 # WNO: Consider changing the wprint-to-Print calling method, similar to
385 # the param-to-GetFormValue change.
386
387 sub wprint(@)
388 {
389 Print @_;
390 }
391 # end sub wprint
392
393
394 =head2 die LIST
395
396 Outputs the contents of LIST to the browser and then exits. C<die> automatically
397 calls C<< $Response->End >> and executes any cleanup code added with
398 C<AddDeathHook>.
399
400 =cut
401
402 sub die(@)
403 {
404 Print @_;
405 Print "</BODY></HTML>";
406 _END;
407 $::Response->End();
408 CORE::die();
409 }
410 # end sub die
411
412
413 =head2 exit
414
415 Exits the current script. C<exit> automatically
416 calls C<< $Response->End >> and executes any cleanup code added with
417 C<AddDeathHook>.
418
419 =cut
420
421 # WNO: This prototype doesn't seem to do very much here,
422 # since the optional argument isn't used.
423
424 sub exit(;$)
425 {
426 _END;
427 $::Response->End();
428 CORE::exit();
429 }
430 # end sub exit
431
432
433 =head2 HTMLEncode LIST
434
435 The same as C<HTMLPrint>, except the output is not printed but returned
436 as a scalar instead. C<HTMLEncode> is not exported, so call it as
437
438 my $text = Win32::ASP::HTMLEncode($val);
439
440 This function is useful to handle output that comes from a database
441 or a file, where you don't have total control over the input.
442
443 If an array reference is passed, C<HTMLEncode> uses it. Otherwise, it assumes
444 an array of scalars is used. Using a reference makes for less time spent
445 passing values back and forth, and is the prefered method.
446
447 =cut
448
449 sub HTMLEncode(@)
450 {
451 my (@encodedHTML,$output) = (@_);
452 my $ref = 0;
453
454 if (ref $encodedHTML[0] eq "ARRAY")
455 {
456 @encodedHTML = @{$encodedHTML[0]};
457 $ref++;
458 }
459
460 for $output (@encodedHTML)
461 {
462 $output = $::Server->HTMLEncode($output);
463 }
464
465 return $ref ? \@encodedHTML : @encodedHTML;
466 }
467 # end sub HTMLEncode
468
469
470 =head2 GetFormValue EXPR [, EXPR]
471
472 Returns the value passed from a form (or non-form GET request). Use this
473 method if you want to be able to develop in GET mode (for ease of debugging)
474 and move to POST mode for release. The second (optional) parameter is for
475 getting multiple parameters, as in
476
477 http://localhost/scripts/test.asp?Q=a&Q=b
478
479 In the above, S<C<GetFormValue("Q", 1)>> returns "a" and S<C<GetFormValue("Q", 2)>>
480 returns "b".
481
482 C<GetFormValue> will work in an array context too, returning all the values
483 for a particular parameter. For example, with the above URL:
484
485 my @AllQs = GetFormValue('Q');
486
487 will result in the array C<@AllQs> containing C<('a', 'b')>.
488
489 If you call C<GetFormValue> without any parameters, it will
490 return a list of form parameters in the same way that CGI.pm's C<param>
491 function does. This allows easy iteration over the form elements:
492
493 for my $key (GetFormValue())
494 {
495 print "$key = ", GetFormValue($key), "<br>\n";
496 }
497
498 For convenience, Win32::ASP exports C<param> as an alias for C<GetFormValue>.
499
500 =cut
501
502 # WNO: Replace the $_[1] with a named parameter, if possible.
503 #
504 # WNO: Is the processing of both the query string *and* the form
505 # the correct thing to do here?
506 #
507
508 sub GetFormValue(;$$)
509 {
510
511 unless (@_)
512 {
513 my @keys;
514
515 for my $f (Win32::OLE::in ($::Request->QueryString))
516 {
517 push @keys, $f;
518 }
519
520 for my $f (Win32::OLE::in ($::Request->Form))
521 {
522 push @keys, $f;
523 }
524
525 return @keys;
526 }
527
528 $_[1] = 1 unless defined $_[1];
529
530 if (!wantarray)
531 {
532 if ($::Request->ServerVariables('REQUEST_METHOD')->Item eq 'GET')
533 {
534 return $::Request->QueryString($_[0])->Item($_[1]);
535 }
536 else
537 {
538 return $::Request->Form($_[0])->Item($_[1]);
539 }
540 }
541 else
542 {
543 my ($i, @ret);
544
545 if ($::Request->ServerVariables('REQUEST_METHOD')->Item eq 'GET')
546 {
547 my $count = $::Request->QueryString($_[0])->{Count};
548
549 for ($i = 1; $i <= $count; $i++ )
550 {
551 push @ret, $::Request->QueryString($_[0])->Item($i);
552 }
553 }
554 else
555 {
556 my $count = $::Request->Form($_[0])->{Count};
557 for ($i = 1; $i <= $count; $i++)
558 {
559 push @ret, $::Request->Form($_[0])->Item($i);
560 }
561 }
562
563 return @ret;
564 }
565 # end if (!wantarray)
566
567 }
568 # end sub GetFormValue
569
570
571 =head2 param EXPR [, EXPR]
572
573 C<param> is an alias for C<GetFormValue>.
574
575 =cut
576
577 # WNO: Since param() wasn't working, I've changed this to use
578 # the & form of subroutine call, so the @_ argument list is passed directly.
579 # I think this also has an affect on the context, but I'm not certain.
580 #
581
582 sub param { &GetFormValue; }
583
584
585 =head2 GetFormCount EXPR
586
587 Returns the number of times EXPR appears in the request (Form or QueryString).
588 Use this value as C<$i> to iterate over S<C<GetFormValue(EXPR, $i)>>.
589
590 For example, if the URL is:
591
592 http://localhost/scripts/myscript.asp?Q=a&Q=b
593
594 And code is:
595
596 my $numQs = GetFormCount('Q');
597
598 Then C<$numQs> will equal 2.
599
600 =cut
601
602 sub GetFormCount($)
603 {
604 if ($::Request->ServerVariables('REQUEST_METHOD')->Item eq 'GET')
605 {
606 return $::Request->QueryString($_[0])->Count;
607 }
608 else
609 {
610 return $::Request->Form($_[0])->Count;
611 }
612
613 }
614 # end sub GetFormCount
615
616
617 =head2 AddDeathHook LIST
618
619 This frightening-sounding function allows you to have cleanup code
620 executed when you C<die> or C<exit>. For example, you may want to
621 disconnect from your database if there is a problem:
622
623 <%
624 my $Conn = $Server->CreateObject('ADODB.Connection');
625 $Conn->Open( "DSN=BADEV1;UID=sa;DATABASE=ProjAlloc" );
626 $Conn->BeginTrans();
627
628 Win32::ASP::AddDeathHook( sub { $Conn->Close if $Conn; } );
629 %>
630
631 Now when you C<die> because of an error, your database connection
632 will close gracefully, instead of you having loads of rogue connections
633 that you have to kill by hand, or restart your database once a day.
634
635 Death hooks are not executed upon the normal termination of the script,
636 so if you have processing that should occur upon a normal exit,
637 be sure to execute it directly.
638
639 =cut
640
641 sub AddDeathHook(@)
642 {
643 push @DeathHooks, @_;
644 }
645 # end sub AddDeathHook
646
647
648 # WNO: I've removed this for now, since the execution of END blocks is
649 # inconsistent among different PerlScript versions.
650 #
651 # According to my very brief tests, END blocks seem to run under builds
652 # 516 and 522, but not under 623 (or at least not visibly). I don't yet
653 # know how they act under other builds.
654 #
655 # END
656 # {
657 # my $func;
658 #
659 # for $func (@DeathHooks)
660 # {
661 # &$func();
662 # }
663 # }
664 # # end END block
665
666
667 =head2 BinaryWrite LIST
668
669 Performs the same function as C<< $Response->BinaryWrite >>, but handles
670 Perl's Unicode-related null padding. This function is not exported,
671 so call it as
672
673 Win32::ASP::BinaryWrite($val);
674
675 =cut
676
677 use Win32::OLE::Variant;
678
679 sub BinaryWrite(@)
680 {
681 for my $output (@_)
682 {
683 if (length($output) > 128000)
684 {
685 BinaryWrite(unpack('a128000a*', $output));
686 }
687 else
688 {
689 my $variant = Win32::OLE::Variant->new( VT_UI1, $output );
690 $::Response->BinaryWrite($variant);
691 }
692 }
693 }
694 # end sub BinaryWrite
695
696
697 =head2 LoadEnvironment
698
699 Copies the C<< $Request->ServerVariables >> collection
700 to the C<%ENV> hash, allowing the values to be accessed as environment variables.
701 Changes to C<%ENV> are not propagated back to the C<ServerVariables>
702 collection, and changes to the C<ServerVariables> collection do not automatically
703 appear in C<%ENV>. To see any such changes, simply run C<LoadEnvironment> again.
704
705 C<LoadEnvironment> is not exported, so run it as follows:
706
707 Win32::ASP::LoadEnvironment;
708
709 =cut
710
711 sub LoadEnvironment
712 {
713 for my $svar (Win32::OLE::in($::Request->ServerVariables))
714 {
715 $ENV{$svar} = $::Request->ServerVariables($svar)->{Item};
716 }
717 }
718 # end sub LoadEnvironment
719
720
721 # These two functions are ripped from CGI.pm
722
723 # WNO: I'm leaving expire_calc and data alone for now.
724
725 sub expire_calc {
726 my($time) = @_;
727 my(%mult) = ('s'=>1,
728 'm'=>60,
729 'h'=>60*60,
730 'd'=>60*60*24,
731 'M'=>60*60*24*30,
732 'y'=>60*60*24*365);
733 # format for time can be in any of the forms...
734 # "now" -- expire immediately
735 # "+180s" -- in 180 seconds
736 # "+2m" -- in 2 minutes
737 # "+12h" -- in 12 hours
738 # "+1d" -- in 1 day
739 # "+3M" -- in 3 months
740 # "+2y" -- in 2 years
741 # "-3m" -- 3 minutes ago(!)
742 # If you don't supply one of these forms, we assume you are
743 # specifying the date yourself
744 my($offset);
745 if (!$time || ($time eq 'now')) {
746 $offset = 0;
747 } elsif ($time=~/^([+-]?\d+)([mhdMy]?)/) {
748 $offset = ($mult{$2} || 1)*$1;
749 } else {
750 return $time;
751 }
752 return (time+$offset);
753 }
754
755 sub date {
756 my($time,$format) = @_;
757 my(@MON)=qw/Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec/;
758 my(@WDAY) = qw/Sun Mon Tue Wed Thu Fri Sat/;
759
760 # pass through preformatted dates for the sake of expire_calc()
761 if ("$time" =~ m/^[^0-9]/o) {
762 return $time;
763 }
764
765 # make HTTP/cookie date string from GMT'ed time
766 # (cookies use '-' as date separator, HTTP uses ' ')
767 my($sc) = ' ';
768 $sc = '-' if $format eq "cookie";
769 my($sec,$min,$hour,$mday,$mon,$year,$wday) = gmtime($time);
770 $year += 1900;
771 return sprintf("%s, %02d$sc%s$sc%04d %02d:%02d:%02d GMT",
772 $WDAY[$wday],$mday,$MON[$mon],$year,$hour,$min,$sec);
773 }
774
775 =head2 SetCookie Name, Value [, HASH]
776
777 Sets the cookie I<Name> with the value I<Value>. The optional HASH can
778 contain any of the following parameters:
779
780 =over 4
781
782 =item * -expires => A CGI.pm style expires value (see the CGI.pm header() documentation).
783
784 =item * -domain => a domain in the style ".matt.com" that the cookie is returned to.
785
786 =item * -path => a path that the cookie is returned to.
787
788 =item * -secure => cookie only gets returned under SSL if this is true.
789
790 =back
791
792 If I<Value> is a hash reference, then it creates a cookie dictionary. See
793 the ASP docs for more info on cookie dictionaries.
794
795 Example:
796
797 Win32::ASP::SetCookie("Matt", "Sergeant", ( -expires => "+3h",
798 -domain => ".matt.com",
799 -path => "/users/matt",
800 -secure => 0 ));
801
802 =cut
803
804
805 sub SetCookie($$;%)
806 {
807 my ($name, $value, %hash) = @_;
808
809 if (ref($value) eq 'HASH')
810 {
811 $value = join( "\&" ,
812 map { $::Server->URLEncode($_) . '=' . $::Server->URLEncode($$value{$_}) }
813 keys(%$value)
814 )
815 }
816
817 $::Response->AddHeader( 'Set-Cookie',
818 "$name=$value"
819 . ($hash{-path} ? "; path=" . $hash{-path} : "")
820 . ($hash{-domain} ? "; domain=" . $hash{-domain} : "")
821 . ($hash{-secure} ? "; secure" : "")
822 . ($hash{-expires} ? "; expires=" . &date(&expire_calc($hash{-expires})) : "")
823 );
824 }
825 # end sub SetCookie
826
827 =head1 AUTHORS
828
829 Originally created by Matt Sergeant E<lt>F<matt@sergeant.org>E<gt>.
830
831 Currently being maintained and updated by Bill Odom E<lt>F<wnodom@intrasection.com>E<gt>.
832
833 =cut
834
835 # end module Win32::ASP