Apache :: ASP
< % Web Applications with Apache & mod_perl % >
はじめに
インストール
設定
構文
イベント
% オブジェクト
SSI
セッション
XML/XSLT
CGI
PERLスクリプト
FAQ
チューニング
謝辞
サポート
使用サイト
リソース
計画
履歴
ライセンス

実例

ASP 工作室
日本語訳について

Powered by Apache::ASP
Powered by ModPerl and Apache
Powered by Perl
Links Checked by NodeWorks
SourceForge.jp
オブジェクト


ASP オブジェクトモデルの美点は、
CGIとセッション管理の重荷を開発者から取り除き、
どんな、ASP script & include からもアクセス可能なように、
オブジェクトとして組み入れ可能になることです。
Perl プログラマは、これらのオブジェクトと汎用変数を、
ASP アプリケーションでは、どこからでもアクセスできるように扱ってください。
 Apache::ASP オブジェクトモデル は、以下をサポートします:

 オブジェクト    機能
 ------         --------
 $Session      - ユーザセッションの状態
 $Response     - ブラウザへの出力
 $Request      - ブラウザからの入力
 $Application  - アプリケーションの状態
 $Server       - 汎用メソッド
これらのオブジェクトとそのメソッドは、続きのセッションで詳細に定義づけられています。
あなたのスクリプトとインクルードで使う 独自の汎用オブジェクトを定義づけたいなら、 global.asa での Script_OnStart で以下のように初期化することができます。
 use vars qw( $Form $Site ); # 汎用変数宣言
 sub Script_OnStart {
     $Site = My::Site->new;  # $Site オブジェクトの初期化
     $Form = $Request->Form; # フォームデータ別名
     $Server->RegisterCleanup(sub { # ガベージコレクション
				  $Site->DESTROY; 
				  $Site = $Form = undef; 
			      });
 }
このようにして、共用できる機能を持った、 サイトでの幅広いアプリケーションオブジェクトと エイリアス(別名)を簡単に作ることができます。

$Session Object $Response->Write($data)
$Session->{CodePage}
$Session->{LCID} $Request Object
$Session->{SessionID} $Request->{Method}
$Session->{Timeout} [= $minutes] $Request->{TotalBytes}
$Session->Abandon() $Request->BinaryRead($length)
$Session->Lock() $Request->ClientCertificate()
$Session->UnLock() $Request->Cookies($name [,$key])
$Request->FileUpload($form_field, $key)
$Response Object $Request->Form($name)
$Response->{BinaryRef} $Request->Params($name)
$Response->{Buffer} $Request->QueryString($name)
$Response->{CacheControl} $Request->ServerVariables($name)
$Response->{Charset}
$Response->{Clean} = 0-9; $Application Object
$Response->{ContentType} = "text/html" $Application->Lock()
$Response->{Debug} = 1|0 $Application->UnLock()
$Response->{Expires} = $time $Application->GetSession($sess_id)
$Response->{ExpiresAbsolute} = $date $Application->SessionCount()
$Response->{FormFill} = 0|1
$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 || \$string )
$Response->Cookies($name, [$key,] $value) $Server->MapInclude($include)
$Response->Debug(@args) $Server->MapPath($url);
$Response->End() $Server->Mail(\%mail, %smtp_args);
$Response->ErrorDocument($code, $uri) $Server->RegisterCleanup($sub)
$Response->Flush() $Server->Transfer($file, @args)
$Response->Include($filename, @args) $Server->URLEncode($string)
$Response->Include(\%cache_args, @sub_args) *CACHE API* $Server->URL($url, \%params)
$Response->IsClientConnected() $Server->XSLT($xsl_data_ref, $xml_data_ref)
$Response->Redirect($url)  
$Response->TrapInclude($file, @args)  

$Session Object


$Session オブジェクトは、ユーザーと Web クライアントの状態の軌跡を
継続して、保つので、比較的容易に、Web アプリケーションを開発できます。
$Session の状態は、(1 回 1 回の) HTTP 接続をまたがって、
Global か StateDir ディレクトリにあるデータベースに蓄えられ、
サーバが再稼動しても継続されます。

ユーザセッションは、128 ビット / 32 バイトの MD5 として、 16進(の文字)でのハッシュされたクッキーで、参照され、 セッション id が推測されたり、セッションのハイジャックからも 安全であると考えられます。 ハッカーがセッションを推測するまでには、システムは、 タイムアウトになりますし、2**128 (3.4e38) の数のキーを推測に使うとすると ハッカーは、id をすぐには推測できません。
やってくるクッキーが、タイムアウトになったか、 存在しないセッションにマッチすると、新しいセッションが作り出されます。 id が、現在アクティブなセッションにマッチすると、 セッションは結び合わされ、戻り値を返します。 このことは、Microsoft ASP の実装に似ています。
$Session への参照は、hash ref(ハッシュへの参照)で、 データを以下のように蓄えることが出来ます。
    $Session->{count}++;	# カウントを1つづつ増加
    %{$Session} = ();	# $Session データをクリア
$Session オブジェクトの状態は、MLDBM を介して実現され、 ユーザは、MLDBM の限界について注意を払ってください。 基本的には、複雑な構造を読むことはできますが、直接書く事が出来ません。
  $data = $Session->{complex}{data};     # 読み込み 可
  $Session->{complex}{data} = $data;     # 書き込み 不可
  $Session->{complex} = {data => $data}; # 一度で書き込み可
この話題での詳細情報は、MLDBM を見てください。 $Session は、以下のメソッドとプロパティのように使用することが出来ます。

$Session->{CodePage}


実装されていません。たぶん、誰かが必要とするまでそうでしょう。

	

$Session->{LCID}


実装されていません。たぶん、誰かが必要とするまでそうでしょう。

	
	

$Session->{SessionID}


SessionID プロパティ、クライアントとサーバ間でクッキーとして交換される
現在のセッションの id を返します。
	

$Session->{Timeout} [= $minutes]


タイムアウトプロパティ、分が割り当てられると、
ユーザセッションの既定のタイムアウト時間として設定され、
そうでなければ、現在のセッションのタイムアウト時間を返します。
もし、ユーザセッションがタイムアウト時間いっぱいでアクティブでなければ、 システムによりセッションが破棄されます。 タイムアウト後は、誰もアクセスできませんし、 システムは、最終的には(そのセッションを)ガベージコレクションします。

$Session->Abandon()


Abondon(中断)メソッドは、ただちにセッションをタイムアウトさせます。
このプロセスでは、どのセッションもがタイムアウトする時のように、
すべてのセッションデータはクリアされます。


	
	

$Session->Lock()


API の拡張です。以下のように、数多い連続的な読み書きで、
$Session を使おうとすると、
明示的に、$Sesion をロックし、ロック解除すると
パフォーマンスを改善することが可能です。
  $Session->Lock();
  $Session->{count}++;
  $Session->{count}++;
  $Session->{count}++;
  $Session->UnLock();  
一方が読み込みもう一方が書き込みして、2つづつ増加されると 6回のロックとロック解除に対して この一連の動作では、$Session は、1 回だけです。
実際に各々のロックは、SDBM_File と DB_File に、結果をバッファし、 (その)データベースに、常に新たに結び付けられていますので、 ここではセーブの際のパフォーマンスは、少なからぬんものがあります。
SessionSerialize をセットしているなら、 Script_OnStart で $Session->Lock() を呼び出すように、 $Session は、自動的な各々のスクリプトの呼び出しに対して すでに、ロックされていることに注目。 かくして、パフォーマンス故に、$Session のロックに思い煩うことはありません。 詳細情報は、SessionSerialize の項を見てください。

$Session->UnLock()


API の拡張です。明示的に、$Session をロック解除します。
このオブジェクトを呼び出さなければ、$Session は、スクリプトの最後で
自動的にロック解除されます。

	
	

$Response Object


このオブジェクトは、
ASP アプリケーションとクライアントの Web ブラウザからの出力を管理します。
$Session オブジェクトのように、状態の情報は記憶しませんが、
コールされるメソッドは、豊富にあります。


	
	

$Response->{BinaryRef}


API 拡張です。
これは、$Response オブジェクトのバッファーされた出力を、
Perl 様式で参照します。
global.asa の Script_OnFlush で使用すると、すべてのスクリプトを変えないで、
スクリプトに汎用な変更を適用するため、実行中に、
バッファーされた出力を修正できます。
この変更は、内容がクライアントの Web ブラウザにフラッシュされる前に
発生します。
 sub Script_OnFlush {
   my $ref = $Response->{BinaryRef};
   $$ref =~ s/\s+/ /sg; # 余分な空白を削除
 }
使用実例は、./site/eg/global.asa をチェックしてください。

$Response->{Buffer}


デフォールトは 1 です。真の場合、スクリプトの処理手続きの最後にのみ、
スクリプトからクライアントへ出力します。
0 の時は、レスポンス(応答)はバッファされないで、
クライアントへはスクリプトが作成した出力としてそのまま送られてきます。
	

$Response->{CacheControl}


デフォールトは、"private" です。public にセットされると、
プロキシ(代理)サーバが内容をキャッシュできるようになります。
この設定は、HTTP のヘッダのCache-Control にセットされる変数を
コントロールします。
	

$Response->{Charset}


このメンバー(変数)がセットされると、
HTTP ヘッダでの Content-Type の値に追加されます。
 $Response->{Charset} = 'ISO-LATIN-1' と設定されると、
対応するヘッダは以下のようになります。
  Content-Type: text/html; charset=ISO-LATIN-1

$Response->{Clean} = 0-9;


API 拡張です。クリーンレベルをセットし、デフォールトは 0 で、
スクリプトが、その通リに出力されます。
1-9 (段階)でのクリーンレベルでは、text/html 出力を圧縮します。
詳しくは、
(設定ページでの)クリーン設定の項を
ご覧ください。
この設定は、不明瞭な HTML の圧縮に有用かもしれません。

	
	

$Response->{ContentType} = "text/html"


クライアントへ送信される現在のレスポンスに対する MIME タイプをセットします。HTTP ヘッダとして送られます。

	
	

$Response->{Debug} = 1|0


API 拡張です。デフォールトは、Debug 設定の値です。
以下のように、一時的に、
$Response->Debug()の作用を
有効化ないし無効化したい時に使用される事が多いでしょう。
 {
   local $Response->{Debug} = 1;
   $Response->Debug($values);
 }
(の構文は)常に何かをログに記録します。 Debug() メソッドは、ログのデータを、 データ構造で一レベル下に記録しますので、 AppendToLog() より良いでしょう。 AppendToLog は、そのまま、文字列 / スカラーの値で出力します。

$Response->{Expires} = $time


クライアントに、レスポンスヘッダでドキュメントの有効期限を、$time (の値)を秒単位で送信します。time が、0 ならただちに、失効します。
ヘッダは、"Wed, 09 Feb 1994 22:23:32 GMT" のような、
HTTP 標準形式で生成されます。

	
	

$Response->{ExpiresAbsolute} = $date


クライアントに、レスポンスヘッダで、有効期限を、$date (の値)で、
絶対的な時間形式で送信します。
受け入れる時間形式は、以下のように、
HTTP::Date::str2time() が受け入れるすべての形式です。
 "Wed, 09 Feb 1994 22:23:32 GMT"     -- HTTP 形式
 "Tuesday, 08-Feb-94 14:15:29 GMT"   -- 旧の rfc850 HTTP 形式

 "08-Feb-94"       -- 旧の rfc850 HTTP 形式
 "09 Feb 1994"     -- 提案された新しい HTTP 形式

 "Feb  3  1994"    -- Unix 'ls -l' 形式
 "Feb  3 17:03"    -- Unix 'ls -l' 形式

$Response->{FormFill} = 0|1


真なら、スクリプト出力で生成された HTML フォームは、
$Request->Form からのデータが自動的に埋め込まれます。
この特質は、HTML::FillInForm がインストールされている事が要件です。
詳細は、FormFill CONFIG を見てください。
このセッティングは、単にスクリプトを実行時の FormFill 設定に上書きされます。

$Response->{IsClientConnected}

1 if web client is connected, 0 if not.  This value
starts set to 1, and will be updated whenever a
$Response->Flush() is called.  If BufferingOn is
set, by default $Response->Flush() will only be
called at the end of the HTML output.  
As of version 2.23 this value is updated correctly before global.asa Script_OnStart is called, so global script termination may be correctly handled during that event, which one might want to do with excessive user STOP/RELOADS when the web server is very busy.
An API extension $Response->IsClientConnected may be called for refreshed connection status without calling first a $Response->Flush

$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. The @args can be found in @_ in the includes like:
  # include.inc
  <% my @args = @_; %>
As of 2.23, multiple return values can be returned from an include like:
 my @rv = $Response->Include($filename, @args);

$Response->Include(\%cache_args, @sub_args) *CACHE API*

As of version 2.23, output from an include may be
cached with this API and the CONFIG settings CacheDir & CacheDB.  This
can be used to execute expensive includes only rarely
where applicable, drastically increasing performance in 
some cases.
This API extension applies to the entire include family:
  my @rv = $Response->Include(\%cache_args, @include_args)
  my $html_ref = $Response->TrapInclude(\%cache_args, @include_args)
  $Server->Execute(\%cache_args, @include_args)
For this output cache to work, you must load Apache::ASP in the Apache parent httpd like so:
  # httpd.conf
  PerlModule Apache::ASP
The cache arguments are shown here
  $Response->Include({
    File => 'file.inc',
    Cache => 1, # to activate cache layer
    Expires => 3600, # to expire in one hour
    LastModified => time() - 600, # to expire if cached before 10 minutes ago
    Key => $Request->Form, # to cache based on checksum of serialized form data,
    Clear => 1, # always executes include & cache output
  }, @include_args);

  File - include file to execute, can be file name or \$script 
    script data passed in as scalar ref.

  Cache - activate caching, will run like normal include without this

  Expires - only cache for this long in seconds

  LastModified - if cached before this time(), expire

  Key - The cache item identity.  Can be $data, \$data, \%data, \@data, 
    this data is serialized and combined with the filename & @include_args 
    to create a MD5 checksum to fetch from the cache with. If you wanted
    to cache the results of a search page from form data POSTed, 
    then this key could be 

      { Key => $Request->Form }

  Clear - If set to 1, or boolean true, will always execute the include 
    and update the cache entry for it.
Motivation: If an include takes 1 second to execute because of complex SQL to a database, and you can cache the output of this include because it is not realtime data, and the cache layer runs at .01 seconds, then you have a 100 fold savings on that part of the script. Site scalability can be dramatically increased in this way by intelligently caching bottlenecks in the web application.
Use Sparingly: If you have a fast include, then it may execute faster than the cache layer runs, in which case you may actually slow your site down by using this feature. Therefore try to use this sparingly, and only when sure you really need it. Apache::ASP scripts generally execute very quickly, so most developers will not need to use this feature at all.

$Response->IsClientConnected()

API Extension.  1 for web client still connected, 0 if 
disconneted which might happen if the user hits the stop button.
The original API for this $Response->{IsClientConnected}
is only updated after a $Response->Flush is called,
so this method may be called for a refreshed status.
Note $Response->Flush calls $Response->IsClientConnected to update $Response->{IsClientConnected} so to use this you are going straight to the source! But if you are doing a loop like:
  while(@data) {
    $Response->End if ! $Response->{IsClientConnected};
    my $row = shift @data;
    %> <%= $row %> <%
    $Response->Flush;
  }
Then its more efficient to use the member instead of the method since $Response->Flush() has already updated that value for you.

$Response->Redirect($url)

Sends the client a command to go to a different url $url.  
Script immediately ends.
	
	

$Response->TrapInclude($file, @args)

Calls $Response->Include() with same arguments as
passed to it, but instead traps the include output buffer
and returns it as as a perl scalar ref.  This allows
one to postprocess the output buffer before sending
to the client.
  my $string_ref = $Response->TrapInclude('file.inc');
  $$string_ref =~ s/\s+/ /sg; # squash whitespace like Clean 1
  print $$string_ref;
The scalar is returned as a referenece to save on what might be a large string copy. You may dereference the scalar with the $$string_ref notation.

$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->{Method}

API extension.  Returns the client HTTP request method, as in
GET or POST.  Added in version 2.31.
	
	

$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.  One can use this hash to 
create a nice alias to the form data like:
 # in global.asa
 use vars qw( $Form );
 sub Script_OnStart {
   $Form = $Request->Form;
 }
 # then in ASP scripts
 <%= $Form->{var} %>
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->Params($name)

API extension. If RequestParams CONFIG is set, the $Request->Params 
object is created with combined contents of $Request->QueryString 
and $Request->Form.  This is for developer convenience simlar 
to CGI.pm's param() method.  Just like for $Response->Form, 
one could create a nice alias like:
 # in global.asa
 use vars qw( $Params );
 sub Script_OnStart {
   $Params = $Request->Params;
 }

$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)
May also be invoked as $Server->Config(), which will return a hash ref of all the PerlSetVar settings.

$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 || \$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.
As of version 2.23, $Server->HTMLEncode() may take a scalar reference for an optmization when encoding a large buffer as an API extension. Here is how one might use one over the other:
  my $buffer = '&' x 100000;
  $buffer = $Server->HTMLEncode($buffer);
  print $buffer;
    - or -
  my $buffer = '&' x 100000;
  $Server->HTMLEncode(\$buffer);
  print $buffer;
Using the reference passing method in benchmarks on 100K of data was 5% more efficient, but maybe useful for some. It saves on copying the 100K buffer twice.

$Server->MapInclude($include)

API extension.  Given the include $include, as an absolute or relative file name to the current
executing script, this method returns the file path that the include would
be found from the include search path.  The include search path is the 
current script directory, Global, and IncludesDir directories.
If the include is not found in the includes search path, then undef, or bool false, is returned. So one may do something like this:
  if($Server->MapInclude('include.inc')) {
    $Response->Include('include.inc');
  }
This code demonstrates how one might only try to execute an include if it exists, which is useful since a script will error if it tries to execute an include that does not exist.

$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',
		Debug => 0 || 1,
	       });
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.
If you would like to include the output of an ASP page as the body of the mail message, you might do something like:
  my $mail_body = $Response->TrapInclude('mail_body.inc');
  $Server->Mail({ %mail, Body => $$mail_body });

$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->Transfer($file, @args)

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.
As of Apache::ASP 2.31, this method now accepts optional arguments like $Response->Include & $Server->Execute. $Server->Transfer is now just a wrapper for:
  $Response->Include($file, @args);
  $Response->End;

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

$Server->XSLT($xsl_data_ref, $xml_data_ref)

 * NON-PORTABLE ASP EXTENSION *
This method takes scalar refs for XSL and XML data and returns the XSLT output as a scalar ref like:
  my $xslt_data_ref = $Server->XSLT($xsl_data_ref, $xml_data_ref)
The XSLT parser defaults to XML::XSLT, and is configured with the XSLTParser setting. Please see the CONFIG section for more information on the setting.
This API was created to allow developers easy XSLT component rendering without having to render the entire ASP scripts via XSLT. This will make an easy plugin architecture for those looking to integrate XML into their existing ASP application frameworks.
At some point, the API will likely take files as arguments, but not as of the 2.11 release.
 
Copyright © 1998-2002, Joshua Chamas, Chamas Enterprises Inc.