📄 cgi.pm
字号:
package CGI;require 5.004;use Carp 'croak';# See the bottom of this file for the POD documentation. Search for the# string '=head'.# You can run this file through either pod2man or pod2html to produce pretty# documentation in manual or html file format (these utilities are part of the# Perl 5 distribution).# Copyright 1995-1998 Lincoln D. Stein. All rights reserved.# It may be used and modified freely, but I do request that this copyright# notice remain attached to the file. You may modify this module as you # wish, but if you redistribute a modified version, please attach a note# listing the modifications you have made.# The most recent version and complete docs are available at:# http://stein.cshl.org/WWW/software/CGI/$CGI::revision = '$Id: CGI.pm,v 1.49 2001/02/04 23:08:39 lstein Exp $';$CGI::VERSION='2.752';# HARD-CODED LOCATION FOR FILE UPLOAD TEMPORARY FILES.# UNCOMMENT THIS ONLY IF YOU KNOW WHAT YOU'RE DOING.# $TempFile::TMPDIRECTORY = '/usr/tmp';use CGI::Util qw(rearrange make_attributes unescape escape expires);use constant XHTML_DTD => ['-//W3C//DTD XHTML Basic 1.0//EN', 'http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd'];# >>>>> Here are some globals that you might want to adjust <<<<<<sub initialize_globals { # Set this to 1 to enable copious autoloader debugging messages $AUTOLOAD_DEBUG = 0; # Set this to 1 to generate XTML-compatible output $XHTML = 1; # Change this to the preferred DTD to print in start_html() # or use default_dtd('text of DTD to use'); $DEFAULT_DTD = [ '-//W3C//DTD HTML 4.01 Transitional//EN', 'http://www.w3.org/TR/html4/loose.dtd' ] ; # Set this to 1 to enable NOSTICKY scripts # or: # 1) use CGI qw(-nosticky) # 2) $CGI::nosticky(1) $NOSTICKY = 0; # Set this to 1 to enable NPH scripts # or: # 1) use CGI qw(-nph) # 2) CGI::nph(1) # 3) print header(-nph=>1) $NPH = 0; # Set this to 1 to enable debugging from @ARGV # Set to 2 to enable debugging from STDIN $DEBUG = 1; # Set this to 1 to make the temporary files created # during file uploads safe from prying eyes # or do... # 1) use CGI qw(:private_tempfiles) # 2) CGI::private_tempfiles(1); $PRIVATE_TEMPFILES = 0; # Set this to a positive value to limit the size of a POSTing # to a certain number of bytes: $POST_MAX = -1; # Change this to 1 to disable uploads entirely: $DISABLE_UPLOADS = 0; # Automatically determined -- don't change $EBCDIC = 0; # Change this to 1 to suppress redundant HTTP headers $HEADERS_ONCE = 0; # separate the name=value pairs by semicolons rather than ampersands $USE_PARAM_SEMICOLONS = 1; # Other globals that you shouldn't worry about. undef $Q; $BEEN_THERE = 0; undef @QUERY_PARAM; undef %EXPORT; undef $QUERY_CHARSET; undef %QUERY_FIELDNAMES; # prevent complaints by mod_perl 1;}# ------------------ START OF THE LIBRARY ------------# make mod_perlhappyinitialize_globals();# FIGURE OUT THE OS WE'RE RUNNING UNDER# Some systems support the $^O variable. If not# available then require() the Config libraryunless ($OS) { unless ($OS = $^O) { require Config; $OS = $Config::Config{'osname'}; }}if ($OS =~ /^MSWin/i) { $OS = 'WINDOWS';} elsif ($OS =~ /^VMS/i) { $OS = 'VMS';} elsif ($OS =~ /^dos/i) { $OS = 'DOS';} elsif ($OS =~ /^MacOS/i) { $OS = 'MACINTOSH';} elsif ($OS =~ /^os2/i) { $OS = 'OS2';} elsif ($OS =~ /^epoc/i) { $OS = 'EPOC';} else { $OS = 'UNIX';}# Some OS logic. Binary mode enabled on DOS, NT and VMS$needs_binmode = $OS=~/^(WINDOWS|DOS|OS2|MSWin)/;# This is the default class for the CGI object to use when all else fails.$DefaultClass = 'CGI' unless defined $CGI::DefaultClass;# This is where to look for autoloaded routines.$AutoloadClass = $DefaultClass unless defined $CGI::AutoloadClass;# The path separator is a slash, backslash or semicolon, depending# on the paltform.$SL = { UNIX=>'/', OS2=>'\\', EPOC=>'/', WINDOWS=>'\\', DOS=>'\\', MACINTOSH=>':', VMS=>'/' }->{$OS};# This no longer seems to be necessary# Turn on NPH scripts by default when running under IIS server!# $NPH++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;$IIS++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;# Turn on special checking for Doug MacEachern's modperlif (exists $ENV{'GATEWAY_INTERFACE'} && ($MOD_PERL = $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-Perl\//)){ $| = 1; require Apache;}# Turn on special checking for ActiveState's PerlEx$PERLEX++ if defined($ENV{'GATEWAY_INTERFACE'}) && $ENV{'GATEWAY_INTERFACE'} =~ /^CGI-PerlEx/;# Define the CRLF sequence. I can't use a simple "\r\n" because the meaning# of "\n" is different on different OS's (sometimes it generates CRLF, sometimes LF# and sometimes CR). The most popular VMS web server# doesn't accept CRLF -- instead it wants a LR. EBCDIC machines don't# use ASCII, so \015\012 means something different. I find this all # really annoying.$EBCDIC = "\t" ne "\011";if ($OS eq 'VMS') { $CRLF = "\n";} elsif ($EBCDIC) { $CRLF= "\r\n";} else { $CRLF = "\015\012";}if ($needs_binmode) { $CGI::DefaultClass->binmode(main::STDOUT); $CGI::DefaultClass->binmode(main::STDIN); $CGI::DefaultClass->binmode(main::STDERR);}%EXPORT_TAGS = ( ':html2'=>['h1'..'h6',qw/p br hr ol ul li dl dt dd menu code var strong em tt u i b blockquote pre img a address cite samp dfn html head base body Link nextid title meta kbd start_html end_html input Select option comment charset escapeHTML/], ':html3'=>[qw/div table caption th td TR Tr sup Sub strike applet Param embed basefont style span layer ilayer font frameset frame script small big/], ':netscape'=>[qw/blink fontsize center/], ':form'=>[qw/textfield textarea filefield password_field hidden checkbox checkbox_group submit reset defaults radio_group popup_menu button autoEscape scrolling_list image_button start_form end_form startform endform start_multipart_form end_multipart_form isindex tmpFileName uploadInfo URL_ENCODED MULTIPART/], ':cgi'=>[qw/param upload path_info path_translated url self_url script_name cookie Dump raw_cookie request_method query_string Accept user_agent remote_host content_type remote_addr referer server_name server_software server_port server_protocol virtual_host remote_ident auth_type http save_parameters restore_parameters param_fetch remote_user user_name header redirect import_names put Delete Delete_all url_param cgi_error/], ':ssl' => [qw/https/], ':imagemap' => [qw/Area Map/], ':cgi-lib' => [qw/ReadParse PrintHeader HtmlTop HtmlBot SplitParam Vars/], ':html' => [qw/:html2 :html3 :netscape/], ':standard' => [qw/:html2 :html3 :form :cgi/], ':push' => [qw/multipart_init multipart_start multipart_end multipart_final/], ':all' => [qw/:html2 :html3 :netscape :form :cgi :internal/] );# to import symbols into callersub import { my $self = shift;# This causes modules to clash. # undef %EXPORT_OK;# undef %EXPORT; $self->_setup_symbols(@_); my ($callpack, $callfile, $callline) = caller; # To allow overriding, search through the packages # Till we find one in which the correct subroutine is defined. my @packages = ($self,@{"$self\:\:ISA"}); foreach $sym (keys %EXPORT) { my $pck; my $def = ${"$self\:\:AutoloadClass"} || $DefaultClass; foreach $pck (@packages) { if (defined(&{"$pck\:\:$sym"})) { $def = $pck; last; } } *{"${callpack}::$sym"} = \&{"$def\:\:$sym"}; }}sub compile { my $pack = shift; $pack->_setup_symbols('-compile',@_);}sub expand_tags { my($tag) = @_; return ("start_$1","end_$1") if $tag=~/^(?:\*|start_|end_)(.+)/; my(@r); return ($tag) unless $EXPORT_TAGS{$tag}; foreach (@{$EXPORT_TAGS{$tag}}) { push(@r,&expand_tags($_)); } return @r;}#### Method: new# The new routine. This will check the current environment# for an existing query string, and initialize itself, if so.####sub new { my($class,$initializer) = @_; my $self = {}; bless $self,ref $class || $class || $DefaultClass; if ($MOD_PERL && defined Apache->request) { Apache->request->register_cleanup(\&CGI::_reset_globals); undef $NPH; } $self->_reset_globals if $PERLEX; $self->init($initializer); return $self;}# We provide a DESTROY method so that the autoloader# doesn't bother trying to find it.sub DESTROY { }#### Method: param# Returns the value(s)of a named parameter.# If invoked in a list context, returns the# entire list. Otherwise returns the first# member of the list.# If name is not provided, return a list of all# the known parameters names available.# If more than one argument is provided, the# second and subsequent arguments are used to# set the value of the parameter.####sub param { my($self,@p) = self_or_default(@_); return $self->all_parameters unless @p; my($name,$value,@other); # For compatibility between old calling style and use_named_parameters() style, # we have to special case for a single parameter present. if (@p > 1) { ($name,$value,@other) = rearrange([NAME,[DEFAULT,VALUE,VALUES]],@p); my(@values); if (substr($p[0],0,1) eq '-') { @values = defined($value) ? (ref($value) && ref($value) eq 'ARRAY' ? @{$value} : $value) : (); } else { foreach ($value,@other) { push(@values,$_) if defined($_); } } # If values is provided, then we set it. if (@values) { $self->add_parameter($name); $self->{$name}=[@values]; } } else { $name = $p[0]; } return unless defined($name) && $self->{$name}; return wantarray ? @{$self->{$name}} : $self->{$name}->[0];}sub self_or_default { return @_ if defined($_[0]) && (!ref($_[0])) &&($_[0] eq 'CGI'); unless (defined($_[0]) && (ref($_[0]) eq 'CGI' || UNIVERSAL::isa($_[0],'CGI')) # slightly optimized for common case ) { $Q = $CGI::DefaultClass->new unless defined($Q); unshift(@_,$Q); } return wantarray ? @_ : $Q;}sub self_or_CGI { local $^W=0; # prevent a warning if (defined($_[0]) && (substr(ref($_[0]),0,3) eq 'CGI' || UNIVERSAL::isa($_[0],'CGI'))) { return @_; } else { return ($DefaultClass,@_); }}######################################### THESE METHODS ARE MORE OR LESS PRIVATE# GO TO THE __DATA__ SECTION TO SEE MORE# PUBLIC METHODS######################################### Initialize the query object from the environment.# If a parameter list is found, this object will be set# to an associative array in which parameter names are keys# and the values are stored as lists# If a keyword list is found, this method creates a bogus# parameter list with the single parameter 'keywords'.sub init { my($self,$initializer) = @_; my($query_string,$meth,$content_length,$fh,@lines) = ('','','',''); local($/) = "\n"; # if we get called more than once, we want to initialize # ourselves from the original query (which may be gone # if it was read from STDIN originally.) if (defined(@QUERY_PARAM) && !defined($initializer)) { foreach (@QUERY_PARAM) { $self->param('-name'=>$_,'-value'=>$QUERY_PARAM{$_}); } $self->charset($QUERY_CHARSET); $self->{'.fieldnames'} = {%QUERY_FIELDNAMES}; return; } $meth=$ENV{'REQUEST_METHOD'} if defined($ENV{'REQUEST_METHOD'}); $content_length = defined($ENV{'CONTENT_LENGTH'}) ? $ENV{'CONTENT_LENGTH'} : 0; $fh = to_filehandle($initializer) if $initializer; # set charset to the safe ISO-8859-1 $self->charset('ISO-8859-1'); METHOD: { # avoid unreasonably large postings if (($POST_MAX > 0) && ($content_length > $POST_MAX)) { $self->cgi_error("413 Request entity too large"); last METHOD; } # Process multipart postings, but only if the initializer is # not defined. if ($meth eq 'POST' && defined($ENV{'CONTENT_TYPE'}) && $ENV{'CONTENT_TYPE'}=~m|^multipart/form-data| && !defined($initializer) ) { my($boundary) = $ENV{'CONTENT_TYPE'} =~ /boundary=\"?([^\";,]+)\"?/; $self->read_multipart($boundary,$content_length); last METHOD; } # If initializer is defined, then read parameters # from it. if (defined($initializer)) { if (UNIVERSAL::isa($initializer,'CGI')) { $query_string = $initializer->query_string; last METHOD; } if (ref($initializer) && ref($initializer) eq 'HASH') { foreach (keys %$initializer) { $self->param('-name'=>$_,'-value'=>$initializer->{$_}); } last METHOD; } if (defined($fh) && ($fh ne '')) { while (<$fh>) { chomp; last if /^=/; push(@lines,$_); } # massage back into standard format if ("@lines" =~ /=/) { $query_string=join("&",@lines); } else { $query_string=join("+",@lines); } last METHOD; } # last chance -- treat it as a string $initializer = $$initializer if ref($initializer) eq 'SCALAR'; $query_string = $initializer; last METHOD; }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -