CGI Interface

Mary Kroening mary@amzi.com

Introduction

The Amzi! Logic Server Common Gateway Interface (CGI) interface allows you to integrate Prolog logic with web servers through CGI scripts written in Prolog. The Prolog code can read information from a Web form and dynamically generate HTML to send back to the user.

A straight-forward class of applications for the CGI-Amzi! interface is intelligent form editors. Prolog code can be used to analyze user input from forms and then, based on that analysis, generate either responses or other HTML user input elements to gather or correct missing or wrong information.

Expert systems can be implemented that dynamically generate HTML forms to query the user, and, based on user answers, either generate more questions or provide answers in HTML to the user.

Expert systems are just one form of intelligent interaction enabled by the CGI-Amzi! interface. Others include intelligent tutorials, natural language processing applications, database or other information retrieval, and, of course, interactive games.

WebLS is another Amzi! product that is an example of the type of application you can implement using the CGI-Amzi! interface. WebLS is a custom rule engine that uses a simple rule language to let webmasters add expertise to their Web pages. The rule engine is written in Prolog and uses HTML specified in WebLS question and answer fields to communicate with the user.

Architecture

CGI provides a way for an application to communicate with a Web server. The Web server calls the CGI application when it receives information from the user, and the CGI application can send generated HTML back to the user through the Web server.

The executable file that the server calls is written in C, and is provided with full source code. That program starts the Amzi! Logic Server and loads the Prolog CGI script. Before calling the main entry point of the Prolog script, the CGI executable program first gathers information from the HTML form and asserts that information to the Prolog dynamic database. This step is what allows the Prolog code to easily reason over the information entered by the user in the incoming HTML form.

The CGI executable than calls the Prolog portion of the CGI-Amzi! interface. This is a Prolog wrapper that provides many of the bookkeeping functions necessary for CGI. That Prolog program then calls predicates that are defined in the user-written Prolog script. From this point, the user Prolog program is processing the CGI data.

The Prolog program communicates back with the CGI interface through a number of extended predicates that are implemented in both the Prolog wrapper and C executable program.

Sample

Infoform is a simple example of a form editting application. The full source is available in the SAMPLES/CGI directory, and it is running on Amzi!'s Web site to gather user's information requests.

The main entry point looks at the CGI variable 'Request Method', which was asserted by the CGI executable shell, and calls processMethod with its value. Usually a 'get' request is used when the user wants to receive a form for the first time, and a 'post' request is used to submit information. You can control which type of request is used by setting 'method=' in your <FORM ...> definition.

cgiMain :-
  cgi('Request Method', RM),
  processMethod(RM).
cgiMain :-
  throw($cgiMain failed\n$).

The predicate processMethod/1 calls various helper predicates to check the information on the form and either thanks the user or gives them the opportunity to edit and fix the inputs. It generates HTML for the output form using the extended predicate cgiSend/1.

% 
% For the initial get, simply return our HTML form
%
processMethod('GET') :-
  cgiSend($Content-type: text/html$),
  cgiSend($$),
  cgiSendLocalHTMLFile('infoform.htm').
% 
% After the user has filled in the form, we need to check it, then 
% send a response back. 
% 
processMethod('POST') :- 
  sendHeader,
  checkFacts,
  writeRequestLog,
  cgiSend($Thank you! Your information request has been successfully submitted!$),
  cgiSend($<P>Return to <A HREF="/index.html">Amzi!'s home page</A>.$),
  sendFooter.
processMethod('POST') :-
  cgiSend($<P>Press the 'Back' or '&lt;-' button on your browser to change your form and resubmit it.$),
  sendFooter. 

Here is one of the checking predicates. It looks at the various fact/2 clauses that were asserted in the dynamic database by the CGI executable shell. Each fact represents an input field that was filled in on the original HTML form. In this case it sees if the user has requested a catalog or newsletters. If not,then there is no potential problem. If so, then make sure there is information entered for the three address fields.

checkAddress :-
  fact(request, RL),
  not(member(catalog, RL)),
  not(member(newsletters, RL)),
  !.
checkAddress :-
  fact(address1, A1),
  fact(city, C1),
  fact(country, C2),
  !.
checkAddress :-
  cgiSend($Please fill in your mailing address including street, city, region and country.$),
  fail, !.

Implementation

The Amzi! implementation supports the current CGI 1.1 standard, and also includes support for the 'Windows CGI' 1.3a quasi-standard.

The CGI interface consists of two parts. First, there is a Prolog library which provides the basic framework for the script and many supporting functions. Second, there is a C program that invokes the script framework in the Prolog library and also provides some additional supporting functions. The files are:

In the SAMPLES/CGI subdirectory, you will find an example of the simple information gathering form described above.

Building the C Program

The first step is to compile and link the C program for your particular web server and environment. You need to define either STDCGI for the standard CGI interface or WINCGI for the Windows CGI interface. Then compile and link AMZICGI.C and AMZISUB.C into an executable. As currently written, the C program loads an XPL file with the same name. For example, AMZICGI.EXE will load AMZICGI.XPL.

Writing the Prolog Script

The second step is to write a Prolog script that conforms to the framework provided in ACGI.PRO. You need to define the following predicates:

cgiStart/0
This predicate is called before anything else, and may be used to set up a debugging log file or other system parameters.
cgiLoad/0
This predicate needs to consult or load any external Prolog modules, rule sets or logic-bases. All the cgi and system variables are already asserted into the dynamic database and the output file has been opened.
cgiMain/0
This is your main script which processes get and post requests from forms.
cgiErrorNote/0
This outputs additional information (via cgiSend) when an unexpected but fatal error occurs. Generally you will want to output who to contact about the problem.

CGI Variables

Within your CGI script (cgiMain) you will want to access the values entered into the forms. These are all dynamically asserted as:

fact(field_name, value)

The field names and values are Prolog atoms.

You script can also access the values of many CGI variables. The Amzi! implementation uses the Windows CGI names and create predicates of arity 2 representing each value. For example:

cgi('Content Length', $1462$)

All cgi, extraheader and accept variables have string values. All system variables have atom values.

The following table lists the possible CGI variables that may be set. Web servers differ in the variables they set and the format of the values they use.

Standard CGI Name Windows CGI Name Predicate Name
AUTH_NAME 'Authentication Realm' cgi
AUTH_USER 'Authentication Username' cgi
AUTH_TYPE 'Authentication Method' cgi
CGI_VERSION 'CGI Version' cgi
CONTENT_FILE 'Content File' cgi
CONTENT_LENGTH 'Content Length' cgi
CONTENT_TYPE 'Content Type' cgi
COOKIE 'Cookie' extraheaders
GATEWAY_INTERFACE 'Gateway Interface' cgi
HTTP_COOKIE 'Cookie' extraheaders
HTTP_FROM 'From' cgi
HTTP_REFERER 'Referer' cgi
HTTP_USER_AGENT 'User Agent' cgi
LOGNAME 'Remote User' cgi
PATH_INFO 'Logical Path' cgi
PATH_TRANSLATED 'Physical Path' cgi
QUERY_STRING 'Query String' cgi
REFERER_URL 'Referer' cgi
REMOTE_ADDR 'Remote Address' cgi
REMOTE_HOST 'Remote Host' cgi
REMOTE_USER 'Remote User' cgi
REQUEST_METHOD 'Request Method' cgi
REQUEST_RANGE 'Request Range' cgi
SCRIPT_NAME 'Executable Path' cgi
SERVER_ADMIN 'Server Admin' cgi
SERVER_NAME 'Server Name' cgi
SERVER_PORT 'Server Port' cgi
SERVER_PROTOCOL 'Server Protocol' cgi
SERVER_SOFTWARE 'Server Software' cgi
USER_AGENT 'User Agent' cgi
DEBUG_MODE 'Debug Mode' system
GMT_OFFSET 'GMT Offset' system

There are some additional system variables that affect the operation of the functions provided by ACGI.PRO. These are:

'Log File'
This is the name of the file to write logging information to (via cgiLog). It is the pathname passed to the operating system to open the file. It must be an atom. If you have not defined a log file, then all calls to cgiLog are ignored.
'Log File URL'
This is the URL of the log file for easy access to the file from your web browser.

CGI Predicates

All CGI predicates provided by ACGI.PRO and by AMZISUB.C begin with 'cgi'. They are:

cgiExpandChars(InputList, OutputList)
Given a character list, these clauses expand special characters into their proper HTML representations, e.g. > becomes &gt; This could be used by the error handler when reporting syntax (read) errors as the buffer contains parts of the logic-base which include HTML tags which are not to be interpreted, simply displayed.
cgiSend(ListOrTerm)
Outputs the list of terms or the term (which may be a string, atom, number, etc. to the output file.
cgiSendLocalHTMLFile(FileName)
Outputs the contents of an existing HTML text file to the output file. You must output the header separately before calling this function. This allows you to intermix "canned" HTML with generated HTML.
cgiSendURL(URL)
Tells the server to redirect to the specified URL.
cgiAskField(Key, Prompt, Length, Separator, DefaultValue)
Outputs the Prompt into the current HTML output file with the input box of the specified Length and DefaultValue, followed by the Separator.
cgiAskYesNo(Key, Prompt, Separator)
Outputs the Prompt and asks for a yes, no or unknown radio button to be checked.
cgiAskMenu(Key, Prompt, Choices, Type, Separator)
Outputs the Prompt and a checkbox, radio or drop-down menu containing the items in the Choices list, each separated by the Separtor.
cgiAskTextbox(Key, Prompt, Length, Separator)
Outputs a textarea with Length rows followed by Separator.
cgiLog(Stuff)
If logging is enabled (by the existence of a system fact named 'Log File') then write Stuff to it. The first write causes the file to be opened, and all the system, cgi and facts to be written to it. The file is closed automatically when the script finishes.
cgiLogSuspend
Suspends output to the log file via cgiLog calls.
cgiLogResume
Resumes output to the log file via cgiLog calls.

Copyright ©1987-1997 Amzi! inc. All Rights Reserved.