LuaSearch - Navigate Lua Module Documentation


NAME

cgilua - web CGI handling (CGILua)


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 (http://www.keplerproject.org/kepler/).

CGILua includes a set of external libraries that allows the handling of Cookies, Serialized Data and Sessions. To use these libraries just require them in your CGILua config.lua file.


DOWNLOAD

CGILua source code can be downloaded from its LuaForge (http://luaforge.net/projects/cgilua/files) page


INSTALLATION

CGILua follows the package model (http://www.inf.puc-rio.br/~roberto/pil2/chapter15.pdf) for Lua 5.1, therefore it should be ``installed''. Refer to Compat-5.1 configuration (http://www.keplerproject.org/compat/manual.html#configuration) section about how to install the modules properly in a Lua 5.0 environment.


CONFIGURATION

CGILua 5.0 offers a single configuration file, called config.lua 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 config.lua you can use a separate directory for configuration files.

If you using Kepler it creates a $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 config.lua customization are:

Script Handlers
A handler is responsible for the response of a request. You can add new CGILua handlers using cgilua.addscripthandler (see also cgilua.buildplainhandler and cgilua.buildprocesshandler for functions that build simple handlers).

POST Data Sizes
You can change the POST data size limits using cgilua.setmaxinput and cgilua.setmaxfilesize.

Opening and Closing Functions
You can add your functions to the life cycle of CGILua using cgilua.addopenfunction and cgilua.addclosefunction. These functions are executed just before and just after the script execution, even when an error occurs in the script processing.

In particular, the opening and closing functions are useful for different things. Some examples of the use of such functions in config.lua are shown next.

Previous versions of CGILua loaded a env.lua 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)

Note that the function cgilua.addopenfunction must be used to call cgilua.session.open because this function needs to change the cgi table (see section Receiving parameters: the cgi table for more information on this special table) which is not yet available during the execution of the config.lua file (see the Request life cycle (Request life cycle)).

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 require 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)


Introduction

CGILua uses Lua (http://www.lua.org) as a server-side scripting language for creating dynamic Web pages. Both pure Lua Scripts (Lua Scripts) and Lua Pages (Lua Pages) (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 (Lua Scripts) and Lua Pages (Lua Pages).

Architecture

CGILua architecture is divided in two layers. The lower level is represented by the Server API (SAPI (Server API)) 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 (http://www.keplerproject.org/kepler/).

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.

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:

Add default handlers such as LuaScripts and Lua Pages.
Execute the config.lua file, allowing the customization of the next steps.
Remove dangerous globals (such as debug) from the user script environment.
Build the cgi table (processing POST and GET data).
Change to user script directory.
Execute the registered open functions.
Execute the requested script with the correct environment.
Execute the registered close functions.
Change back to the original directory

Editing the config.lua file one can customize the CGILua behaviour. One typical use would be registering the open and close 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 (Configuration), or even to implement new abstractions over the whole CGILua way of live, like MVC-frameworks such as Orbit.

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 .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 (Headers) and then sending the actual document contents (Content Generation).

CGILua offers some functions to ease these tasks, such as cgilua.htmlheader to produce the header for a HTML document and cgilua.put 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([[
  <html>
  <head>
    <title>Hello World</title>
  </head>
  <body>
    <strong>Hello World!</strong>
  </body>
  </html>]])

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&aacute; Mundo!'
  else
    greeting = '[unknown language]'
  end
  
  cgilua.put('<html>')  
  cgilua.put('<head>')
  cgilua.put('  <title>'..greeting..'</title>')
  cgilua.put('</head>')
  cgilua.put('<body>')
  cgilua.put('  <strong>'..greeting..'</strong>')
  cgilua.put('</body>')
  cgilua.put('</html>')

In the above example the use of cgi.language indicates that language was passed to the Lua Script as a CGILua parameter (Receiving parameters: the cgi table), 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.

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

<?lua chunk ?>
Processes and merges the Lua chunk execution results where the markup is located in the template. The alternative form <% chunk %> can also be used.

<?lua= expression ?>
Processes and merges the Lua expression evaluation where the markup is located in the template. The alternative form <%= expression %> can also be used.

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:

  <html>
  <?lua
  if cgi.language == 'english' then
    greeting = 'Hello World!'
  elseif cgi.language == 'portuguese' then
    greeting = 'Ol&aacute; Mundo!'
  else
    greeting = '[unknown language]'
  end
  ?>
  <head>
    <title><%= greeting %></title>
  </head>
  <body>
    <>strong<%= greeting %></strong>
  </body>
  </html>

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 getGreeting was definied in file functions.lua as follows:

  function getGreeting()
    local greeting
    if cgi.language == 'english' then
      greeting = 'Hello World!'
    elseif cgi.language == 'portuguese' then
      greeting = 'Ol&aacute; Mundo!'
    else
      greeting = '[unknown language]'
    end
    return greeting
  end

the Lua Page could be rewriten as:

  <?lua
  assert (loadfile"functions.lua")()
  ?>
  <html>
  <head>
    <title><%= getGreeting() %></title>
  </head>
  <body>
    <strong><%= getGreeting() %></strong>
  </body>
  </html>

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("<ul>")
  for i, item in ipairs(list) do
      cgilua.put("<li>"..item.."</li>")
  end
  cgilua.put("</ul>")

The equivalent loop in Lua Page would be:

  <ul>
      <% for i, item in ipairs(list) do %>
      <li><%= item %></li>
      <% end %>
  </ul>

Receiving parameters: the cgi 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 cgi 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:

filename
the file name as given by the client.

filesize
the file size in bytes.

file
the temporary file handle. The file must be copied because CGILua will remove it after the script ends.

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

Error Handling

There are three functions for error handling in CGILua:

The function cgilua.seterrorhandler defines the error handler, 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: debug.traceback.

The function cgilua.seterroroutput 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 (http://luasocket.luaforge.net/) or LuaLogging (http://www.keplerproject.org/lualogging/) for example).

The function cgilua.errorlog 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", "<br>\n"), "\t", "&nbsp;&nbsp;")
                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"<h1>An error occurred</h1>\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.


Headers

Headers functions are used to change the HTTP response headers and consist of:

cgilua.contentheader

  cgilua.contentheader (type, subtype)

Sends a Content-type header with the given values of type and sub-type.

Both arguments are strings: type is the header type; subtype is the header sub-type.

Returns nothing.

cgilua.header

  cgilua.header (header, value)

Sends a generic header. This function should not be used to generate a Content-type nor a Location header because some launchers/web-servers use different functions for this purpose.

Both arguments are strings: header is the name of the header; value is its value.

Returns nothing.

cgilua.htmlheader

cgilua.htmlheader ()

Sends the header of an HTML file (Content-type: text/html).

Returns nothing.

cgilua.redirect

  cgilua.redirect (url, args)

Sends the header to force a redirection to the given URL adding the parameters in table args to the new URL.

The first argument (url) is the URL the browser should be redirected to; the second one (args) is an optional table which could have pairs name = value that will be encoded to form a valid URL (see function cgilua.urlcode.encodetable).

Returns nothing.


Content Generation

Content generation functions are used to output text to the response and to generate URLs in the CGILua format. They consist of:

cgilua.mkabsoluteurl

  cgilua.mkabsoluteurl (path)

Creates an absolute URL containing the given URL path.

Returns the resulting absolute URL.

cgilua.mkurlpath

  cgilua.mkurlpath (script [, args])

Creates an URL path to be used as a link to a CGILua script using the optional table of arguments (args). The arguments are used in the URL as query string parameters. Returns the resulting URL.

cgilua.put


  cgilua.put (string)

Sends the given string to the client. This function should always be used, do not use print or io.write for output otherwise your script may not work for every launching method.

Returns nothing.


Lua Pages

Lua Pages functions are used to process Lua Pages templates and to define the behavior of this processing. They consist of:

cgilua.handlelp

  cgilua.handlelp (filename)

Equivalent to cgilua.lp.include but sends the HTML header before the pre-processed file.

Returns nothing.

cgilua.lp.compile


  cgilua.lp.compile (string)

Compile a piece of code given as a string into a Lua function. The string is translated with cgilua.lp.translate into another string which is transformed into a function with loadstring. The resulting function is cached internaly and reused if the same piece of code is given.

Returns a function.

cgilua.lp.include

  cgilua.lp.include (filename)

Pre-processes a Lua Page template (given by filename) and sends the result to the client. The file content is processed by cgilua.lp.compile and no headers are sent.

Returns nothing.

cgilua.lp.setcompatmod

  cgilua.lp.setcompatmode (boolean)

Turns on or off the compatibility mode. Turning it on will make the Lua Pages preprocessor understand the expression fields and code fields structures used by previous versions of CGILua.

Default value: true

Returns nothing.

cgilua.lp.setoutfunc

  cgilua.lp.setoutfunc (funcname)

Defines the name of the output function for templates. The Lua Pages preprocessor will generate calls to the function with the given funcname (a string).

Returns nothing.

cgilua.lp.translate

  cgilua.lp.translate (string)

Uses the Lua Pages preprocessor to generate a string corresponding to the Lua code that executes the Lua chunks and/or expressions inside the given string.

Returns a string with the resulting Lua code.


CGILua Variables

CGILua Variables offers information about the script being processed and the CGI environment variables (SAPI.Request.servervariable) depending on the Web server and launcher used. They consist of both atributes and functions:

cgilua.script_file

  cgilua.script_file

The file name of the running script. Obtained from cgilua.script_path.

cgilua.script_path

  cgilua.script_path

The complete path of the running script. This variable is usually the same as the CGI environment variable (SAPI.Request.servervariable) PATH_TRANSLATED.

cgilua.script_pdir

  cgilua.script_pdir

The directory of the running script. Obtained from cgilua.script_path.

cgilua.script_vdir

  cgilua.script_vdir

The virtual directory of the running script. Obtained from cgilua.script_vpath.

cgilua.script_vpath

  cgilua.script_vpath

The complete virtual path of the running script. Equivalent to the CGI environment variable (SAPI.Request.servervariable) PATH_INFO.

cgilua.servervariable

  cgilua.servervariable (varname)

Returns a string with the value of the CGI environment variable correspoding to varname. For a list of CGI variables please refer to /SAPI.Request.servervariable.

cgilua.urlpath

  cgilua.urlpath

The name of the script. Equivalent to the CGI environment variable (SAPI.Request.servervariable) SCRIPT_NAME.


Error Handling

CGILua error handling functions allow the redefinition of how errors are handled and presented to the user. The consist of:

cgilua.errorlog

  cgilua.errorlog (string)

Sends the given string to the error log file.

Returns nothing.

cgilua.seterrorhandler

  cgilua.seterrorhandler (func)

Sets the error handler function to func. This function is called by Lua when an error occurs. It receives the error message generated by Lua and it is responsible for generating and returning the correct error message to be used by CGILua.

Returns nothing.

cgilua.seterroroutput

  cgilua.seterroroutput (func)

Sets the error output function to func. This function is called by Lua to generate the error output itself.

Returns nothing.


CGILua behavior

The behavior of CGILua can be configured using this set of functions:

cgilua.addclosefunction (func)

Defines a function (func) to be called after the execution of the script requested.

Returns nothing.

cgilua.addopenfunction

  cgilua.addopenfunction (func)

Defines a function (func) to be called before the execution of the script requested.

Returns nothing.

cgilua.addscripthandler

  cgilua.addscripthandler (ext, func)

Defines a function (func) to pre-process files with a certain extension (ext). The default configuration uses cgilua.doscript to process Lua Scripts (.lua files) and cgilua.handlelp to process Lua Pages (.lp files).

Returns nothing.

cgilua.buildplainhandler

  cgilua.buildplainhandler (type, subtype)

Creates a script handler that sends the given header and the plain file requested. The Content-type header is formed by the two arguments; the created function will receive a filename as its only argument and will return the given filename untouched.

Returns a function.

cgilua.buildprocesshandler

  cgilua.buildprocesshandler (type, subtype)

Creates a script handler that sends the given header and the processed file requested. The Content-type header is formed by the two arguments; the created function will receive a filename as its only argument and will return the given filename pre-processed by the function cgilua.lp.include.

Returns a function.

cgilua.setmaxfilesize

  cgilua.setmaxfilesize (size)

Sets the maximum size (in bytes) for each uploaded file. This value is bounded by the maximum total input size (see cgilua.setmaxinput. This function only takes effect if used before POST data is processed, therefore its use in scripts are meaningless.

Returns nothing.

cgilua.setmaxinput

  cgilua.setmaxinput (size)

Sets the maximum total input size allowed (in bytes). This function only takes efect if used before POST data is processed, therefore its use in scripts are meaningless.

Returns nothing.


URL encoding functions

CGILua enconding functions allow the processing of URL strings in a simple way:

cgilua.urlcode.encodetable

  cgilua.urlcode.encodetable (table)

URL-encode the elements of a table creating a string to be used as a URL for passing data/parameters to another script.

Returns a string representing the encoded argument table.

cgilua.urlcode.escape

  cgilua.urlcode.escape (string)

URL-encode a string.

Returns the encoded string.

cgilua.urlcode.insertfield

  cgilua.urlcode.insertfield (args, name, value)

Adds the given value to the field indexed by name in the args table. If the field already has a value, it is transformed into a table with this value at index 1 and the new value at index 2. Other values will be added at the end of the array-part of the created table.

Returns nothing.

cgilua.urlcode.parsequery

  cgilua.urlcode.parsequery (query, args)

Parse URL-encoded request data. This could be the query part of the script URL or URL-encoded POST data. Each decoded name = value pair is inserted into the args table.

Returns nothing.

cgilua.urlcode.unescape

  cgilua.urlcode.unescape (string)

URL-decodes a string.

Returns the decoded string.


Auxiliar functions

cgilua.doif

  cgilua.doif (filepath)

Executes a file (given by filepath) if it exists. Returns the values returned by the execution, or <tt>nil</tt> followed by an error message if the file does not exists.

cgilua.doscript

  cgilua.doscript (filepath)

Executes a file (given by filepath). Raises an error if it occurs. In case of success, returns the values returned by the execution.

cgilua.pack

  cgilua.pack (...)

Returns a new table with all the passed arguments stored in it.

cgilua.splitpath

  cgilua.splitpath (path)

Returns two strings with the ``directory'' and ``file'' parts of the given path.


Cookies

cgilua.cookies.get

  cgilua.cookies.get (name)

Gets the value of the cookie with the given name.

Returns a string with the value of the cookie.

cgilua.cookies.set

  cgilua.cookies.set (name, value[, options])

Sets the value of the cookie with a given name. The optional table options is used togive the values of the cookies attributes: expires, path, domain, secure. This function should be called before the HTTP headers are sent and before any output is generated, so it must not be used inside a Lua Page.

This function sends a cookie with the response. If you need to create a cookie inside the generated response or if the cookie needs to be set inside the client, use cgilua.cookies.sethtml instead.

Returns nothing.


=head2 C<cgilus.cookies.sethtml>
  cgilua.cookies.sethtml (name, value[, options])

Sets the value of the cookie with a given name. The optional table options is used to give the values of the cookies attributes: expires, path, domain, secure.

This function generates a <meta> HTML element so it should be called after the <head> HTML tag and before the corresponding </head>.

This function creates a cookie in the client, if you need to send the cookie with the response use cgilua.cookies.set instead.

Returns nothing.

cgilua.cookies.delete

  cgilua.cookies.delete (name[, options])

Deletes a cookie with a given name (setting its value to xxx). This function should be called before the HTTP headers are sent and before any output is generated.

Returns nothing.


Serialize

cgilua.serialize

  cgilua.serialize (table, outfunc[, indent[, prefix]])

Serializes a table using outfunc as the function to be used to generate the output; indent as an optional string with the indentation pattern; prefix as an optional string with the indentation prefix (it is used to store the actual indentation between the recursion calls).

Some restrictions must be noted: values of types function and userdata are not serialized; tables with cycles are not serialized. Returns nothing.


Session

cgilua.session.close

  cgilua.session.close ()

Closes the user session. Saves all data in cgilua.session.data to the storage system being used (usually the filesystem). This function should be called after the end of the script execution. A recommended way to ensure that is to use cgilua.addclosefunction in the configuration file.

Returns nothing.

head2 cgilua.session.data


  cgilua.session.data

Table which holds the user session data.

cgilua.session.delete

  cgilua.session.delete (id)

Deletes a session. The argument id is the session identifier.

Returns nothing.

cgilua.session.load

  cgilua.session.load (id)

Loads data from a session. The argument id is the session identifier.

Returns a table with session data or nil followed by an error message.

cgilua.session.new

  cgilua.session.new ()

Creates a new session identifier.

Returns the new session identifier.

cgilua.session.open

  cgilua.session.open ()

Opens the user session. Creates the table cgilua.session.data. This function should be called just before the execution of the script, but after the processing of the request's headers. A recommended way to ensure that is to use cgilua.addopenfunction in the configuration file.

Returns nothing.

cgilua.session.save


  cgilua.session.save (id, data)

Saves data to a session with an id.

Returns nothing.

cgilua.session.setsessiondir

cgilua.session.setsessiondir (path)

Defines the session temporary directory. Argument path is a string with the new directory.

Returns nothing.


Server API

The Server API (SAPI) is a set of functions that encapsulate the web server and the used launcher. A SAPI launcher is the mechanism that allows a Web server to execute and communicate with CGILua and its Web applications. SAPI allows the abstraction of a series of internal details and allows CGILua to be a lot more portable, since porting CGILua to a new platform means simply writing a SAPI Launcher for the target platform.

Kepler is the reference implementation of SAPI launchers and currently supports Apache, Microsoft IIS and Xavante as Web servers, and CGI, FastCGI, mod_lua and ISAPI as Launchers. Xavante has a native SAPI launcher.

The functions implemented by launchers are separated into two packages: SAPI.Request and SAPI.Response.

The SAPI.Request package offers two functions:

SAPI.Request.getpostdata

  SAPI.Request.getpostdata ([n])

Gets a block of POST data. The optional parameter n is the number of bytes to read (a default block size is used if no parameter is passed).

Returns the block as a Lua string.

SAPI.Request.servervariable

  SAPI.Request.servervariable (string)

Gets the value of a server environment variable. The argument can be one of the defined CGI Variables (http://hoohoo.ncsa.uiuc.edu/cgi/env.html), although not all servers implements the full set of variables. The set consists of:

AUTH_TYPE
If the server supports user authentication, and the script is protected, this is the protocol-specific authentication method used to validate the user.

CONTENT_LENGTH
The length of the content itself as given by the client.

CONTENT_TYPE
For queries which have attached information, such as HTTP POST and PUT, this is the content type of the data.

GATEWAY_INTERFACE
The revision of the CGI specification to which this server complies. Format: CGI/revision

PATH_INFO
The extra path information, as given by the client. In other words, scripts can be accessed by their virtual pathname, followed by extra information at the end of this path. The extra information is sent as PATH_INFO. This information should be decoded by the server if it comes from a URL before it is passed to the CGI script.

PATH_TRANSLATED
The server provides a translated version of PATH_INFO, which takes the path and does any virtual-to-physical mapping to it.

QUERY_STRING
The information which follows the ``?'' in the URL which referenced this script. This is the query information. It should not be decoded in any fashion. This variable should always be set when there is query information, regardless of command line decoding.

REMOTE_ADDR
The IP address of the remote host making the request.

REMOTE_HOST
The hostname making the request. If the server does not have this information, it should set REMOTE_ADDR and leave this unset.

REMOTE_IDENT
If the HTTP server supports RFC 931 identification, then this variable will be set to the remote user name retrieved from the server. Usage of this variable should be limited to logging only.

REMOTE_USER
If the server supports user authentication, and the script is protected, this is the username they have authenticated as.

REQUEST_METHOD
The method with which the request was made. For HTTP, this is ``GET'', ``HEAD'', ``POST'', etc.

SCRIPT_NAME
A virtual path to the script being executed, used for self-referencing URLs.

SERVER_NAME
The server's hostname, DNS alias, or IP address as it would appear in self-referencing URLs.

SERVER_PORT
The port number to which the request was sent.

SERVER_PROTOCOL
The name and revision of the information protcol this request came in with. Format: protocol/revision

SERVER_SOFTWARE
The name and version of the web server software answering the request (and running the gateway). Format: name/version

In addition to these, the header lines received from the client, if any, are placed into the environment with the prefix HTTP_ followed by the header name. Any - characters in the header name are changed to _ characters. The server may exclude any headers which it has already processed, such as Authorization, Content-type, and Content-length. If necessary, the server may choose to exclude any or all of these headers if including them would exceed any system environment limits.

Returns a string.

And the SAPI.Response package offers five functions:

SAPI.Response.contenttype

  SAPI.Response.contenttype (string)

Sends the Content-type header to the client. The given string is of the form ``type/subtype''. This function must be called before any output is sent using SAPI.Response.write

Returns nothing.

SAPI.Response.errorlog

  SAPI.Response.errorlog (string)

Generates error output using the given string.

Returns nothing.

SAPI.Response.header

  SAPI.Response.header (header, value)

Sends a generic header to the client. The first argument must be the header name, such as ``Set-Cookie''. The second argument should be its value. This function should not be used to replace the SAPI.Response.contenttype nor the SAPI.Response.redirect functions.

Returns nothing.

SAPI.Response.redirect

  SAPI.Response.redirect (url)

Sends the Location header to the client. The given url should be a string.

Returns nothing.

SAPI.Response.write

  SAPI.Response.write (string)

Generates output using the given string.

Returns nothing.


VERSION

Current version is 5.0.1


HISTORY

Version 5.0.1 [20/Sep/2006]
  Uses Compat-5.1 Release 5.
  Caches Lua Pages template strings.
  New configuration examples.
  Improvements in the L<session> library.
  Removed the C<debug> package from the user scripts environment.
  POST handling bug fixes (related to the C<text/plain> content type).
Version 5.0</strong> [23/Jul/2005]
  CGILua distribution includes now only the Lua files, the launchers
    have been moved to Kepler (L<http://www.keplerproject.org/kepler/>;).
  The Stable (L<http://www.keplerproject.org/venv/manual.html#reference>;)
    library is now distributed with VEnv (L<http://www.keplerproject.org/venv/>;).
  Fixed a file upload bug in the CGI and Xavante launchers.
  C<cgilua.lp.include()> now accepts an environment to run
    the preprocessed file in it.
Version 5.0 beta 2 [23/Dec/2004]
  Distribution bug fix: stable.lua was missing
Version 5.0 beta [15/Dec/2004]
  New ISAPI and Servlet Launchers.
  New Error Handling features.
  New persistent data feature (Stable).
  Uses the package model (L<http://www.keplerproject.org/compat/>;)
    for Lua 5.1.
  Simpler User Session (L<session>) API.
  Small bug corrections
Version 5.0 alpha 3 [8/Jun/2004]
Version 5.0 alpha [21/Apr/2004]

Incompatibility with previous CGILua versions (4.0 and 3.x)

CGILua 5.0 uses Lua 5.0 (http://www.lua.org).

The cgi table now allows table values. See Receiving parameters: the cgi table for a more detailed explanation.

The template tags have changed. See Lua pages (Lua Pages) for a more detailed explanation.

The use of getenv calls to obtain CGI variables should be replaced by cgilua.servervariable calls.


CREDITS

CGILua 5.0
CGILua 5.0 was completely redesigned by Roberto Ierusalimschy, André Carregal and Tomás Guisasola as part of the Kepler Project (http://www.keplerproject.org). The implementation is compatible with Lua 5.0 and was coded by Tomás Guisasola with invaluable contributions by Ana Lúcia de Moura, Fábio Mascarenhas and Danilo Tuler. CGILua 5.0 development was sponsored by Fábrica Digital (http://www.fabricadigital.com.br), FINEP (http://www.finep.gov.br/) and CNPq (http://www.cnpq.br/).

CGILua 4.0
Ana Lúcia de Moura adapted CGILua 3.2 to Lua 4.0, reimplemented some code and added a few improvements but this version was not officially distributed.

CGILua 3.x
CGILua was born as the evolution of an early system developed by Renato Ferreira Borges and André Clínio at TeCGraf (http://www.tecgraf.puc-rio.br). At the time (circa 1995) there were no CGI tools available and everything was done with shell scripts!

However, the main contribution to CGILua 3 was done by Anna Hester, who consolidated the whole tool and developed a consistent distribution with versions 3.1 and 3.2 (the number was an effort to follow Lua version numbers). This version was widely used on a great variety of systems.


CONTACT

For more information please contact us (info-NO-SPAM-THANKS@keplerproject.org) Comments are welcome!

You can also reach other CGILua developers and users on the Kepler Project mailing list (http://luaforge.net/mail/).


LICENSE

CGILua is free software and uses the same license as Lua 5.0.

CGILua is free software: it can be used for both academic and commercial purposes at absolutely no cost. There are no royalties or GNU-like ``copyleft'' restrictions. CGILua qualifies as Open Source (http://www.opensource.org/docs/definition.html) software. Its licenses are compatible with GPL (http://www.gnu.org/licenses/gpl.html). CGILua is not in the public domain and the Kepler Project (http://www.keplerproject.org) keep its copyright. The legal details are below.

The spirit of the license is that you are free to use CGILua for any purpose at no cost without having to ask us. The only requirement is that if you do use CGILua, then you should give us credit by including the appropriate copyright notice somewhere in your product or its documentation.

The CGILua library is designed and implemented by Roberto Ierusalimschy, André Carregal and Tomás Guisasola. The implementation is not derived from licensed software.

~~~~~

Copyright © 2003-2006 The Kepler Project.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ``Software''), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

~~~~~