Apache :: ASP

INTRO
INSTALL
CONFIG
SYNTAX
EVENTS
OBJECTS
SSI
CGI
PERLSCRIPT
FAQ
TUNING
CREDITS
SUPPORT
SITES USING

EXAMPLES

Powered by ModPerl & Apache
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 accesible from anywhere in your ASP application.

  Currently the Apache::ASP object model supports the following:

    Object	 -	Function
    ------		--------
    $Session	 -	session state
    $Response	 -	output
    $Request	 -	input
    $Application -	application state
    $Server	 -	OLE support + misc
These objects, and their methods are further defined in the following sections.

$Session Object

$Session->{CodePage}
$Session->{LCID}
$Session->{SessionID}
$Session->{Timeout} [= $minutes]
$Session->Abandon()

$Response Object

$Response->{Buffer}
$Response->{CacheControl}
$Response->{Charset}
$Response->{Clean} = 0-9;
$Response->{ContentType} = "text/html"
$Response->{Expires} = $time
$Response->{ExpiresAbsolute} = $date
$Response->{IsClientConnected}
$Response->{PICS}
$Response->{Status} = $status
$Response->AddHeader($name, $value)
$Response->AppendToLog($message)
$Response->BinaryWrite($data)
$Response->Clear()
$Response->Cookies($name, [$key,] $value)
$Response->Debug(@args)
$Response->End()
$Response->Flush()
$Response->Include($filename, @args)
$Response->Redirect($url)
$Response->Write($data)

$Request Object

$Request->{TotalBytes}
$Request->BinaryRead($length)
$Request->ClientCertificate()
$Request->Cookies($name [,$key])
$Request->Form($name)
$Request->QueryString($name)
$Request->ServerVariables($name)

$Application Object

$Application->Lock()
$Application->UnLock()
$Application->SessionCount()

$Server Object

$Server->{ScriptTimeout} = $seconds
$Server->CreateObject($program_id)
$Server->HTMLEncode($string)
$Server->MapPath($url);
$Server->URLEncode($string)
$Server->RegisterCleanup($sub_reference)

$Session Object

The $Session object keeps track of user + web client state, in a persistent manner, making it relatively easy to develop web applications. The $Session state is stored accross HTTP connections, in database files in the Global directory, and will persist across 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 refererence 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 explains what its supposed to do.

$Session->{LCID}

Not implemented. May never be until someone explains what its supposed to do.

$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.

$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->{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    (no weekday, no time)
 "09 Feb 1994"       -- proposed new HTTP format  (no weekday, no time)

 "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 $Reponse->{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 gif.htm example 
in ./site/eg/gif.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 shortcut, 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 debuging 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 occured 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 preceeding 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->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 coderef 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 brower, 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 Activeware 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.

$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->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 gaurantees 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->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->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->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->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 url's... 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_reference)

 non-portable extension
Sets a subroutine reference to be executed after the script ends, whether normally or abnormally, the latter occuring 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.
Copyright (c) 1998-1999, Joshua Chamas, Chamas Enterprises Inc.