System

This library offers some useful functions of the operating system, such as date, and file operations. More system functions are offered by Lua itself - see Lua's manual section 6.4 I/O Facilities.
 
Library's author(s):   Anna Hester and Renato Borges
Loaded by default:   yes
 
Reference:   See above.

mkdir( path )

Description
This function creates a directory on the local filesystem.
Parameters
path Path of the directory to be created (or simply a name if it is to be created under the current directory).
Return
Returns nil in case of failure or 1 in success.


chdir( path )

Description
Changes the current directory to the directory specified.
Parameters
path The path of the new working directory.
Return
No return. In case of failure, the script is aborted and an error message is given.


getcwd( )

Description
Retrieves the current working directory.
Return
A string containing the complete path of the current working directory.


cp( source, target )

Description
Copy the file in the path source to target.
Return
A nil return indicates that an error occurred; in this case, the second return is a string describing the error.
Example of use

  
  cp( "c:/test/ball.gif", "c:/www/ball.gif" )  


filetype( file )

Description
Retrieves the file type.
Parameters
file The file to be queried.
Return
One of the strings "file", "directory" or "other" according to the file type, or nil if the file type could not be retrieved.


filetime( fmt, file )

Description
Retrieves the last modification time of a file.
Parameters
fmt The format string of the output, similar to the C function strftime.
file (Optional) the file to be queried.If no value is specified, the path of the current script is used.
Return
A string with the last modification time, according to the format specified.
Example of use
The following code:
  
  $|filetime("%d/%m/%Y")|$  

produces the following output:

27/04/1999



date2sec( date, fmt )

Description
Converts a date to the corresponding number of seconds since January 1st, 1970.
Parameters
date A string containing a date.
fmt The format of the date to be scanned, following a standard
Return
The corresponding number of seconds.
Example of use
The following code:
  
  $|date2sec("5/02/1997","%d/%m/%Y")|$  

produces the following output:

855111600



sec2date( nsec, fmt )

Description
This function takes a number and converts it to a date, considering that the number is the number of seconds since January 1th, 1970.
Parameters
nsec Number of seconds.
fmt The format string of the output.
Return
The date corresponding to the number of seconds given as parameter.
Example of use
The following code:
  
  $|sec2date( date2sec("5/02/1997","%d/%m/%Y"),"%d/%m/%Y")|$  

produces the following output:

05/02/1997



lock( fhandle, mode )

Description
This function locks or unlocks a file. The mechanism is called "advisory record locking" because the lock does not prevents unauthorized access on the file, only helps programs to implement exclusive file operations. It depends, then, on programing discipline to work correctly.
Parameters
fhandle File handle of an open file. This can be provided, after a successful call to writeto, by the Lua variable _OUTPUT.
mode The kind of operation desired. Use the character l to lock a file and u to unlock.
Return
Returns nil in case of failure or 1 in success.
Example of use
The following code waits until no other process is using the file to set a lock:
  
  writeto( "data.txt")  
  while not lock( _OUTPUT, "l") do sleep (50) end  
  write ( "ok" )  
  lock( _OUTPUT, "u")  
  writeto ()  


sleep( msec )

Description
This function makes the current process or thread sleep for msec miliseconds.
Parameters
msec The amount of miliseconds to sleep.


DBLua

This library offers access to databases. On Unix systems, the Mini SQL database can be accessed. On Windows systems, any database with a ODBC driver can be accessed (MS Access, SQL Server, Oracle, Ingres, ...).
 
Library's author(s):   Mauricio Mediano
Loaded by default:   no
 
Reference:   See main functions above, but for further details refer to DBLua's homepage.

DBOpen( dbdescr )

Description
This function opens a connection to the database described by dbdescr.
Parameters
dbdescr Connection string to open database, see examples.
Return
Returns nil if the connection were successfuly open or a string describing the error occurred.
Example of use

On ODBC systems:

  
  errormsg = DBOpen("DSN=agenda;")  
  if errormsg then  
    cgilua.redirect( 'dberror.html', { msg=errormsg })  
  end  

When authentication is needed to be done explicity, the values UID and PASSWD should be given:

  
  DBOpen("DSN=agenda;UID=cgilua;PASSWD=lua;")  

On Mini-SQL systems:

  
  DBOpen('HOST=davinci;DATABASE=agenda;')  


Notes
For portability, DATABASE and DSN keywords are equivalent, and HOST is ignored on ODBC systems. Therefore, a connecition string "HOST=davinci;DATABASE=agenda;" would be valid on both ODBC and Mini-SQL systems if "agenda" is also a name of a ODBC data source name (DSN).


DBExec( sqlcommand )

Description
Executes an SQL command on the open database connection.
Parameters
sqlcommand A string with the SQL command to be executed.
Example of use

  
  DBExec( "create table tst (nome char(50), cpf char(15))" )  
  DBExec( "insert into tst values ('Luiza','001.234.567-89')" )  
  DBExec( "insert into tst values ('Fabiana','009.876.543-21')" )  
  DBExec( "delete from tst where nome = 'Luiza'")  
  DBExec( "update tst set cpf = '009.999.999-99' "..  
          "where name ='Fabiana'")  

For helping avoiding confusion with Lua's string delimiters (" or ') and SQL's string delimiters ('), the Lua's format function can be used; suppose cgi.name and cgi.cpf contains a valid input data:

  
  sql = format( "insert into tabela_teste values ('%s','%s')", cgi.name, cgi.cpf )  
  DBExec( sql )  


Notes
In case of error in the SQL statement, an execution error is issued, aborting the execution of the script. To avoid this kind of behavior, execute commands to test error situations (e.g test if a record exists with a SELECT statement before trying to deleting it). If this behaviour is really unconvenient, the error signal can be avoided redefining DBExec to use a different error method (see Lua's manual for details and the file cgilua.conf/dblua.lua for an example of this kind of redefinition).


DBRow( )

Description
This function retrieves the next row of the result table produced by the SQL query previously executed (function DBExec).
Return
A Lua table containing the row data, with all the columns of the result table in positional order (indexes [1], [2], ... ) and also indexed by each column's name (indexes ["column_name1"], ["column_name2"], ... ). When there is no next row (the result table has reached its end) the return is nil.
Example of use
Suppose there is table named "employees" in the database, with the following format and data:

id (int)name (char 100)telephone (char 20)
1Maria222-3333
2Marcelo(NULL)
3Pedro555-3333
4William666-3333

The following commands could be used in a .lua script to retrieve data from this table:
  
  DBOpen("DATABASE=company;")  
  DBExec("SELECT telephone, name FROM employees WHERE name LIKE = 'M%'" )  
    
  row = DBRow()  
  while row do  
    write( "Name: ".. row.name .. "<br>" )   -- could be done also with "row[2]"  
    row = DBRow()  
  end  
  DBClose()  

And the result would be:

Name: Maria
Name: Marcelo

On the first cycle of the loop, the Lua table row was:
{ [1]="222-3333", [2]="Maria", ["telephone"]="222-3333", ["name"]="Maria" }
And on the second cycle:
{ [2]="Marcelo", ["name"]="Marcelo" }

The same commands could be done is a HTML template:
  
  <!--$$  
  DBOpen("DATABASE=company;")  
  DBExec("SELECT telephone, name FROM employees WHERE name LIKE = 'M%'" )  
  $$-->  
    
  <!--$$ LOOP start='row=DBRow()', test='row', action='row=DBRow()' $$-->  
    Name: $| row.name |$ <br>  
  <!--$$ ENDLOOP $$-->  
    
  <!--$$  
  DBClose()  
  $$-->  


Notes
Null values are translated to nil values in Lua, therefore care should be taken with tables that accept NULL values. In the previous example the following code could be written to avoid problems trying to write nil values:
  
  if row.telephone then  
    write( "Telephone: ".. row.telephone )      
  else  
    write( "[none]" )  
  end  


DBClose( )

Description
This function closes the active database connection, open with DBClose.
Example of use

  
  DBOpen( "DATABASE=example;" )  
  DBExec( "create table tst (nome char(50), cpf char(15))" )  
  DBClose()  


Crypt

This library provides some cryptography functionalities, such as functions for secret-key cryptography, message digest (hash) function, and RFC 822 encoding/decoding functions (useful for building MIME compliant messages, for instance).
 
Library's author(s):   [target unknown] (MD5),
Roberto Ierusalimschy (MD5),
Frederico Liporace (DES) and
Anna M. Hester (Encode, DES)
Loaded by default:   yes
 
Reference:   See above.

crypt( str, key )

Description
This function does a 56-bit DES cryptography, using the "Fast DES" algorithm as coded and proposed by Stuart Levy, Minnesota Supercomputer Center.
Parameters
str String to be encrypted. This string can be a generic binary buffer.
key (Optional) A string to be used as a seed to the internal key-generation algorithm. Only the first 8 characters are meaningful. If this parameter is not provided, a fixed internal key is used.
Return
This function returns the encrypted data, a full 8-bit buffer that can be normally held by Lua variables.
Example of use
See the following code:
  
  <!--$$  
    cpass = crypt( password )  
    epass = encode( cpass )    
  $$-->  
  The encrypted password is: $| epass |$  
  <a href="$|mkurl('ex1.html', { cryptpass=epass })|$">Ex1</a>  
  <a href="$|mkurl('ex2.html', { cryptpass=cpass })|$">Ex2</a>  

Note the use of encode before displaying the encrypted password, since 8-bit characters are not safe to be printed. For sending the encrypted password to another script, both Ex1 and Ex2 are correct, but Ex1 will produce a shorter URL, so it is recommended.


Notes
For printing the encrypted data or sending it with URLs, use the encode functions (safe 7-bit ASCII characters) and the cgilua.escape related functions (safe URL encoding).

Establishing a reasonably secure system with the use of this library requests adicional measures than simply applying this function to sensitive data. Note that if key is not used, the security of the system depends also on keeping the library itself safe from unauthorized access. If key is used, keeping the secrecy of the key seed itself is an adicional security concern, as this information is enough to decrypt the data if the "intruder" has access to the library.

Also note that 56-bit cryptography schemes are not considered safe from brute-force attacks.



decrypt( cryptbuf, key )

Description
This function decrypts a buffer, using the DES cryptography algorithm.
Parameters
cryptbuf Buffer containing the crypted data do be decrypted.
Return
The original data, decrypted.
Example of use

  
  magicword = "please"  
  box = crypt( secret, magicword )  
  this_is_the_secret = decrypt( box, magicword )  

Notes
See function crypt for further details.


docryptedfile( cryptfile )

Description
This function executes a Lua file that has been encrypted with the crypt executable utility. Lua files precompiled before being encrypted are also accepted.
Parameters
cryptfile The encrypted Lua file to be executed.

Notes
If anything wrong happens, a Lua error is issued. This function is normally used to protect source files of Web Systems, and is only useful with the executable to crypt the files. Using the function crypt to create the crypted files is not valid since the internal key for both are different. The crypt executable is provided by request. If you are interested, please contact [topic unknown].


decryptfile( cryptfile )

Description
This function decrypts an encrypted file and returns its content.
Parameters
cryptfile The file to be decrypted.
Return
The first return is the decrypted content, the second is the size in bytes of the decrypted content. Both can be normally handled by Lua variables.
Example of use

  
  htmldecrypted, size = decryptfile( "script.html" )  
  cgilua.preprocess( htmldecrypted )  

Notes
As in docryptedfile, this function is only useful with the executable to encrypt the files. A usual application is to use this function inside the preprocess module (cgilua.conf/preprocess.lua), so CGILua will only accept encrypted templates.


md5( str )

Description
This function applies the hash algorithm Message Digest 5 to the input.
Parameters
str The string to which the hash function must be applied. Generic binaries buffers are accepted.
Return
The result of the MD5 operation on the input.
Example of use

  
  signature = md5( password )  


exor( buff1, buff2 )

Description
Performs binary exclusive XOR on the buffers taken as arguments. It can be useful to build other cryptography functions with the md5 function.
Parameters
buff1 The first operand.
buff2 The second operand.
Return
The resulting binary buffer.


encode( strbuff )

Description
Performs the conversion of arbitrary 8-bit buffers to a string of 7-bit ASCII characters, as specified in RFC 822. It is traditionally used to attach binary data to eletronic messages (since SMTP gateways may refuse to accept non-ASCII messages), but is also applied in general situations in which the encoding of binary data is required.
Parameters
strbuff The binary buffer to be encoded.
Return
The resulting encoded string.
Example of use

The code above:

  
  encbuff = encode( crypt( "123456789" )  
  write( encbuff )  

Produces the following output:

uwzJJwuywCnAWQD+ynT+eQc=



decode( codedbuff )

Description
Restores a buffer encoded with the encode function.
Parameters
codedbuff The encoded buffer to be decoded.
Return
The decoded buffer.
Example of use

From the example in function encode:

  
  buff = decode( encbuff )  
  write( decrypt( buff ) )  

the resulting output is:

123456789



Cookies

Cookie is an HTTP mechanism for managing state information on the client side of the HTTP connection. This library offers some functions for cookie handling, hiding from the user some crude details of the HTTP headers format.
 
Library's author(s):   Anna M. Hester
Loaded by default:   yes
 
Reference:   See above.

getcookie( name )

Description
This function makes the server inform the value of the cookie stored in the name name, which was provided by the client (browser) when the current script was requested.
Parameters
name Name of the cookie to be retrieved.
Return
The value of the cookie requested.
Example of use
The code above:
  
  naccess = getcookie( "COUNTACCESS" )  
  if not naccess then  
    msg = "Welcome to the new user!"  
  else  
    msg = "Welcome back! You have visited our site "..  
          naccess.." times."  
  end  
  write( msg )  

produces the following output:

Welcome to the new user!


Notes


setcookie( name, value, expires, path, domain, secure )

Description
This function issues the HTTP header needed to set a cookie on the client machine.
Parameters
name The name of the cookie.
value The value of the cookie.
expires (Optional) Date when the cookie will expire, in the format day/month/4-digit year. If this parameter is not given, the cookie will be deleted when the current session is ended (e.g, the browser is closed).
path (Optional) The virtual path on the server pointed by domain (see below) that will view the cookie's value. The broader value that can be specified is "/", which means that any script on the server will have access to cookie name. The default value is the same virtual path as the script that is setting the cookie.
domain (Optional) Indicates the domain of the servers that can access the cookie's value. Partial domains are accepted, as in ".puc-rio.br". If no value is given, the default is to restrict the visibility of this cookie to the server that created it.
secure (Optional) If this parameter has the value of the string "secure", then the cookie will only be transmitted if a secure channel can be established (HTTPS).
Example of use

The code below implements a simple client-side counter:

  
  naccess = getcookie( "COUNTACCESS" )  
  if not naccess then  
   naccess = 1  
  else  
   naccess = naccess + 1  
  end  
  setcookie( "COUNTACCESS", naccess )  
    
  cgilua.htmlheader()  
  write( "<h1>Homepage</h1>" )  
  ... (code of getcookie example)  


Notes
This function must be a part of the HTTP header of the script, so it must be called before any body content is written (e.g, write with HTML code). The function can be called multiple times to set more than one cookie.

As this function must be called when the HTTP header is still being built, its use only makes sense in Lua scripts. Care should be taken to call this function *before* an HTTP header ending function is called (such as cgilua.htmlheader). To set cookie values on HTML templates, please refer to function setcookiehtml.



setcookiehtml(name,value,expires,path,domain,secure)

Description
Same as function setcookie, but useful to be called in HTML templates.
Parameters
name The name of the cookie.
value The value of the cookie.
expires (Optional) Date when the cookie will expire, in the format day/month/4-digit year. If this parameter is not given, the cookie will be deleted when the current session is ended (e.g, the browser is closed).
path (Optional) The virtual path on the server pointed by domain (see below) that will view the cookie's value. The broader value that can be specified is "/", which means that any script on the server will have access to cookie name. The default value is the same virtual path as the script that is setting the cookie.
domain (Optional) Indicates the domain of the servers that can access the cookie's value. Partial domains are accepted, as in ".puc-rio.br". If no value is given, the default is to restrict the visibility of this cookie to the server that created it.
secure (Optional) If this parameter has the value of the string "secure", then the cookie will only be transmitted if a secure channel can be established (HTTPS).
Return
Value of the Set-Cookie header needed to set the specified cookie.
Example of use

  
  <html>  
  <head>  
  <!--$$  
  naccess = getcookie( "COUNTACCESS" )  
  if not naccess then  
   naccess = 1  
  else  
   naccess = naccess + 1  
  end  
  setcookiehtml( "COUNTACCESS", naccess )  
  $$-->  
  </head>  
  <body>  
  ...  

Notes
This function must be called inside the <head> and </head> HTML tags.


deletecookie( name )

Description
Removes the cookie named name from the client machine.
Parameters
name The name of the cookie to be deleted.
Example of use

  
  deletecookie( "COUNTACCESS" )  


Loadlib

This library provides support for dynamic library loading.
 
Library's author(s):   Renato Borges
Loaded by default:   yes
 
Reference:   See above.

loadlib( libname, dir )

Description
Loads the library loadlib.
Parameters
libname The library name (without extension or special prefix) or a full path to the library. If it is a library name, dir can be used to specify the directory where the library is.
dir (Optional). The directory where the library is located.
Return
The function returns a handle to be used with the functions unloadlib and callfromlib. If the library cannot be loaded, the function returns nil as the first return and a string describing the error as a the second return.
Example of use

  
  loadlib( "/usr/lib/libX11.so" )  
  loadlib( "c:\\lua\\poslua.dll" )  
    
  -- search for libposlua.so in unix or poslua.dll in windows,   
  -- using the system default search path  
  loadlib( "poslua" )  
    
  -- search for /lua/libposlua.so in unix, /lua/poslib.dll in windows  
  loadlib( "poslua", "/lua/" )  


unloadlib( libhandle )

Description
Unloads the library whose handle is libhandle.
Parameters
libhandle The handle of the library to be unloaded. This handle is provided by the function loadlib.
Example of use

  
  testlib = loadlib( 'test' )  
    
  -- "test_open" registers the function f() in lua  
  callfromlib( testlib, 'test_open' )  
    
  x = f()  
    
  unloadlib( testlib )  
  -- unregister f()  
  f = nil  

Notes
The Lua functions eventually registered by the library are not automatically removed.


callfromlib( libhandle, funcname )

Description
Call the function funcname from the library whose handle is libhandle.
Parameters
libhandle The handle of the library to be unloaded. This handle is provided by the function loadlib.
funcname The name (string) of an exported function from the library to be called.
Example of use

  
  datelib, errmsg = loadlib( 'date' )  
  if datelib then  
    callfromlib( datelib, 'date_open' )  
  else  
    error( errmsg )  
  end  

Notes
Typically, you use callfromlib only once, after loadlib, to call an "open" function that will register the library functions in the Lua environment.


Mail

Allows a message to be sent via an SMTP mail server.
 
Library's author(s):   Anna Hester
Loaded by default:   yes
 
Reference:   See above.

mail{ to=tolist, from=frm, subject=sbj, message=msg, cc=cclist, bcc=bcclist }

Description
Sends a message to the recipients listed in to.
Parameters
to A comma-separated list of the emails of the recipients of the message.
from The email of the sender.
subject (Optional). The subject of the message.
message (Optional). The body of the message.
cc (Optional). A comma-separated list of the emails of the recipients "carbon-copy" of the message.
bcc (Optional). A comma-separated list of the emails of the recipients "blind carbon-copy" of the message.
mailserver (On Windows systems). The IP of the SMTP server to be used.
Return
Returns a non-nil value (1) if the message was successfully sent or nil if an error occurred, with the second return being a string describing the error.
Example of use

  
  msg = "This is a simple message"  
  ok, errmsg = mail{ mailserver="127.0.0.1", to="cgilua@tecgraf.puc-rio.br",   
                     from="user@hotmail.com", subject="Mail test", message=msg }  
    
  cgilua.htmlheader()  
  if not ok then  
    write( "Message could not be sent. Reason: ".. errmsg )  
  else  
    write( "Message sent!" )  
  end  

Notes
On Windows systems, is mandatory to specify the field "mailserver". It is possible to set this value globally to all scripts defining the Lua global variable MAILSERVER. On Unix systems, please verify if the path to the sendmail executable is correct (file cgilua.conf/mail.lua).


Htmltoolkit

Library of HTML "classes" that allows HTML tags to be built using operations on Lua objects (and not Lua strings).
 
Library's author(s):   Anna Hester
Loaded by default:   no
 
Reference:   See the homepage and the source code (included in CGILua's distribution).

Htk

HTK is a library of Lua constructors to create HTML forms elements. HTK is based on the Htmltoolkit.
 
Library's author(s):   Tomás Guisasola Gorham
Loaded by default:   no
 
Reference:   See the homepage and the source code (included in CGILua's distribution).



Last update in 24/05/1999