Apache :: ASP :: OBJECTS

| INTRO
| INSTALL
| CONFIG
| SYNTAX
| EVENTS
% | OBJECTS
| SSI
| SESSIONS
| XML/XSLT
| CGI
| PERLSCRIPT
| FAQ
| TUNING
| CREDITS
| SUPPORT
| SITES USING
| RESOURCES
| TODO
| CHANGES
| EXAMPLES
| OBJECTS
The beauty of the ASP Object Model is that it takes the burden of CGI and Session Management off the developer, and puts them in objects accessible from any ASP script & include. For the perl programmer, treat these objects as globals accessible from anywhere in your ASP application.
      Currently the Apache::ASP object model supports the following:

        Object	 -	Function
        ------		--------
        $Session	 -	user session state
        $Response	 -	output to browser
        $Request	 -	input from browser
        $Application -	application state
        $Server	 -	general support methods
These objects, and their methods are further defined in the following sections.
$Session Object | $Response->Write($data)
$Session->{CodePage} |
$Session->{LCID} | $Request Object
$Session->{SessionID} | $Request->{TotalBytes}
$Session->{Timeout} [= $minutes] | $Request->BinaryRead($length)
$Session->Abandon() | $Request->ClientCertificate()
$Session->Lock() | $Request->Cookies($name [,$key])
$Session->UnLock() | $Request->FileUpload($form_field, $key)
| $Request->Form($name)
$Response Object | $Request->QueryString($name)
$Response->{BinaryRef} | $Request->ServerVariables($name)
$Response->{Buffer} |
$Response->{CacheControl} | $Application Object
$Response->{Charset} | $Application->Lock()
$Response->{Clean} = 0-9; | $Application->UnLock()
$Response->{ContentType} = "text/html" | $Application->GetSession($sess_id)
$Response->{Expires} = $time | $Application->SessionCount()
$Response->{ExpiresAbsolute} = $date |
$Response->{IsClientConnected} | $Server Object
$Response->{PICS} | $Server->{ScriptTimeout} = $seconds
$Response->{Status} = $status | $Server->Config($setting)
$Response->AddHeader($name, $value) | $Server->CreateObject($program_id)
$Response->AppendToLog($message) | $Server->Execute($file, @args)
$Response->BinaryWrite($data) | $Server->GetLastError()
$Response->Clear() | $Server->HTMLEncode($string)
$Response->Cookies($name, [$key,] $value) | $Server->MapPath($url);
$Response->Debug(@args) | $Server->Mail(\%mail, %smtp_args);
$Response->End() | $Server->Transfer($file)
$Response->ErrorDocument($code, $uri) | $Server->URLEncode($string)
$Response->Flush() | $Server->RegisterCleanup($sub)
$Response->Include($filename, @args) | $Server->URL($url, \%params)
$Response->Redirect($url) |
$Session Object
The $Session object keeps track of user and web client state, in a persistent manner, making it relatively easy to develop web applications. The $Session state is stored across HTTP connections, in database files in the Global or StateDir directories, and will persist across web server restarts.
The user session is referenced by a 128 bit / 32 byte MD5 hex hashed cookie, and can be considered secure from session id guessing, or session hijacking. When a hacker fails to guess a session, the system times out for a second, and with 2**128 (3.4e38) keys to guess, a hacker will not be guessing an id any time soon.
If an incoming cookie matches a timed out or non-existent session, a new session is created with the incoming id. If the id matches a currently active session, the session is tied to it and returned. This is also similar to the Microsoft ASP implementation.
The $Session reference is a hash ref, and can be used as such to store data as in:
        $Session->{count}++;	# increment count by one
        %{$Session} = ();	# clear $Session data
The $Session object state is implemented through MLDBM, and a user should be aware of the limitations of MLDBM. Basically, you can read complex structures, but not write them, directly:
      $data = $Session->{complex}{data};     # Read ok.
      $Session->{complex}{data} = $data;     # Write NOT ok.
      $Session->{complex} = {data => $data}; # Write ok, all at once.
Please see MLDBM for more information on this topic. $Session can also be used for the following methods and properties: $Session->{CodePage}
Not implemented. May never be until someone needs it. $Session->{LCID}
Not implemented. May never be until someone needs it. $Session->{SessionID}
SessionID property, returns the id for the current session, which is exchanged between the client and the server as a cookie. $Session->{Timeout} [= $minutes]
Timeout property, if minutes is being assigned, sets this default timeout for the user session, else returns the current session timeout.
If a user session is inactive for the full timeout, the session is destroyed by the system. No one can access the session after it times out, and the system garbage collects it eventually. $Session->Abandon()
The abandon method times out the session immediately. All Session data is cleared in the process, just as when any session times out. $Session->Lock()
API extension. If you are about to use $Session for many consecutive reads or writes, you can improve performance by explicitly locking $Session, and then unlocking, like:
      $Session->Lock();
      $Session->{count}++;
      $Session->{count}++;
      $Session->{count}++;
      $Session->UnLock();
This sequence causes $Session to be locked and unlocked only 1 time, instead of the 6 times that it would be locked otherwise, 2 for each increment with one to read and one to write.
Because of flushing issues with SDBM_File and DB_File databases, each lock actually ties fresh to the database, so the performance savings here can be considerable.
Note that if you have SessionSerialize set, $Session is already locked for each script invocation automatically, as if you had called $Session->Lock() in Script_OnStart. Thus you do not need to worry about $Session locking for performance. Please read the section on SessionSerialize for more info. $Session->UnLock()
API Extension. Unlocks the $Session explicitly. If you do not call this, $Session will be unlocked automatically at the end of the script. $Response Object
This object manages the output from the ASP Application and the client web browser. It does not store state information like the $Session object but does have a wide array of methods to call. $Response->{BinaryRef}
API extension. This is a perl reference to the buffered output of the $Response object, and can be used in the Script_OnFlush global.asa event to modify the buffered output at runtime to apply global changes to scripts output without having to modify all the scripts. These changes take place before content is flushed to the client web browser.
     sub Script_OnFlush {
       my $ref = $Response->{BinaryRef};
       $$ref =~ s/\s+/ /sg; # to strip extra white space
     }
Check out the ./site/eg/global.asa for an example of its use. $Response->{Buffer}
Default 1, when TRUE sends output from script to client only at the end of processing the script. When 0, response is not buffered, and client is sent output as output is generated by the script. $Response->{CacheControl}
Default "private", when set to public allows proxy servers to cache the content. This setting controls the value set in the HTTP header Cache-Control $Response->{Charset}
This member when set appends itself to the value of the Content-Length HTTP header. If $Response->{Charset} = 'ISO-LATIN-1' is set, the corresponding header would look like:
      Content-Type: text/html; charset=ISO-LATIN-1
$Response->{Clean} = 0-9;
API extension. Set the Clean level, default 0, on a per script basis. Clean of 1-9 compresses text/html output. Please see the Clean config option for more information. $Response->{ContentType} = "text/html"
Sets the MIME type for the current response being sent to the client. Sent as an HTTP header. $Response->{Expires} = $time
Sends a response header to the client indicating the $time in SECONDS in which the document should expire. A time of 0 means immediate expiration. The header generated is a standard HTTP date like: "Wed, 09 Feb 1994 22:23:32 GMT". $Response->{ExpiresAbsolute} = $date
Sends a response header to the client with $date being an absolute time to expire. Formats accepted are all those accepted by HTTP::Date::str2time(), e.g.
     "Wed, 09 Feb 1994 22:23:32 GMT"     -- HTTP format
     "Tuesday, 08-Feb-94 14:15:29 GMT"   -- old rfc850 HTTP format

     "08-Feb-94"       -- old rfc850 HTTP format
     "09 Feb 1994"     -- proposed new HTTP format

     "Feb  3  1994"    -- Unix 'ls -l' format
     "Feb  3 17:03"    -- Unix 'ls -l' format
$Response->{IsClientConnected}
Not implemented, but returns 1 currently for portability. This is value is not yet relevant, and may not be until apache 1.3.6, which will be tested shortly. Apache versions less than 1.3.6 abort the perl code immediately upon the client dropping the connection. $Response->{PICS}
If this property has been set, a PICS-Label HTTP header will be sent with its value. For those that do not know, PICS is a header that is useful in rating the internet. It stands for Platform for Internet Content Selection, and you can find more info about it at: http://www.w3.org $Response->{Status} = $status
Sets the status code returned by the server. Can be used to set messages like 500, internal server error $Response->AddHeader($name, $value)
Adds a custom header to a web page. Headers are sent only before any text from the main page is sent, so if you want to set a header after some text on a page, you must turn BufferingOn. $Response->AppendToLog($message)
Adds $message to the server log. Useful for debugging. $Response->BinaryWrite($data)
Writes binary data to the client. The only difference from $Response->Write() is that $Response->Flush() is called internally first, so the data cannot be parsed as an html header. Flushing flushes the header if has not already been written.
If you have set the $Response->{ContentType} to something other than text/html, cgi header parsing (see CGI notes), will be automatically be turned off, so you will not necessarily need to use BinaryWrite for writing binary data.
For an example of BinaryWrite, see the binary_write.htm example in ./site/eg/binary_write.htm
Please note that if you are on Win32, you will need to call binmode on a file handle before reading, if its data is binary. $Response->Clear()
Erases buffered ASP output. $Response->Cookies($name, [$key,] $value)
Sets the key or attribute of cookie with name $name to the value $value. If $key is not defined, the Value of the cookie is set. ASP CookiePath is assumed to be / in these examples.
     $Response->Cookies('name', 'value');
      --> Set-Cookie: name=value; path=/

     $Response->Cookies("Test", "data1", "test value");
     $Response->Cookies("Test", "data2", "more test");
     $Response->Cookies(
    	"Test", "Expires",
    	&HTTP::Date::time2str(time+86400)
    	);
     $Response->Cookies("Test", "Secure", 1);
     $Response->Cookies("Test", "Path", "/");
     $Response->Cookies("Test", "Domain", "host.com");
      -->	Set-Cookie:Test=data1=test%20value&data2=more%20test;	\
     		expires=Fri, 23 Apr 1999 07:19:52 GMT;		\
     		path=/; domain=host.com; secure
The latter use of $key in the cookies not only sets cookie attributes such as Expires, but also treats the cookie as a hash of key value pairs which can later be accesses by
     $Request->Cookies('Test', 'data1');
     $Request->Cookies('Test', 'data2');
Because this is perl, you can (NOT PORTABLE) reference the cookies directly through hash notation. The same 5 commands above could be compressed to:
     $Response->{Cookies}{Test} =
    	{
    		Secure	=> 1,
    		Value	=>
    			{
    				data1 => 'test value',
    				data2 => 'more test'
    			},
    		Expires	=> 86400, # not portable, see above
    		Domain	=> 'host.com',
    		Path    => '/'
    	};
and the first command would be:
     # you don't need to use hash notation when you are only setting
     # a simple value
     $Response->{Cookies}{'Test Name'} = 'Test Value';
I prefer the hash notation for cookies, as this looks nice, and is quite perlish. It is here to stay. The Cookie() routine is very complex and does its best to allow access to the underlying hash structure of the data. This is the best emulation I could write trying to match the Collections functionality of cookies in IIS ASP.
For more information on Cookies, please go to the source at http://home.netscape.com/newsref/std/cookie_spec.html $Response->Debug(@args)
API Extension. If the Debug config option is set greater than 0, this routine will write @args out to server error log. refs in @args will be expanded one level deep, so data in simple data structures like one-level hash refs and array refs will be displayed. CODE refs like
     $Response->Debug(sub { "some value" });
will be executed and their output added to the debug output. This extension allows the user to tie directly into the debugging capabilities of this module.
While developing an app on a production server, it is often useful to have a separate error log for the application to catch debugging output separately. One way of implementing this is to use the Apache ErrorLog configuration directive to create a separate error log for a virtual host.
If you want further debugging support, like stack traces in your code, consider doing things like:
     $Response->Debug( sub { Carp::longmess('debug trace') };
     $SIG{__WARN__} = \&Carp::cluck; # then warn() will stack trace
The only way at present to see exactly where in your script an error occurred is to set the Debug config directive to 2, and match the error line number to perl script generated from your ASP script.
However, as of version 0.10, the perl script generated from the asp script should match almost exactly line by line, except in cases of inlined includes, which add to the text of the original script, pod comments which are entirely yanked out, and <% # comment %> style comments which have a \n added to them so they still work.
If you would like to see the HTML preceding an error while developing, consider setting the BufferingOn config directive to 0. $Response->End()
Sends result to client, and immediately exits script. Automatically called at end of script, if not already called. $Response->ErrorDocument($code, $uri)
API extension that allows for the modification the Apache ErrorDocument at runtime. $uri may be a on site document, off site URL, or string containing the error message.
This extension is useful if you want to have scripts set error codes with $Response->{Status} like 401 for authentication failure, and to then control from the script what the error message looks like.
For more information on the Apache ErrorDocument mechanism, please see ErrorDocument in the CORE Apache settings, and the Apache->custom_response() API, for which this method is a wrapper. $Response->Flush()
Sends buffered output to client and clears buffer. $Response->Include($filename, @args)
This API extension calls the routine compiled from asp script in $filename with the args @args. This is a direct translation of the SSI tag
      <!--#include file=$filename args=@args-->
Please see the SSI section for more on SSI in general.
This API extension was created to allow greater modularization of code by allowing includes to be called with runtime arguments. Files included are compiled once, and the anonymous code ref from that compilation is cached, thus including a file in this manner is just like calling a perl subroutine. $Response->Redirect($url)
Sends the client a command to go to a different url $url. Script immediately ends. $Response->Write($data)
Write output to the HTML page. <%=$data%> syntax is shorthand for a $Response->Write($data). All final output to the client must at some point go through this method. $Request Object
The request object manages the input from the client browser, like posts, query strings, cookies, etc. Normal return results are values if an index is specified, or a collection / perl hash ref if no index is specified. WARNING, the latter property is not supported in ActiveState PerlScript, so if you use the hashes returned by such a technique, it will not be portable.
A normal use of this feature would be to iterate through the form variables in the form hash...
     $form = $Request->Form();
     for(keys %{$form}) {
    	$Response->Write("$_: $form->{$_}<br>\n");
     }
Please see the ./site/eg/server_variables.htm asp file for this method in action.
Note that if a form POST or query string contains duplicate values for a key, those values will be returned through normal use of the $Request object:
      @values = $Request->Form('key');
but you can also access the internal storage, which is an array reference like so:
      $array_ref = $Request->{Form}{'key'};
      @values = @{$array_ref};
Please read the PERLSCRIPT section for more information on how things like $Request->QueryString() & $Request->Form() behave as collections. $Request->{TotalBytes}
The amount of data sent by the client in the body of the request, usually the length of the form data. This is the same value as $Request->ServerVariables('CONTENT_LENGTH') $Request->BinaryRead($length)
Returns a scalar whose contents are the first $length bytes of the form data, or body, sent by the client request. This data is the raw data sent by the client, without any parsing done on it by Apache::ASP. $Request->ClientCertificate()
Not implemented. $Request->Cookies($name [,$key])
Returns the value of the Cookie with name $name. If a $key is specified, then a lookup will be done on the cookie as if it were a query string. So, a cookie set by:
     Set-Cookie: test=data1=1&data2=2
would have a value of 2 returned by $Request->Cookies('test','data2').
If no name is specified, a hash will be returned of cookie names as keys and cookie values as values. If the cookie value is a query string, it will automatically be parsed, and the value will be a hash reference to these values.
When in doubt, try it out. Remember that unless you set the Expires attribute of a cookie with $Response->Cookies('cookie', 'Expires', $xyz), the cookies that you set will only last until you close your browser, so you may find your self opening & closing your browser a lot when debugging cookies.
For more information on cookies in ASP, please read $Response->Cookies() $Request->FileUpload($form_field, $key)
API extension. The FileUpload interface to file upload data is stabilized. The internal representation of the file uploads is a hash of hashes, one hash per file upload found in the $Request->Form() collection. This collection of collections may be queried through the normal interface like so:
      $Request->FileUpload('upload_file', 'ContentType');
      $Request->FileUpload('upload_file', 'FileHandle');
      $Request->FileUpload('upload_file', 'BrowserFile');
      $Request->FileUpload('upload_file', 'Mime-Header');
      $Request->FileUpload('upload_file', 'TempFile');

      * note that TempFile must be use with the UploadTempFile
        configuration setting.
The above represents the old slow collection interface, but like all collections in Apache::ASP, you can reference the internal hash representation more easily.
      my $fileup = $Request->{FileUpload}{upload_file};
      $fileup->{ContentType};
      $fileup->{BrowserFile};
      $fileup->{FileHandle};
      $fileup->{Mime-Header};
      $fileup->{TempFile};
$Request->Form($name)
Returns the value of the input of name $name used in a form with POST method. If $name is not specified, returns a ref to a hash of all the form data.
File upload data will be loaded into $Request->Form('file_field'), where the value is the actual file name of the file uploaded, and the contents of the file can be found by reading from the file name as a file handle as in:
     while(read($Request->Form('file_field_name'), $data, 1024)) {};
For more information, please see the CGI / File Upload section, as file uploads are implemented via the CGI.pm module. An example can be found in the installation samples ./site/eg/file_upload.asp $Request->QueryString($name)
Returns the value of the input of name $name used in a form with GET method, or passed by appending a query string to the end of a url as in `http://localhost/?data=value.` If $name is not specified, returns a ref to a hash of all the query string data. $Request->ServerVariables($name)
Returns the value of the server variable / environment variable with name $name. If $name is not specified, returns a ref to a hash of all the server / environment variables data. The following would be a common use of this method:
     $env = $Request->ServerVariables();
     # %{$env} here would be equivalent to the cgi %ENV in perl.
$Application Object
Like the $Session object, you may use the $Application object to store data across the entire life of the application. Every page in the ASP application always has access to this object. So if you wanted to keep track of how many visitors there where to the application during its lifetime, you might have a line like this:
     $Application->{num_users}++
The Lock and Unlock methods are used to prevent simultaneous access to the $Application object. $Application->Lock()
Locks the Application object for the life of the script, or until UnLock() unlocks it, whichever comes first. When $Application is locked, this guarantees that data being read and written to it will not suddenly change on you between the reads and the writes.
This and the $Session object both lock automatically upon every read and every write to ensure data integrity. This lock is useful for concurrent access control purposes.
Be careful to not be too liberal with this, as you can quickly create application bottlenecks with its improper use. $Application->UnLock()
Unlocks the $Application object. If already unlocked, does nothing. $Application->GetSession($sess_id)
This NON-PORTABLE API extension returns a user $Session given a session id. This allows one to easily write a session manager if session ids are stored in $Application during Session_OnStart, with full access to these sessions for administrative purposes.
Be careful not to expose full session ids over the net, as they could be used by a hacker to impersonate another user. So when creating a session manager, for example, you could create some other id to reference the SessionID internally, which would allow you to control the sessions. This kind of application would best be served under a secure web server.
The ./site/eg/global_asa_demo.asp script makes use of this routine to display all the data in current user sessions. $Application->SessionCount()
This NON-PORTABLE method returns the current number of active sessions, in the application. This method is not implemented as part of the ASP object model, but is implemented here because it is useful. In particular, when accessing databases with license requirements, one can monitor usage effectively through accessing this value.
This is a new feature as of v.06, and if run on a site with previous versions of Apache::ASP, the count may take a while to synch up. To ensure a correct count, you must delete all the current state files associated with an application, usually in the $Global/.state directory. $Server Object
The server object is that object that handles everything the other objects do not. The best part of the server object for Win32 users is the CreateObject method which allows developers to create instances of ActiveX components, like the ADO component. $Server->{ScriptTimeout} = $seconds
Not implemented. May never be. Please see the Apache Timeout configuration option, normally in httpd.conf. $Server->Config($setting)
API extension. Allows a developer to read the CONFIG settings, like Global, GlobalPackage, StateDir, etc. Currently implemented as a wrapper around
      Apache->dir_config($setting)
$Server->CreateObject($program_id)
Allows use of ActiveX objects on Win32. This routine returns a reference to an Win32::OLE object upon success, and nothing upon failure. It is through this mechanism that a developer can utilize ADO. The equivalent syntax in VBScript is
     Set object = Server.CreateObject(program_id)
For further information, try 'perldoc Win32::OLE' from your favorite command line. $Server->Execute($file, @args)
New method from ASP 3.0, this does the same thing as
      $Response->Include($file, @args)
and internally is just a wrapper for such. Seems like we had this important functionality before the IIS/ASP camp! $Server->GetLastError()
Not implemented, will likely not ever be because this is dependent on how IIS handles errors and is not relevant in Apache. $Server->HTMLEncode($string)
Returns an HTML escapes version of $string. &, ", >, <, are each escapes with their HTML equivalents. Strings encoded in this nature should be raw text displayed to an end user, as HTML tags become escaped with this method. " $Server->MapPath($url);
Given the url $url, absolute, or relative to the current executing script, this method returns the equivalent filename that the server would translate the request to, regardless or whether the request would be valid.
Only a $url that is relative to the host is valid. Urls like "." and "/" are fine arguments to MapPath, but `http://localhost` would not be.
To see this method call in action, check out the sample ./site/eg/server.htm script. $Server->Mail(\%mail, %smtp_args);
With the Net::SMTP and Net::Config modules installed, which are part of the perl libnet package, you may use this API extension to send email. The \%mail hash reference that you pass in must have values for at least the To, From, and Subject headers, and the Body of the mail message.
You could send an email like so:
     $Server->Mail({
    		To => 'somebody@yourdomain.com.foobar',
    		From => 'youremail@yourdomain.com.foobar',
    		Subject => 'Subject of Email',
    		Body =>
    		 'Body of message. '.
    		 'You might have a lot to say here!',
    		Organization => 'Your Organization',
    	       });
Any extra fields specified for the email will be interpreted as headers for the email, so to send an HTML email, you could set 'Content-Type' => 'text/html' in the above example.
If you have MailFrom configured, this will be the default for the From header in your email. For more configuration options like the MailHost setting, check out the CONFIG section.
The return value of this method call will be boolean for success of the mail being sent.
If you would like to specially configure the Net::SMTP object used internally, you may set %smtp_args and they will be passed on when that object is initialized. "perldoc Net::SMTP" for more into on this topic. $Server->Transfer($file)
New method from ASP 3.0. Transfers control to another script. The Response buffer will not be cleared automatically, so if you want this to serve as a faster $Response->Redirect(), you will need to call $Response->Clear() before calling this method.
This new script will take over current execution and the current script will not continue to be executed afterwards. It differs from Execute() because the original script will not pick up where it left off. $Server->URLEncode($string)
Returns the URL-escaped version of the string $string. +'s are substituted in for spaces and special characters are escaped to the ascii equivalents. Strings encoded in this manner are safe to put in urls... they are especially useful for encoding data used in a query string as in:
     $data = $Server->URLEncode("test data");
     $url = "http://localhost?data=$data";

     $url evaluates to http://localhost?data=test+data, and is a
     valid URL for use in anchor <a> tags and redirects, etc.
$Server->RegisterCleanup($sub)
     non-portable extension
Sets a subroutine reference to be executed after the script ends, whether normally or abnormally, the latter occurring possibly by the user hitting the STOP button, or the web server being killed. This subroutine must be a code reference created like:
     $Server->RegisterCleanup(sub { $main::Session->{served}++; });
       or
     sub served { $main::Session->{served}++; }
     $Server->RegisterCleanup(\&served);
The reference to the subroutine passed in will be executed. Though the subroutine will be executed in anonymous context, instead of the script, all objects will still be defined in main::*, that you would reference normally in your script. Output written to $main::Response will have no affect at this stage, as the request to the www client has already completed.
Check out the ./site/eg/register_cleanup.asp script for an example of this routine in action. $Server->URL($url, \%params)
Will return a URL with %params serialized into a query string like:
      $url = $Server->URL('test.asp', { test => value });
which would give you a URL of test.asp?test=value
Used in conjunction with the SessionQuery* settings, the returned URL will also have the session id inserted into the query string, making this a critical part of that method of implementing cookieless sessions. For more information on that topic please read on the setting in the CONFIG section, and the SESSIONS section too.
Copyright © 1998-2000, Joshua Chamas, Chamas Enterprises Inc.