=head1 NAME
cgilua - web CGI handling (CGILua)
=head1 OVERVIEW
CGILua is a tool for creating dynamic Web pages and manipulating input
data from Web forms. CGILua allows the separation of logic and data
handling from the generation of pages, making it easy to develop web
applications with Lua.
One of advantages of CGILua is its abstraction of the underlying Web
server. You can develop a CGILua application for one Web server and
run it on any other Web server that supports CGILua, even if using a
different launching model.
CGILua can be used with a variety of Web servers and, for each server,
with different launchers. A launcher is responsible for the
interaction of CGILua and the Web server, for example using ISAPI on
IIS or mod_lua on Apache. The reference implementation of CGILua
launchers is Kepler (L).
CGILua includes a set of external libraries that allows the handling
of Cookies, Serialized Data and Sessions. To use these libraries just
C them in your CGILua C file.
=head1 DOWNLOAD
CGILua source code can be downloaded from its LuaForge
(L) page
=head1 INSTALLATION
CGILua follows the package model
(L) for Lua
5.1, therefore it should be "installed". Refer to Compat-5.1
configuration
(L)
section about how to install the modules properly in a Lua 5.0
environment.
=head1 CONFIGURATION
CGILua 5.0 offers a single configuration file, called
C and a set of functions to alter the default
CGILua behaviour. This file can be placed anywhere in the Lua Path,
but to make easier to upgrade CGILua without overwriting your
C you can use a separate directory for
configuration files.
If you using Kepler it creates a C<$CONF> directory for the
configuration files. For more details on this usage of Lua Path please
check the Kepler documentation.
Some of the uses of C customization are:
=over 4
=item Script Handlers
A handler is responsible for the response of a request. You can add
new CGILua handlers using C (see also
C and C for
functions that build simple handlers).
=item POST Data Sizes
You can change the POST data size limits using C
and C.
=item Opening and Closing Functions
You can add your functions to the life cycle of CGILua using
C and C. These
functions are executed just before and just after the script
execution, even when an error occurs in the script processing.
=back
In particular, the opening and closing functions are useful for
different things. Some examples of the use of such functions in
C are shown next.
Previous versions of CGILua loaded a C file from
the script directory before processing it. To emulate this with CGILua
5.0 you can use something like:
cgilua.addopenfunction (function ()
cgilua.doif ("env.lua")
end)
If every script needs to load a module (such as the sessions library),
you can do:
require"cgilua.session"
cgilua.session.setsessiondir"/tmp/"
cgilua.addopenfunction (cgilua.session.open)
cgilua.addclosefunction (cgilua.session.close)
I that the function C must be used to
call C because this function needs to change the
C table (see section L for
more information on this special table) which is not yet available
during the execution of the C file (see the Request life
cycle (L)).
When some scripts may use the library but others may not, you could
define an "enabling" function (which should be called at the very
beginning of each script that needs to use sessions):
require"cgilua.session"
cgilua.session.setsessiondir"/tmp/"
cgilua.enablesession = function ()
cgilua.session.open ()
cgilua.addclosefunction (cgilua.session.close)
end
Sometimes you need to configure a private libraries directory for each
application hosted in the server. This configuration allows the
function C to find packages installed in the
private directory and in the system directory but not in other
application's private directory. To implement this you could do:
local app_lib_dir = {
["/virtual/path/"] = "/absolute/path/lib/",
}
local package = package
cgilua.addopenfunction (function ()
local app = app_lib_dir[cgilua.script_vdir]
if app then
package.path = app..'/?.lua'..';'..package.path
end
end)
=head1 Introduction
CGILua uses Lua (L) as a server-side scripting
language for creating dynamic Web pages. Both pure Lua Scripts (L) and Lua Pages (L) (LP) are supported by CGILua.
A Lua Script is essentially a Lua program that creates the whole
contents of a web page and returns it to the client. A Lua Page is a
conventional markup text (HTML, XML etc) file that embeds Lua code
using some special tags. Those tags are processed by CGILua and
resulting page is returned to the client.
Lua Scripts and Lua Pages are equally easy to use, and choosing one of
them basically depends on the characteristics of the resulting
page. While Lua Pages are more convenient for the separation of logic
and format, Lua Scripts are more adequate for creating pages that are
simpler in terms of its structure, but require a more significative
amount of internal processing.
Allowing these two methods to be intermixed, CGILua provides Web
applications developers with great flexibility when both requirements
are present. For a detailed description of both scripting methods and
some examples of their use see Lua Scripts (L) and Lua
Pages (L).
=head2 Architecture
CGILua architecture is divided in two layers. The lower level is
represented by the Server API (SAPI (L)) and the higher
level is represented by the CGILua API itself. SAPI is the interface
between the web server and the CGILua API, so it needs to be
implemented for each Web server and launching method used.
A launcher is responsible for the interaction of CGILua and the Web
server, implementing SAPI for example using ISAPI on IIS or mod_lua on
Apache. The reference implementation of CGILua launchers is Kepler
(L).
The CGILua API is implemented using only SAPI and is totally portable
over different launchers and their supporting Web servers. This way
any Lua Script or Lua Page can be used by any launcher.
=head2 Request life cycle
CGILua processes requests using a CGI metaphor (even if the launcher
is not based on CGI) and requests have a life cycle that can be
customized by the programmer. The CGILua request life cycle consists
in the following sequence of steps for each request:
=over 4
=item Add default handlers such as LuaScripts and Lua Pages.
=item Execute the C file, allowing the customization of the next steps.
=item Remove dangerous globals (such as C) from the user script environment.
=item Build the C table (processing POST and GET data).
=item Change to user script directory.
=item Execute the registered I functions.
=item Execute the requested script with the correct environment.
=item Execute the registered I functions.
=item Change back to the original directory
=back
Editing the C file one can customize the CGILua behaviour.
One typical use would be registering the I and I
functions in order to change the request processing behavior. With
this customization it is possible to implement new features like
session management and private library directories as shown in section
Configuration (L), or even to implement new
abstractions over the whole CGILua way of live, like MVC-frameworks
such as Orbit.
=head2 Lua Scripts
Lua Scripts are text files containing valid Lua code. This style of
usage adopts a more "raw" form of web programming, where a program is
responsible for the entire generation of the resulting page. Lua
Scripts have a default C<.lua> extension.
To generate a valid web document (HTML, XML, WML, CSS etc) the Lua
Script must follow the expected HTTP order to produce its output,
first sending the correct headers (L) and then
sending the actual document contents (L).
CGILua offers some functions to ease these tasks, such as
C to produce the header for a HTML document and
C to send the document contents (or part of it).
For example, a HTML document which displays the sentence "Hello
World!" can be generated with the following Lua Script:
cgilua.htmlheader()
cgilua.put([[
Hello World
Hello World!
]])
It should be noted that the above example generates a "fixed" page:
even though the page is generated at execution time there is no
"variable" information. That means that the very same document could
be generated directly with a simple static HTML file. However, Lua
Scripts become especially useful when the document contains
information which is not known beforehand or changes according to
passed parameters, and it is necessary to generate a "dynamic" page.
Another easy example can be shown, this time using a Lua control
structure, variables, and the concatenation operator:
cgilua.htmlheader()
if cgi.language == 'english' then
greeting = 'Hello World!'
elseif cgi.language == 'portuguese' then
greeting = 'Olá Mundo!'
else
greeting = '[unknown language]'
end
cgilua.put('')
cgilua.put('')
cgilua.put(' '..greeting..'')
cgilua.put('')
cgilua.put('')
cgilua.put(' '..greeting..'')
cgilua.put('')
cgilua.put('')
In the above example the use of C> indicates that
I was passed to the Lua Script as a CGILua parameter
(L), coming from a HTML form
field (via POST) or from the URL used to activate it (via GET). CGILua
automatically decodes such parameters so you can use them at will on
your Lua Scripts and Lua Pages.
=head2 Lua Pages
A Lua Page is a text template file which will be processed by CGILua
before the HTTP server sends it to the client. CGILua does not process
the text itself but look for some special markups that include Lua
code into the file. After all those markups are processed and merged
with the template file, the results are sent to the client.
Lua Pages have a default C<.lp> extension. They are a
simpler way to make a dynamic page because there is no need to send
the HTTP headers. Usually Lua Pages are HTML pages so CGILua sends
the HTML header automatically.
Since there are some restrictions on the uses of HTTP headers
sometimes a Lua Script will have to be used instead of a Lua Page.
The fundamental Lua Page markups are:
=over 4
=item C< ?>>
Processes and merges the Lua I execution results where
the markup is located in the template. The alternative form
C<<% I %>> can also be used.
=item C< ?>>
Processes and merges the Lua I evaluation where the
markup is located in the template. The alternative form
C<<%= I %>> can also be used.
=back
Note that the ending mark could not appear inside a Lua chunk or Lua
expression even inside quotes. The Lua Pages pre-processor just makes
global substitutions on the template, searching for a matching pair of
markups and generating the corresponding Lua code to achieve the same
result as the equivalent Lua Script.
The second example on the previous section could be written using a
Lua Page like:
<%= greeting %>
<>strong<%= greeting %>
HTML tags and Lua Page tags can be freely intermixed. However, as on
other template languages, it's considered a best practice to not use
explicit Lua logic on templates. The recommended aproach is to use
only function calls that returns content chunks, so in this example,
assuming that function C was definied in file
C as follows:
function getGreeting()
local greeting
if cgi.language == 'english' then
greeting = 'Hello World!'
elseif cgi.language == 'portuguese' then
greeting = 'Olá Mundo!'
else
greeting = '[unknown language]'
end
return greeting
end
the Lua Page could be rewriten as:
<%= getGreeting() %>
<%= getGreeting() %>
Another interesting feature of Lua Pages is the intermixing of Lua and
HTML. It is very usual to have a list of values in a table, iterate
over the list and show the items on the page.
A Lua Script could do that using a loop like:
cgilua.put("")
for i, item in ipairs(list) do
cgilua.put("- "..item.."
")
end
cgilua.put("
")
The equivalent loop in Lua Page would be:
<% for i, item in ipairs(list) do %>
- <%= item %>
<% end %>
=head2 Receiving parameters: the C table
CGILua offers an unified way of accessing data passed to the scripts
for both HTTP method used (GET or POST). No matter which method was
used on the client, all parameters will be provided inside the
C table.
Usually all types of parameters will be available as strings. If the
value of a parameter is a number, it will be converted to its string
representation.
There are only two exceptions where the value will be a Lua table. The
first case occurs on file uploads, where the corresponding table will
have the following fields:
=over 4
=item filename
the file name as given by the client.
=item filesize
the file size in bytes.
=item file
the temporary file handle. The file must be copied
because CGILua will remove it after the script ends.
=back
The other case that uses Lua tables occurs when there is more than one
value associated with the same parameter name. This happens in the
case of a selection list with multiple values; but it also occurs when
the form (of the referrer) had two or more elements with the same
C attribute (maybe because one was on a form and
another was in the query string). All values will be inserted in an
indexed table in the order in which they are handled.
=head2 Error Handling
There are three functions for error handling in CGILua:
The function C defines the I, a
function called by Lua when an error has just occurred. The error
handler has access to the execution stack before the error is thrown
so it can build an error message using stack information. Lua also
provides a function to do that: C.
The function C defines the function that
decides what to do with the error message. It could be sent to the
client's browser, written to a log file or sent to an e-mail address
(with the help of LuaSocket (L) or
LuaLogging (L) for example).
The function C
is provided to write directly to the http server error log file.
An useful example of its use could be handling unexpected errors.
Customizing unexpected error messages to the end user but giving all
the information to the application's developers is the goal of the
following piece of code:
local ip = cgilua.servervariable"REMOTE_ADDR"
local developers_machines = {
["192.168.0.20"] = true,
["192.168.0.27"] = true,
["192.168.0.30"] = true,
}
local function mail (s)
require"cgilua.serialize"
require"socket.smtp"
-- Build the message
local msg = {}
table.insert (msg, tostring(s))
-- Tries to obtain the REFERER URL
table.insert (msg, tostring (cgilua.servervariable"HTTP_REFERER"))
table.insert (msg, cgilua.servervariable"SERVER_NAME"..
cgilua.servervariable"SCRIPT_NAME")
-- CGI parameters
table.insert (msg, "CGI")
cgilua.serialize(cgi, function (s) table.insert (msg, s) end)
table.insert (msg, tostring (os.date()))
table.insert (msg, tostring (ip))
table.insert (msg, "Cookies:")
table.insert (msg, tostring (cgilua.servervariable"HTTP_COOKIE" or "no cookies"))
-- Formats message according to LuaSocket-2.0b3
local source = socket.smtp.message {
headers = { subject = "Script Error", },
body = table.concat (msg, '\n'),
}
-- Sends the message
local r, e = socket.smtp.send {
from = "sender@my.domain.net",
rcpt = "developers@my.domain.net",
source = source,
}
end
if developers_machines[ip] then
-- Developer's error treatment: write to the display
cgilua.seterroroutput (function (msg)
cgilua.errorlog (msg)
cgilua.errorlog (cgilua.servervariable"REMOTE_ADDR")
cgilua.errorlog (os.date())
cgilua.htmlheader ()
msg = string.gsub (string.gsub (msg, "\n", "
\n"), "\t", " ")
cgilua.put (msg)
end)
else
-- User's error treatment: shows a standard page and sends an e-mail to
-- the developer
cgilua.seterroroutput (function (s)
cgilua.htmlheader ()
cgilua.put"An error occurred
\n"
cgilua.put"The responsible is being informed."
mail (s)
end)
end
The message is written to the browser if the request comes from one of
the developer's machines. If it is not the case, a simple polite
message is given to the user and a message is sent to the developer's
e-mail account containing all possible information to help reproduce
the situation.
=head1 Headers
Headers functions are used to change the HTTP response headers and
consist of:
=head2 C
cgilua.contentheader (type, subtype)
Sends a I header with the given values of type and
sub-type.
Both arguments are strings: C is the header type; C is
the header sub-type.
Returns nothing.
=head2 C
cgilua.header (header, value)
Sends a generic header. This function should I be used to
generate a I nor a I header because some
launchers/web-servers use different functions for this purpose.
Both arguments are strings: C is the name of the header;
C is its value.
Returns nothing.
=head2 C
cgilua.htmlheader ()
Sends the header of an HTML file (I).
Returns nothing.
=head2 C
cgilua.redirect (url, args)
Sends the header to force a redirection to the given URL adding the
parameters in table C to the new URL.
The first argument (C) is the URL the browser should be
redirected to; the second one (C) is an optional table
which could have pairs I that will be encoded to form
a valid URL (see function C).
Returns nothing.
=head1 Content Generation
Content generation functions are used to output text to the response
and to generate URLs in the CGILua format. They consist of:
=head2 C
cgilua.mkabsoluteurl (path)
Creates an absolute URL containing the given URL C.
Returns the resulting absolute URL.
=head2 C
cgilua.mkurlpath (script [, args])
Creates an URL path to be used as a link to a CGILua C