GLUEscript - The manual - 0.1.07 Glueing Libraries Using EcmaScript Franky Braem GLUEscript - The manual - 0.1.07: Glueing Libraries Using EcmaScript Franky Braem

Publication date Copyright © 2002 - 2011 Franky Braem Table of Contents

1. Introduction ...... 1 What's GLUEscript? ...... 1 History ...... 1 Glue ...... 1 Configuration ...... 1 glue.runtimeSize ...... 2 glue.contextSize ...... 2 glue.contextPoolSize ...... 2 2. Building GLUE ...... 3 Prerequisites ...... 3 Premake ...... 3 POCO ...... 3 wxWidgets ...... 3 Linux ...... 3 NSPR ...... 3 Premake ...... 3 PocoJavaScript ...... 4 GLUEscript ...... 4 Install ...... 5 glue.properties ...... 6 3. Apache ...... 7 Introduction ...... 7 Configure Apache ...... 7 4. core ...... 8 Introduction ...... 8 Reference ...... 8 5. curl ...... 13 Introduction ...... 13 Setting Options ...... 13 curl.Auth ...... 15 curl.Easy ...... 16 curl.Form ...... 36 curl.FTPAuth ...... 37 curl.FTPMethod ...... 38 curl.FTPSSL ...... 39 curl.Http ...... 40 curl.Info ...... 41 curl.IPResolve ...... 43 curl.Multi ...... 44 Curl ...... 45 curl.Netrc ...... 46 curl.Option ...... 47 curl.Protocol ...... 51 curl.ProxyType ...... 52 curl.SSHAuth ...... 53 curl.SSLVersion ...... 54 curl.UseSSL ...... 55 6. Data ...... 56 Introduction ...... 56 Reference ...... 56 7. expat ...... 62

iii GLUEscript - The manual - 0.1.07

Introduction ...... 62 Reference ...... 62 8. fcgi ...... 67 Introduction ...... 67 Example ...... 67 Class Reference ...... 67 9. gd ...... 69 Introduction ...... 69 Examples ...... 69 Drawing a pixel ...... 69 Drawing a line ...... 69 Drawing a dashed line ...... 70 Drawing a triangle ...... 71 Drawing a rectangle ...... 71 Drawing a filled polygon ...... 72 Drawing a partial ellipse ...... 72 Drawing a filled partial ellipse ...... 73 Alpha Blending ...... 73 Reference ...... 74 10. memcache ...... 101 Introduction ...... 101 memcached in JavaScript ...... 101 Reference ...... 101 11. mysql ...... 105 Introduction ...... 105 Database ...... 105 Executing SQL statements ...... 105 Class Reference ...... 105 12. net ...... 122 Introduction ...... 122 Handling Form Input ...... 122 Naming the elements ...... 122 Uploading files ...... 123 Class Reference ...... 124 13. sqlite ...... 182 Introduction ...... 182 Database ...... 182 Executing SQL statements ...... 182 Class Reference ...... 182 14. system ...... 191 Introduction ...... 191 Reference ...... 191 15. tpl ...... 217 Introduction ...... 217 Template files ...... 217 A template example ...... 217 Class Reference ...... 218 16. wx ...... 221 Introduction ...... 221 wxTheApp ...... 221 Event Handling ...... 221 Class Reference ...... 222 Index ...... 583

iv List of Tables

5.1. Constants of curl.Auth ...... 15 5.2. Constants of curl.FTPAuth ...... 37 5.3. Constants of curl.FTPMethod ...... 38 5.4. Constants of curl.FTPSSL ...... 39 5.5. Constants of curl.Http ...... 40 5.6. Constants of curl.Info ...... 41 5.7. Constants of curl.IPResolve ...... 43 5.8. Constants of curl.Netrc ...... 46 5.9. Constants of curl.Option ...... 47 5.10. Constants of curl.Protocol ...... 51 5.11. Constants of curl.ProxyType ...... 52 5.12. Constants of curl.SSHAuth ...... 53 5.13. Constants of curl.SSLVersion ...... 54 5.14. Constants of curl.UseSSL ...... 55 7.1. Constants of expat.Parser ...... 63 10.1. Constants of memcache.Client ...... 102 11.1. Constants of mysql.Database ...... 106 12.1. Constants of net.Family ...... 129 12.2. Constants of net.HTTPResponse ...... 141 12.3. Constants of net.MailRecipient ...... 154 13.1. Constants of sqlite.Database ...... 183 14.1. Constants of system.InputStream ...... 198 14.2. Constants of system.OutputStream ...... 200 14.3. Constants of system.Path ...... 202 16.1. Constants of wx.AcceleratorEntry ...... 226 16.2. Constants of wx.Alignment ...... 231 16.3. Constants of wx.Animation ...... 232 16.4. Constants of wx.AnimationCtrl ...... 234 16.5. Constants of wx.AuiManagerDock ...... 241 16.6. Constants of wx.AuiManagerOption ...... 242 16.7. Constants of wx.AuiNotebook ...... 243 16.8. Constants of wx.AuiPaneInsertLevel ...... 255 16.9. Constants of wx.BitmapType ...... 263 16.10. Constants of wx.BookCtrlBase ...... 265 16.11. Constants of wx.BookHittest ...... 271 16.12. Constants of wx.Border ...... 272 16.13. Constants of wx.Button ...... 274 16.14. Constants of wx.CalendarCtrl ...... 277 16.15. Constants of wx.CalendarDateBorder ...... 283 16.16. Constants of wx.CheckBox ...... 287 16.17. Constants of wx.CheckBoxState ...... 290 16.18. Constants of wx.Choicebook ...... 294 16.19. Constants of wx.CollapsiblePane ...... 299 16.20. Constants of wx.ColourPickerCtrl ...... 307 16.21. Constants of wx.ComboBox ...... 310 16.22. Constants of wx.Dialog ...... 322 16.23. Constants of wx.Direction ...... 326 16.24. Constants of wx.FileDialog ...... 328 16.25. Constants of wx.Filter ...... 330 16.26. Constants of wx.FindReplaceData ...... 332 16.27. Constants of wx.FindReplaceDialog ...... 333

v GLUEscript - The manual - 0.1.07

16.28. Constants of wx.Font ...... 337 16.29. Constants of wx.FontEncoding ...... 342 16.30. Constants of wx.Frame ...... 347 16.31. Constants of wx.FullScreen ...... 350 16.32. Constants of wx.Gauge ...... 351 16.33. Constants of wx.HtmlWindow ...... 359 16.34. Constants of wx.Id ...... 366 16.35. Constants of wx.ItemKind ...... 380 16.36. Constants of wx.KeyCode ...... 383 16.37. Constants of wx.LayoutAlignment ...... 390 16.38. Constants of wx.LayoutOrientation ...... 391 16.39. Constants of wx.ListAlign ...... 392 16.40. Constants of wx.Listbook ...... 393 16.41. Constants of wx.ListBox ...... 396 16.42. Constants of wx.ListColumnFormat ...... 398 16.43. Constants of wx.ListCtrl ...... 402 16.44. Constants of wx.ListFind ...... 414 16.45. Constants of wx.ListMask ...... 419 16.46. Constants of wx.ListNext ...... 420 16.47. Constants of wx.ListRect ...... 421 16.48. Constants of wx.ListState ...... 422 16.49. Constants of wx.MenuBar ...... 428 16.50. Constants of wx.Menu ...... 432 16.51. Constants of global ...... 446 16.52. Constants of wx.Notebook ...... 447 16.53. Constants of wx.NotebookHittest ...... 450 16.54. Constants of wx.Orientation ...... 452 16.55. Constants of wx.PickerBase ...... 456 16.56. Constants of wx.RadioBox ...... 461 16.57. Constants of wx.RadioButton ...... 465 16.58. Constants of wx.SashDragStatus ...... 469 16.59. Constants of wx.SashEdgePosition ...... 470 16.60. Constants of wx.SashWindow ...... 474 16.61. Constants of wx.Slider ...... 499 16.62. Constants of wx.SpinButton ...... 503 16.63. Constants of wx.SpinCtrl ...... 505 16.64. Constants of wx.SplitMode ...... 508 16.65. Constants of wx.SplitterWindow ...... 510 16.66. Constants of wx.StaticText ...... 516 16.67. Constants of wx.StatusBar ...... 518 16.68. Constants of wx.Stretch ...... 521 16.69. Constants of wx.SystemSettings ...... 523 16.70. Constants of wx.TextCtrl ...... 527 16.71. Constants of wx.ToolBar ...... 536 16.72. Constants of wx.TreeCtrl ...... 550 16.73. Constants of wx.TreeItemIcon ...... 567 16.74. Constants of wx.Window ...... 570

vi Chapter 1. Introduction What's GLUEscript?

GLUE stands for Glueing Libraries Using EcmaScript. With GLUEscript, EcmaScript (better known as JavaScript) can be used as a general purpose language. It allows you to write desktop applications, dynamic web pages, system scripts ... with JavaScript.

GLUEscript uses SpiderMonkey, the JavaScript engine used in FireFox.

The interpreter can be run as a console program, a FastCGI program or as an Apache module. History

GLUEscript is the successor of wxJavaScript. wxJavaScript was a port of wxWidgets, a portable GUI framework. But wxJavaScript wasn't only wxWidgets. It also ported MySQL, SQLite, memcached, cURL, ... After several years of developing wxJavaScript, it was decided to create an interpreter which didn't depend on wxWidgets. Instead of wxWidgets, the POCO framework is used for writing portable ++ code. You can still write GUI applications with the wxWidgets ported classes, but for system scripts, dynamic webpages, ... which don't need wxWidgets, you can run GLUEscript without the wxWidgets binaries. Glue

A port of a C/C++ library is called a "glue". A glue is a dynamic linked library which ports the C/C++ library to JavaScript. The following glues are available in GLUEscript:

• curl

• expat

• gd

• memcached

• mysql

• net

• system

• sqlite

• wx Configuration

GLUEscript is configured using a property file. GLUEscript will search for a file with the name glue.properties in the application directory. For the console application this directory is the directory where the executable is stored. For the Apache environment this is the file specified with AddPocoConfig in httpd.conf.

1 Introduction

The configuration of the console application, FastCGI program and Apache can be done in the same property file. A property for the console program starts with glue.console. For FastCGI glue.fcgi is used and for Apache the name of the host is used: glue.localhost. When a property is valid for all programs, only glue. is used. An example:

glue.runtimeSize = 1M glue.localhost.runtimeSize = 2M

In this example the runtime size will be 1 MB. Except for Apache, where 2 MB will be used for localhost.

glue.modules.URI is the only property that can't be overruled by Apache, FCGI, ... glue.runtimeSize

Defines the maximum number of allocated bytes after which garbage collection is run. You can use the suffix M for MB and K for KB. glue.contextSize

Defines the size, in bytes, of each "stack chunk". This is a memory management tuning parameter which most users should not adjust. 8192 is a good default value. You can use the suffix M for MB and K for KB. glue.contextPoolSize

Contexts are pooled. This parameter defines the size of the pool. glue.modules.URI

A URI where the dynamic libraries are stored. When this is not set the folder 'modules' is searched in the application directory (where glue.exe is)

2 Chapter 2. Building GLUE Prerequisites

Before you can start building GLUEscript, you need to follow some steps. Premake

GLUEscript uses Premake [http://industriousone.com/premake] for generating files. Premake uses LUA-scripts for generating these files. Installing Premake is easy. Just get the right executable (version 4.2) for your operating system. POCO

The POCO [http://poco.appinf.com/] library is used for writing portable C++ code. So download the POCO library and install it. Build POCO as shared libraries. When you want to build POCO on Windows with MinGW then you can download some Premake scripts from here [http://gluescript.svn.sourceforge.net/ viewvc/gluescript/src/poco.zip] to build it with CodeLite or Code::Blocks. wxWidgets

When you want to use the GUI classes you need to build wxWidgets. You can get more information about it on their website [http://www.wxwidgets.org]. Linux NSPR

To build GLUEscript on Linux, a prebuild NSPR library is needed. Get the latest version from NSPR [http://www.mozilla.org/projects/nspr] and install NSPR. Premake

Open a terminal and move to the source folder of GLUEscript and run premake. When you also want to compile/build the WX glue, specify --with-wx as first argument to premake4. For example:

bronx@ubuntu:~$ cd dev* bronx@ubuntu:~/development$ cd glue* bronx@ubuntu:~/development/gluescript$ cd src bronx@ubuntu:~/development/gluescript/src$ premake4 --with-wx gmake

When everythings goes right, you should see something like this:

Poco Include Directory: /usr/local/include Poco Library Directory: /usr/local/lib NSPR Include Directory: /usr/local/include/nspr

3 Building GLUE

NSPR Library Directory: /usr/local/lib Using the zlib library which is part of GLUEscript Using the png library which is part of GLUEscript Using the jpg library which is part of GLUEscript Building configurations... Running action 'gmake'... Generating ../build/gmake/PocoJavaScript.make... Generating ../build/gmake/ApacheConnector.make... Generating ../build/gmake/Script.make... Generating ../build/gmake/SpiderMonkey.make... Generating ../build/gmake/GLUE.make... Generating ../build/gmake/zlib.make... Generating ../build/gmake/png.make... Generating ../build/gmake/jpg.make... Generating ../build/gmake/Common.make... Generating ../build/gmake/Core.make... Generating ../build/gmake/glue.make... Generating ../build/gmake/Data.make... Generating ../build/gmake/Expat.make... Generating ../build/gmake/SQLite.make... Generating ../build/gmake/Tpl.make... Generating ../build/gmake/MySQL.make... Generating ../build/gmake/GD.make... Generating ../build/gmake/MemCached.make... Generating ../build/gmake/Curl.make... Generating ../build/gmake/FCGI.make... Generating ../build/gmake/Net.make... Generating ../build/gmake/System.make... Generating ../build/gmake/WX.make... Generating ../build/gmake/Apache.make... Done.

The action gmake will generate common makefiles. With premake it's also possible to generate workspaces for Codelite and Code::Blocks. All makefiles will be generated in the build folder. For each different action of premake you find a folder. For example, You can find the common makefiles in the gmake folder. PocoJavaScript

The Poco JavaScript framework, which is donated by GLUEscript to Poco, must be build before you can start building GLUEscript. PocoJavaScript also contains the Poco Script framework and the Poco Apache Connector. The following is an example on building this framework in release mode on a 64-bit operating system (Ubuntu).

make -f PocoJavaScript.make config=release64

GLUEscript Now it's possible to build GLUEscript:

make -f GLUEscript.make config=release64

4 Building GLUE

Install

At the moment there's no install script. By default the glue program searches for modules in the 'modules' subdirectory of the program. So move them to this directory. You also have to remove the 'lib' prefix. Make it look like this:

drwxr-xr-x 4 bronx bronx 4096 2010-05-04 19:03 .. -rwxr-xr-x 1 bronx bronx 165840 2010-05-04 20:38 libmod_poco.so -rwxr-xr-x 1 bronx bronx 51992 2010-05-04 20:38 libPocoScript.so -rwxr-xr-x 1 bronx bronx 2078752 2010-05-04 20:41 libPocoSpiderMonkey.so -rwxr-xr-x 1 bronx bronx 139288 2010-05-04 21:01 glue -rwxr-xr-x 1 bronx bronx 402944 2010-05-04 21:57 libglue_data.so -rwxr-xr-x 1 bronx bronx 228616 2010-05-05 22:16 libglue_apache.so -rwxr-xr-x 1 bronx bronx 218112 2010-05-06 19:03 glue_fcgi drwxr-xr-x 3 bronx bronx 4096 2010-05-06 21:05 . drwxr-xr-x 2 bronx bronx 4096 2010-05-06 21:06 modules bronx@ubuntu:~/development/gluescript/bin/Release$ cd modules bronx@ubuntu:~/development/gluescript/bin/Release/modules$ ls -lart total 15416 -rwxr-xr-x 1 bronx bronx 591752 2010-05-04 21:26 glue_core.so -rwxr-xr-x 1 bronx bronx 529232 2010-05-04 21:57 glue_expat.so -rwxr-xr-x 1 bronx bronx 1049472 2010-05-04 21:57 glue_sqlite.so -rwxr-xr-x 1 bronx bronx 720032 2010-05-04 21:58 glue_mysql.so -rwxr-xr-x 1 bronx bronx 262136 2010-05-04 22:15 glue_tpl.so -rwxr-xr-x 1 bronx bronx 2150184 2010-05-04 22:15 glue_gd.so -rwxr-xr-x 1 bronx bronx 395152 2010-05-04 22:19 glue_memcache.so -rwxr-xr-x 1 bronx bronx 1034360 2010-05-04 22:54 glue_system.so -rwxr-xr-x 1 bronx bronx 921280 2010-05-05 21:24 glue_net.so -rwxr-xr-x 1 bronx bronx 7402224 2010-05-05 22:16 glue_wx.so -rwxr-xr-x 1 bronx bronx 649432 2010-05-06 19:05 glue_curl.so drwxr-xr-x 3 bronx bronx 4096 2010-05-06 21:05 .. drwxr-xr-x 2 bronx bronx 4096 2010-05-06 21:06 .

When you run glue, you problably see this error:

bronx@ubuntu:~/development/gluescript/bin/Release$ ./glue ./glue: error while loading shared libraries: libPocoSpiderMonkey.so: cannot open shared object file: No such file or directory

Fixing this problem is easy. Simply add the directory to your /etc/ld.so.conf file, and then -- as root -- run the ldconfig program so it rebuilds /etc/ld.so.cache.

Now run glue:

glue runs in interactive mode. Each line will be executed. Enter an empty line to end glue. > print("Hello World\n"); Hello World >

5 Building GLUE

glue.properties

glue.properties is a file that configures GLUEscript. Use it to define which modules must be loaded. An example:

glue.uri=file:///c:/development/gluescript/bin/release/modules glue.modules.core=${glue.uri}/glue_core.dll glue.modules.wx=${glue.uri}/glue_wx.dll glue.modules.system=${glue.uri}/glue_system.dll glue.modules.net=${glue.uri}/glue_net.dll glue.modules.curl=${glue.uri}/glue_curl.dll glue.modules.memcache=${glue.uri}/glue_memcache.dll glue.modules.sqlite=${glue.uri}/glue_sqlite.dll glue.modules.mysql=${glue.uri}/glue_mysql.dll glue.modules.tpl=${glue.uri}/glue_tpl.dll glue.modules.expat=${glue.uri}/glue_expat.dll glue.modules.gd=${glue.uri}/glue_gd.dll

Note The core module is important! Without it GLUEscript can't load other modules.

6 Chapter 3. Apache Introduction

GLUEscript can be used to create dynamic webpages with Apache. Configure Apache

Internally GLUEscript uses the ApacheConnector of the POCO framework. To run JavaScript you need to use the POCO configuration tags. This is an example:

LoadModule poco_module c:/GLUEscript/bin/mod_pocod.dll AddPocoRequestHandler GLUERequestHandlerFactory c:/GLUEscript/bin/glue_apache.dll /hello AddPocoRequestHandler GLUERequestHandlerFactory c:/GLUEscript/bin/glue_apache.dll /book AddPocoConfig c:/GLUEscript/glue.properties

This example will redirect all URI's that start with hello and book to GLUEscript. GLUEscript is configured in the glue.properties file. In this file you need to attach a script for each request handler.

glue.localhost.controller.hello = c:/GLUEscript/samples/apache/echo.js glue.localhost.controller.book = c:/GLUEscript/samples/apache/book.js

When a script is called, a request and response object is automatically available. request is a net.HTTPServerRequest and response is a net.HTTPServerResponse.

7 Chapter 4. core Introduction

The core glue contains classes that are used by several glues. It defines classes like Binary, BinaryString, Encoding, ... This glue is always loaded automatically by the GLUEscript engine. Reference

8 core

Name core.Binary — Prototype for Binary classes

Properties length

Integer length ;

Returns the length of the Binary Methods concat

core.BinaryString concat(core.Binary Buffer);

core.BinaryString concat(Array Buffer);

core.BinaryString concat(Integer Buffer);

Returns a new binary comprised of this binary joined with other binary, array or integer value(s). Multiple arguments can be specified. byteAt

core.BinaryString byteAt(Integer Offset);

Return the byte at offset as a core.BinaryString decodeToString

String decodeToString(String Encoding);

Converts the binary into a String with the given encoding get

Integer get(Integer Offset);

Return the byte as Integer

9 core

Name core.BinaryString

Constructor

BinaryString(String Str, String Encoding= UTF-8);

BinaryString(core.Binary Buffer);

BinaryString(Array Arr);

BinaryString();

Constructs a new BinaryString class

10 core

Name core.Encoding — class for text encodings like UTF-8 or ISO 8859-1.

All the available encodings are defined as class properties. Retrieve as follows:

Encoding["UTF-16-BE"]

The following encodings are available: ASCII, ISO-8859-1, ISO-8859-15, UTF-8, UTF-16, UTF-16-LE, UTF-16-BE and CP1252.

11 core

Name core.Version — Represents a version number

Properties major

Integer major ;

Returns the major number minor

Integer minor ;

Returns the minor number release

Integer release ;

Returns the release number description

String description ;

Returns the description

12 Chapter 5. curl Introduction

The curl glue ports cURL [http://curl.haxx.se] to JavaScript. libcurl is a free and easy-to-use client-side URL transfer library, supporting FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS and FILE. libcurl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, Kerberos4), file transfer resume, http proxy tunneling and more! Warning

When you use the prebuild cURL from the binary distribution of GLUEscript on Windows you need to install OpenSSL. Download the OpenSSL binaries from Shining Light Productions [http://www.slproweb.com/products/Win32OpenSSL.html]. Setting Options

There are 3 ways in JavaScript to set cURL options. Use setopt

With setopt options are set as in the C/C++ version. All available options are defined as constants in curl.Option.

var curl = require("curl"); var c = new curl.Easy(); c.setopt(curl.Option.VERBOSE, true); c.setopt(curl.Option.URL, "http://gluescript.sf.net");

Use setopt with an object

An object can be used. Use the constants as array index for the option. This can be handy, when you want to use a separate script for setting the options (a configuration script for example) or to store the options in JSON format.

var curl = require("curl"); var options = new Object(); options[curl.Option.VERBOSE] = true; options[curl.Option.URL] = "http://gluescript.sf.net";

var c = new curl.Easy(); c.setopt(options);

13 curl

Use properties

All options are also properties of curl.Easy.

var curl = require("curl"); var c = new curl.Easy(); c.url = "http://gluescript.sf.net"; c.verbose = true;

14 curl

Name curl.Auth — Defines constants for httpAuth

This class defines constants for setting the property httpAuth Constants

Table 5.1. Constants of curl.Auth

Name Description ANY ANYSAFE BASIC DIGEST GSSNEGOTIATE NTLM

15 curl

Name curl.Easy — The easy interface

Use this class to create a libcurl easy session. Class Methods strerror

String strerror(Integer Code);

Return string describing error code Constructor

Easy();

This creates a new libcurl easy session. It is automatically cleaned up. Properties append

Boolean append ;

Tells the library to append to the remote file instead of overwrite it. This is only useful when uploading to an ftp site. autoReferer

Boolean autoReferer ;

Set to true to enable this. When enabled, libcurl will automatically set the Referer: field in requests where it follows a Location: redirect. cookie

String cookie ;

It will be used to set a cookie in the http request. The format of the string should be NAME=CONTENTS, where NAME is the cookie name and CONTENTS is what the cookie should contain.

If you need to set multiple cookies, you need to set them all using a single option and thus you need to concatenate them all in one single string. Set multiple cookies in one string like this: "name1=content1; name2=content2;" etc.

16 curl cookieFile

String cookieFile ;

The name of a file holding cookie data to read. The cookie data may be in Netscape / Mozilla cookie data format or just regular HTTP-style headers dumped to a file.

Given an empty or non-existing file or by passing the empty string, this option will enable cookies for this curl handle, making it understand and parse received cookies and then use matching cookies in future request.

If you set this property multiple times, you just add more files to read. Subsequent files will add more cookies. cookieJar

String cookieJar ;

This will make curl write all internally known cookies to the specified file when curl is destroyed. If no cookies are known, no file will be created. Specify "-" to instead have the cookies written to stdout. Using this option also enables cookies for this session, so if you for example follow a location it will make matching cookies get sent accordingly. cookieList

String cookieList ;

Cookie can be either in Netscape / Mozilla format or just regular HTTP-style header (Set-Cookie: ...) format. If cURL cookie engine was not enabled it will enable its cookie engine. Passing a magic string "ALL" will erase all cookies known by cURL. (Added in 7.14.1) Passing the special string "SESS" will only erase all session cookies known by cURL. (Added in 7.15.4) Passing the special string "FLUSH" will write all cookies known by cURL to the file specified by cookieJar. cookieSession

Boolean cookieSession ;

It will force libcurl to ignore all cookies it is about to load that are "session cookies" from the previous session. By default, libcurl always stores and loads all cookies, independent if they are session cookies are not. Session cookies are cookies without expiry date and they are meant to be alive and existing for this "session" only. crlf

Boolean crlf ;

Convert Unix newlines to CRLF newlines on transfers. customRequest

17 curl

String customRequest ;

This will be used instead of GET or HEAD when doing an HTTP request, or instead of LIST or NLST when doing an ftp directory listing. This is useful for doing DELETE or other more or less obscure HTTP requests. Don't do this at will, make sure your server supports the command first. dirListOnly

Boolean dirListOnly ;

A true value tells the library to just list the names of files in a directory, instead of doing a full directory listing that would include file sizes, dates etc. This works for FTP and SFTP URLs. dnsCacheTimeout

Integer dnsCacheTimeout ;

This sets the timeout in seconds. Name resolves will be kept in memory for this number of seconds. Set to zero (0) to completely disable caching, or set to -1 to make the cached entries remain forever. By default, libcurl caches this info for 60 seconds. This is the same as calling setopt with Option.DNS_CACHE_TIMEOUT. effectiveUrl

String effectiveUrl ;

Returns the last used effective URL. encoding

String encoding ;

Sets the contents of the Accept-Encoding: header sent in an HTTP request. error

String error ;

Returns the last error as a String filetime

Boolean filetime ;

When true, libcurl will attempt to get the modification date of the remote document in this operation. followLocation

Boolean followLocation ;

18 curl

True tells the library to follow any Location: header that the server sends as part of an HTTP header. ftpAccount

String ftpAccount ;

When an FTP server asks for "account data" after user name and password has been provided, this data is sent off using the ACCT command. ftpAlternativeToUser

String ftpAlternativeToUser ;

A string which will be used to authenticate if the usual FTP "USER user" and "PASS password" negotiation fails ftpCreateMissingDirs

Boolean ftpCreateMissingDirs ;

curl will attempt to create any remote directory that it fails to CWD into. CWD is the command that changes working directory. ftpFileMethod

Integer ftpFileMethod ;

This option controls what method libcurl should use to reach a file on a FTP(S) server. See curl.FTPMethod. ftpPort

String ftpPort ;

This will be used to get the IP address to use for the ftp PORT instruction. The PORT instruction tells the remote server to connect to our specified IP address. The string may be a plain IP address, a host name, an network interface name (under Unix) or just a '-' letter to let the library use your systems default IP address. Default FTP operations are passive, and thus won't use PORT. ftpResponseTimeout

Integer ftpResponseTimeout ;

Causes curl to set a timeout period (in seconds) on the amount of time that the server is allowed to take in order to generate a response message for a command before the session is considered hung. ftpSkipPasvIp

19 curl

Boolean ftpSkipPasvIp ;

If set to a true value, it instructs libcurl to not use the IP address the server suggests in its 227-response to libcurl's PASV command when libcurl connects the data connection. Instead libcurl will re-use the same IP address it already uses for the control connection. But it will use the port number from the 227-response. ftpSSLAuth

Integer ftpSSLAuth ;

See curl.FTPAuth ftpSSLCCC

Integer ftpSSLCCC ;

See curl.FTPSSL. If enabled, this option makes libcurl use CCC (Clear Command Channel). It shuts down the SSL/TLS layer after authenticating. The rest of the control channel communication will be unencrypted. This allows NAT routers to follow the FTP transaction. ftpUseEPRT

Boolean ftpUseEPRT ;

Tells curl to use the EPRT (and LPRT) command when doing active FTP downloads. ftpUseEPSV

Boolean ftpUseEPSV ;

Tells curl to use the EPSV command when doing passive FTP downloads. header

Boolean header ;

Set this to true tells the library to include the header in the body output. This is the same as calling setopt with Option.HEADER when set. http200Aliases

Array http200Aliases ;

Pass an array with aliases to be treated as valid HTTP 200 responses. Some servers respond with a custom header response line. For example, IceCast servers respond with "ICY 200 OK". By including this string in your list of aliases, the response will be treated as a valid HTTP header line such as "HTTP/1.0 200 OK". httpAuth

20 curl

Integer httpAuth ;

Tell libcurl what authentication method(s) to use. See curl.Auth HttpContentDecoding

Boolean HttpContentDecoding ;

If set to false, content decoding will be disabled. If set to true it is enabled. Note however that libcurl has no default content decoding but requires you to use encoding for that. httpGet

Boolean httpGet ;

When true, this forces the HTTP request to get back to GET. usable if a POST, HEAD, PUT or a custom request have been used previously using the same curl handle.

When setting httpGet to true, it will automatically set noBody. httpVersion

Integer httpVersion ;

This forces libcurl to use the specific HTTP versions. This is not sensible to do unless you have a good reason. See curl.Http httpHeader

Array httpHeader ;

An array with String elements which are HTTP headers to pass to the server in your HTTP request. If you add a header that is otherwise generated and used by libcurl internally, your added one will be used instead. If you add a header with no contents as in 'Accept:' (no data on the right side of the colon), the internally used header will get disabled. Thus, using this option you can add new headers, replace internal headers and remove internal headers. To add a header with no contents, make the contents be two quotes: "". The headers included in the array must not be CRLF-terminated, because curl adds CRLF after each header item. Failure to comply with this will result in strange bugs because the server will most likely ignore part of the headers you specified. httpPost

curl.Form httpPost ;

A multipart/formdata HTTP POST. httpProxyTunnel

Boolean httpProxyTunnel ;

21 curl

Set the parameter to true to get the library to tunnel all operations through a given HTTP proxy. This is the same as calling setopt with Option.HTTPPROXYTUNNEL. httpTransferDecoding

Boolean httpTransferDecoding ;

If set to false, transfer decoding will be disabled, if set to true it is enabled (default). libcurl does chunked transfer decoding by default unless this option is set to zero. ignoreContentLength

Boolean ignoreContentLength ;

Ignore the Content-Length header. This is useful for Apache 1.x (and similar servers) which will report incorrect content length for files over 2 gigabytes. If this option is used, curl will not be able to accurately report progress, and will simply stop the download when the server ends the connection. inFileSize

Integer inFileSize ;

When uploading a file to a remote site, this option should be used to tell libcurl what the expected size of the infile is. interface

String interface ;

This sets the interface name to use as outgoing network interface. The name can be an interface name, an IP address or a host name. This is the same as calling setopt with Option.INTERFACE. localPort

Integer localPort ;

This sets the local port number of the socket used for connection. This is the same as calling setopt with Option.LOCALPORT. localPortRange

Integer localPortRange ;

This is the number of attempts libcurl should do to find a working local port number. It starts with the given localPort and adds one to the number for each retry. Setting this value to 1 or below will make libcurl do only one try for exact port number. Note that port numbers by nature is a scarce resource that will be busy at times so setting this value to something too low might cause unnecessary connection setup failures. This is the same as calling setopt with Option.LOCALPORTRANGE.

22 curl maxFileSize

Integer maxFileSize ;

This allows you to specify the maximum size (in bytes) of a file to download. If the file requested is larger than this value, the transfer will not start and Error.FILESIZE_EXCEEDED will be returned. maxRedirs

Integer maxRedirs ;

The redirection limit. netrc

Integer netrc ;

This parameter controls the preference of libcurl between using user names and passwords from your ~/.netrc file, relative to user names and passwords in the URL supplied with url. See netrc for values. netrcFile

String netrcFile ;

Contains the full path name to the file you want libcurl to use as .netrc file. If this option is omitted, and netrc is set, libcurl will attempt to find the a .netrc file in the current user's home directory. noBody

Boolean noBody ;

Tells the library to not include the body-part in the output. noProgress

Boolean noProgress ;

Set this to true tells the library to shut off the built-in progress meter completely. This is the same as calling setopt with Option.NOPROGRESS when set. port

Integer port ;

Set the remote port number to connect to, instead of the one specified in the URL or the default port for the used protocol. This is the same as calling setopt with Option.PORT.

23 curl post

Boolean post ;

Tells the library to do a regular HTTP post. postFields

core.Binary postFields ;

A buffer with the full data to post in an HTTP POST operation. Make sure that the data is formatted the way you want the server to receive it. libcurl will not convert or encode it for you. Most web servers will assume this data to be url-encoded. The buffer is not copied by the library: as a consequence, they must be preserved by the calling application until the transfer finishes. postQuote

Array postQuote ;

An array with FTP or SFTP commands to pass to the server after your ftp transfer request. preQuote

Array preQuote ;

An array with FTP commands to pass to the server after the transfer type is set. protocols

Integer protocols ;

Pass a long that holds a bitmask of curl.Protocol constants. If used, this bitmask limits what protocols libcurl may use in the transfer. This allows you to have a libcurl built to support a wide range of protocols but still limit specific transfers to only be allowed to use a subset of them. By default libcurl will accept all protocols it supports. See also redirProtocols. proxy

String proxy ;

Set HTTP proxy to use. This is the same as calling setopt with Option.PROXY. proxyAuth

Integer proxyAuth ;

Tells libcurl what authentication method(s) to use for the proxy authentication.

24 curl proxyPort

Integer proxyPort ;

Set the proxy port to connect to unless it is specified in the proxy string. This is the same as calling setopt with Option.PROXYPORT. proxyUserPwd

String proxyUserPwd ; quote

Array quote ;

An array with FTP or SFTP commands to pass to the server prior to your ftp request. This will be done before any other commands are issued (even before the CWD command for FTP). range

String range ;

A property which should contain the specified range you want. It should be in the format "X-Y", where X or Y may be left out. HTTP transfers also support several intervals, separated with commas as in "X-Y,N- M". Using this kind of multiple intervals will cause the HTTP server to send the response document in pieces (using standard MIME separation techniques). Pass a null to this option to disable the use of ranges. redirProtocols

Integer redirProtocols ;

Pass a long that holds a bitmask of curl.Protocol constants. If used, this bitmask limits what protocols libcurl may use in a transfer that it follows to in a redirect when followLocation is enabled. This allows you to limit specific transfers to only be allowed to use a subset of protocols in redirections. By default libcurl will allow all protocols except for FILE and SCP. referer

String referer ;

This will be used to set the Referer: header in the http request sent to the remote server. This can be used to fool servers or scripts. resumeFrom

Integer resumeFrom ;

25 curl

It contains the offset in number of bytes that you want the transfer to start from. Set this option to 0 to make the transfer start from the beginning (effectively disabling resume). For FTP, set this option to -1 to make the transfer start from the end of the target file (useful to continue an interrupted upload). tcpNoDelay

Boolean tcpNoDelay ;

Setting this option to true will disable TCP's Nagle algorithm. The purpose of this algorithm is to try to minimize the number of small packets on the network (where "small packets" means TCP segments less than the Maximum Segment Size (MSS) for the network). This is the same as calling setopt with Option.TCP_NODELAY timeCondition

Integer timeCondition ; timeout

Integer timeout ;

The maximum time in seconds that you allow the libcurl transfer operation to take. Normally, name lookups can take a considerable time and limiting operations to less than a few minutes risk aborting perfectly normal operations. This option will cause curl to use the SIGALRM to enable time-outing system calls. timeoutMs

Double timeoutMs ;

Like timeout but takes number of milliseconds instead. timeValue

Double timeValue ; transferText

Boolean transferText ;

When true, it tells the library to use ASCII mode for ftp transfers, instead of the default binary transfer. For win32 systems it does not set the stdout to binary mode. unrestrictedAuth

Boolean unrestrictedAuth ;

26 curl

True tells the library it can continue to send authentication (user+password) when following locations, even when hostname changed. upload

Boolean upload ;

When true, it tells the library to prepare for an upload. url

String url ;

The actual URL to deal with. This is the same as calling setopt with Option.URL. useragent

String useragent ;

This will be used to set the User-Agent: header in the http request sent to the remote server. This can be used to fool servers or scripts. username

String username ;

Sets the user name to be used in protocol authentication. You should not use this option together with the (older) userPwd. password

String password ;

Set a password to use for the transfer. proxyUsername

String proxyUsername ;

Sets user name to use for the transfer while connecting to Proxy. proxyPassword

String proxyPassword ;

Set a password to use for connecting to the proxy.

27 curl useSSL

Integer useSSL ; userPwd

String userPwd ;

A string which should be [user name]:[password] to use for the connection. verbose

Boolean verbose ;

Set this to true to get the library to display a lot of verbose information about its operations. This is the same as calling setopt with Option.VERBOSE. bufferSize

Integer bufferSize ;

Set the preferred size (in bytes) for the receive buffer in libcurl. The main point of this would be that the write callback gets called more often and with smaller chunks. This is the same as calling setopt with Option.BUFFERSIZE. lowSpeedLimit

Integer lowSpeedLimit ;

It contains the transfer speed in bytes per second that the transfer should be below during lowSpeedTime seconds for the library to consider it too slow and abort. lowSpeedTime

Integer lowSpeedTime ;

It contains the time in seconds that the transfer should be below the lowSpeedLimit for the library to consider it too slow and abort. maxSendSpeed

Double maxSendSpeed ;

If an upload exceeds this speed on cumulative average during the transfer, the transfer will pause to keep the average rate less than or equal to this property.

28 curl maxRecvSpeed

Double maxRecvSpeed ;

If a download exceeds this speed on cumulative average during the transfer, the transfer will pause to keep the average rate less than or equal to the property value. maxConnects

Integer maxConnects ;

The set number will be the persistent connection cache size. The set amount will be the maximum amount of simultaneously open connections that libcurl may cache in this easy handle. Default is 5, and there isn't much point in changing this value unless you are perfectly aware of how this work and changes libcurl's behaviour. This concerns connection using any of the protocols that support persistent connections.

When reaching the maximum limit, curl closes the oldest one in the cache to prevent the number of open connections to increase. freshConnect

Boolean freshConnect ;

Set to true to make the next transfer use a new (fresh) connection by force. If the connection cache is full before this connection, one of the existing connections will be closed as according to the selected or default policy. forbidReuse

Boolean forbidReuse ;

Set to true to make the next transfer explicitly close the connection when done. Normally, libcurl keep all connections alive when done with one transfer in case there comes a succeeding one that can re-use them. connectTimeout

Integer connectTimeout ;

This should contain the maximum time in seconds that you allow the connection to the server to take. This only limits the connection phase, once it has connected, this option is of no more use. connectTimeoutMS

Double connectTimeoutMS ;

Like connectTimeout but takes number of milliseconds instead. ipResolve

29 curl

Integer ipResolve ;

Allows an application to select what kind of IP addresses to use when resolving host names. This is only interesting when using host names that resolve addresses using more than one version of IP. connectOnly

Boolean connectOnly ;

A true value tells the library to perform any required proxy authentication and connection setup, but no data transfer. sslCert

String sslCert ;

The string should be the file name of a certificate. sslCertType

String sslCertType ;

The string should be the format of the certificate. Supported formats are "PEM" and "DER" sslKey

String sslKey ;

The string should be the file name of a private key. The default format is "PEM" and can be changed with sslKeyType. sslKeyType

String sslKeyType ;

The string should be the format of the private key. Supported formats are "PEM", "DER" and "ENG". keyPasswd

String keyPasswd ;

It will be used as the password required to use the sslKey or sshPrivateKeyFile private key. sslEngine

String sslEngine ;

It will be used as the identifier for the crypto engine you want to use for your private key.

30 curl sslEngineDefault

String sslEngineDefault ;

Sets the actual crypto engine as the default for (asymmetric) crypto operations. sslVersion

Integer sslVersion ;

Control what version of SSL/TLS to attempt to use. See curl.SSLVersion sslVerifyPeer

Boolean sslVerifyPeer ;

This property determines whether curl verifies the authenticity of the peer's certificate. A true value means curl verifies. cainfo

String cainfo ;

A String naming a file holding one or more certificates to verify the peer with. capath

String capath ;

A String naming a directory holding multiple CA certificates to verify the peer with. randomFile

String randomFile ;

The file will be used to read from to seed the random engine for SSL. The more random the specified file is, the more secure the SSL connection will become. egdSocket

String egdSocket ;

Path name to the Entropy Gathering Daemon socket. It will be used to seed the random engine for SSL. sslVerifyHost

Integer sslVerifyHost ;

31 curl

This option determines whether libcurl verifies that the server cert is for the server it is known as. sslCipherList

String sslCipherList ;

A String holding the list of ciphers to use for the SSL connection. The list must be syntactically correct, it consists of one or more cipher strings separated by colons. Commas or spaces are also acceptable separators but colons are normally used, !, - and + can be used as operators. sslSessionIdCache

Boolean sslSessionIdCache ;

False disables libcurl's use of SSL session-ID caching. Set this to true to enable it. krbLevel

String krbLevel ;

Set the kerberos security level for FTP; this also enables kerberos awareness. This is a string, 'clear', 'safe', 'confidential' or 'private'. If the string is set but doesn't match one of these, 'private' will be used. Set the property to null to disable kerberos support for FTP. sshAuthTypes

Integer sshAuthTypes ;

See curl.SSHAuth. sshHostPublicKeyMD5

String sshHostPublicKeyMD5 ;

A string containing 32 hexadecimal digits. The string should be the 128 bit MD5 cheksum of the remote host's public key, and libcurl will reject the connection to the host unless the md5sums match. This option is only for SCP and SFTP transfers. sshPublicKeyFile

String sshPublicKeyFile ;

A file name for the public key. sshPrivateKeyFile

String sshPrivateKeyFile ;

32 curl

A file name for the private key. newFilePerms

Integer newFilePerms ;

Permissions that will be assigned to newly created files on the remote server. The default value is 0644, but any valid value can be used. newDirectory

Integer newDirectory ;

Permissions that will be assigned to newly created directories on the remote server. The default value is 0755, but any valid value can be used. telnetOptions

Array telnetOptions ;

The elements should be in the format . libcurl supports the options 'TTYPE', 'XDISPLOC' and 'NEW_ENV'. See the TELNET standard for details. proxyType

Integer proxyType ;

Set the type of the proxy. Use constants of the class curl.ProxyType. Methods cleanup

cleanup();

Destroys the CURL handle. When you call this, you can't use this object anymore. escape

String escape(String Str);

URL encodes the given string. This function converts the given input string to an URL encoded string and returns that as a new string. All input characters that are not a-z, A-Z or 0-9 are converted to their "URL escaped" version (%NN where NN is a two-digit hexadecimal number). unescape

33 curl

String unescape(String Str);

This function converts the given URL encoded input string to a plain string duphandle

Easy duphandle();

This function will return a new Easy curl object, a duplicate, using all the options of this object. The new object will not inherit any state information, no connections, no SSL sessions and no cookies. reset

reset();

Re-initializes all options previously set on a specified CURL object to the default values.

It does not change the following information kept in the object: live connections, the Session ID cache, the DNS cache, the cookies and shares. getinfo

Mixed getinfo(Integer info);

Request internal information from the curl session with this function. setopt

Integer setopt(Integer opt, Mixed parameter);

Integer setopt(Object Options);

Set options for curl. You can set properties using an object or by calling setopt several times.

var curl = require("curl"); var options = new Object(); options[curl.Option.URL] = "http://www.sitepoint.com"; options[curl.Option.HEADER] = 1;

var c = new curl.Easy(); c.setopt(options);

is the same as

var curl = require("curl"); var c = new curl.Easy();

34 curl

c.setopt(curl.Option.URL, "http://www.sitepoint.com"); c.setopt(curl.Option.HEADER, 1); perform

Integer perform();

This function is called after all the setopt calls are made, and will perform the transfer as described in the options. You can do any amount of calls to perform while using the same object. If you intend to transfer more than one file, you are even encouraged to do so. libcurl will then attempt to re-use the same connection for the following transfers, thus making the operations faster, less CPU intense and using less network resources. Just note that you will have to use setopt between the invokes to set options for the following perform.

You must never call this function simultaneously from two places using the same object. Let the function return first before invoking it another time. If you want parallel transfers, you must use several curl objects. Events onWrite

The function is called as soon as there is data received that needs to be saved. The data is passed as a core.Binary. The return value should be the number of bytes actually used from the buffer. When this amount differs from the size of the buffer, curl will report an error and will abort the transfer. onRead

This function gets called by libcurl as soon as it needs to read data in order to send it to the peer. This function must return a core.Binary which contains the data. Return 'null' to stop the transfer. onProgress

This function gets called by curl instead of its internal equivalent with a frequent interval during operation (roughly once per second) no matter if data is being transfered or not. Unknown/unused argument values passed to the callback will be set to zero (like if you only download data, the upload size will remain 0). Returning a non-zero value from this callback will cause libcurl to abort the transfer. Arguments are: download total, download now, upload total, upload now.

35 curl

Name curl.Form — Building a multipart/formdata HTTP POST

This class can be used for building a multipart/formdata HTTP POST. Constructor

Form();

Creates a new Form Methods addName

Integer addName(String Name, String Content);

Appens a new section addFile

Integer addFile(String Name, String File, String ContentType);

Adds a file

36 curl

Name curl.FTPAuth — Defines constants for ftpSSLAuth

This class defines constants for setting the property ftpSSLAuth. Constants

Table 5.2. Constants of curl.FTPAuth

Name Description DEFAULT SSL TLS

37 curl

Name curl.FTPMethod — Defines constants for ftpFileMethod

This class defines constants for setting the property ftpFileMethod. Constants

Table 5.3. Constants of curl.FTPMethod

Name Description MULTICWD NOCWD SINGLECWD

38 curl

Name curl.FTPSSL — Defines constants for ftpSSLCCC

This class defines constants for setting the property ftpSSLCCC Constants

Table 5.4. Constants of curl.FTPSSL

Name Description CCC_ACTIVE CCC_NONE CCC_PASSIVE

39 curl

Name curl.Http — Defines constants for httpVersion

Use the constants of this class for setting httpVersion Constants

Table 5.5. Constants of curl.Http

Name Description VERSION_1_0 VERSION_1_1 VERSION_NONE

40 curl

Name curl.Info — Defines constants for use with getinfo

Use the constants in the method getinfo to request internal information from the curl session. Look at libcurl website [http://curl.haxx.se/libcurl/c] for more information about all these constants. Constants

Table 5.6. Constants of curl.Info

Name Description APPCONNECT_TIME Get the time, in seconds, it took from the start until the SSL/SSH connect/handshake to the remote host was completed CERTINFO Not implemented yet! CONDITION_UNMET Get 1 if the condition provided in the previous request didn't match CONNECT_TIME Get the time, in seconds, it took from the start until the connect to the remote host (or proxy) was completed CONTENT_LENGTH_DOWNLOAD Get the content-length of the download. CONTENT_LENGTH_UPLOAD Get the specified size of the upload. CONTENT_TYPE Get the content-type of the downloaded object. This is the value read from the Content-Type: field. COOKIELIST Get a list of all cookies cURL knows EFFECTIVE_URL Get the last used effective URL. FILETIME Get the remote time of the retrieved document (in number of seconds since 1 jan 1970 in the GMT/ UTC time zone). FTP_ENTRY_PATH Get a string holding the path of the entry path. HEADER_SIZE Get the total size of all the headers received. Measured in number of bytes. HTTPAUTH_AVAIL Get a bitmask indicating the authentication method(s) available. HTTP_CONNECTCODE Get the last received proxy response code to a CONNECT request LASTSOCKET Get the last socket used by this curl session. NAMELOOKUP_TIME Get the time, in seconds, it took from the start until the name resolving was completed. NUM_CONNECTS Get how many new connections libcurl had to create to achieve the previous transfer. OS_ERRNO Get the errno variable from a connect failure. PRETRANSFER_TIME Get the time, in seconds, it took from the start until the file transfer is just about to begin

41 curl

Name Description PRIMARY_IP Get a string holding the IP address of the most recent connection done with this curl handle. PROXYAUTH_AVAIL Get a bitmask indicating the authentication method(s) available for your proxy authentication. REDIRECT_COUNT Get the total number of redirections that were actually followed. REDIRECT_TIME Get the total time, in seconds, it took for all redirection steps include name lookup, connect, pretransfer and transfer before final transaction was started. REQUEST_SIZE Get the total size of the issued requests. RESPONSE_CODE Get the last received HTTP or FTP code. SIZE_DOWNLOAD Get the total amount of bytes that were downloaded. SIZE_UPLOAD Get the total amount of bytes that were uploaded. SPEED_DOWNLOAD Get the average download speed that curl measured for the complete download. SPEED_UPLOAD Get the average upload speed that curl measured for the complete upload. SSL_ENGINES SSL_VERIFYRESULT Get the result of the certification verification that was requested. STARTTRANSFER_TIME Get the time, in seconds, it took from the start until the first byte is just about to be transferred. TOTAL_TIME Get the total time in seconds for the previous transfer, including name resolving, TCP connect etc.

42 curl

Name curl.IPResolve — Defines constants for ipResolve

Use the constants of this class for setting ipResolve Constants

Table 5.7. Constants of curl.IPResolve

Name Description V4 Resolve to IPv4 addresses. V6 Resolve to IPv6 addresses. WHATEVER Default, resolves addresses to all IP versions that your system allows.

43 curl

Name curl.Multi — A class to create a libcurl multi session

Class Methods strerror

String strerror(Integer Code); Constructor

Multi();

This creates a new libcurl multi session. It is automatically cleaned up. Methods addHandle

Integer addHandle(curl.Easy Curl); removeHandle

Integer removeHandle(curl.Easy Curl); perform

Integer perform();

44 curl

Name Curl

45 curl

Name curl.Netrc — Defines constants for netrc

Use the constants of this class to set netrc Constants

Table 5.8. Constants of curl.Netrc

Name Description IGNORED The library will ignore the file and use only the information in the URL. This is the default. OPTIONAL The use of your ~/.netrc file is optional, and information in the URL is to be preferred. The file will be scanned for the host and user name (to find the password only) or for the host only, to find the first user name and password after that machine, which ever information is not specified in the URL. REQUIRED This value tells the library that use of the file is required, to ignore the information in the URL, and to search the file for the host only.

46 curl

Name curl.Option — Contains constants for setopt method

Use the constants of this class to set options:

var curl = require("curl"); var options = new Object(); options[curl.Option.VERBOSE] = true; options[curl.Option.URL] = "http://gluescript.sf.net"; var c = new curl.Easy(); c.setopt(options);

For more information about all these options, look at curl_easy_setopt [http://curl.haxx.se/libcurl/c/ curl_easy_setopt.html] api documentation and the documentation of curl.Easy (all these options are also properties of this class). Constants

Table 5.9. Constants of curl.Option

Name Description APPEND AUTOREFERER BUFFERSIZE CAINFO CAPATH CONNECTTIMEOUT CONNECTTIMEOUT_MS COOKIE COOKIEFILE COOKIEJAR COOKIELIST COOKIESESSION CRLF CUSTOMREQUEST DIRLISTONLY DNS_CACHE_TIMEOUT EGDSOCKET ENCODING FAILONERROR FILETIME FOLLOWLOCATION

47 curl

Name Description FORBID_REUSE FRESH_CONNECT FTPPORT FTPSSLAUTH FTP_ACCOUNT FTP_ALTERNATIVE_TO_USER FTP_CREATE_MISSING_DIRS FTP_FILEMETHOD FTP_RESPONSE_TIMEOUT FTP_SKIP_PASV_IP FTP_SSL_CCC FTP_USE_EPRT FTP_USE_EPSV HEADER HTTP200ALIASES HTTPAUTH HTTPGET HTTPHEADER HTTPPOST HTTPPROXYTUNNEL HTTP_CONTENT_DECODING HTTP_TRANSFER_DECODING HTTP_VERSION IGNORE_CONTENT_LENGTH INFILESIZE INFILESIZE_LARGE INTERFACE IPRESOLVE KEYPASSWD KRBLEVEL LOCALPORT LOCALPORTRANGE LOW_SPEED_LIMIT LOW_SPEED_TIME MAXCONNECTS MAXFILESIZE MAXFILESIZE_LARGE MAXREDIRS

48 curl

Name Description MAX_RECV_SPEED_LARGE MAX_SEND_SPEED_LARGE NETRC NETRC_FILE NEW_DIRECTORY_PERMS NEW_FILE_PERMS NOBODY NOPROGRESS NOSIGNAL PASSWORD PORT POST POSTFIELDS POSTFIELDSIZE POSTFIELDSIZE_LARGE POSTQUOTE PREQUOTE PROTOCOLS PROXY PROXYAUTH PROXYPASSWORD PROXYPORT PROXYTYPE PROXYUSERNAME PROXYUSERPWD PUT QUOTE RANDOM_FILE RANGE REDIR_PROTOCOLS REFERER RESUME_FROM RESUME_FROM_LARGE SSH_AUTH_TYPES SSH_PRIVATE_KEYFILE SSH_PUBLIC_KEYFILE SSLCERT SSLCERTTYPE

49 curl

Name Description SSLENGINE SSLENGINE_DEFAULT SSLKEY SSLKEYTYPE SSLVERSION SSL_CIPHER_LIST SSL_SESSIONID_CACHE SSL_VERIFYHOST SSL_VERIFYPEER STDERR TCP_NODELAY TELNETOPTIONS TIMECONDITION TIMEOUT TIMEOUT_MS TIMEVALUE TRANSFERTEXT UNRESTRICTED_AUTH UPLOAD URL USERAGENT USERNAME USERPWD USE_SSL VERBOSE

50 curl

Name curl.Protocol — Defines constants for protocols and redirProtocols

Use the constants of this class to set protocols and redirProtocols. Constants

Table 5.10. Constants of curl.Protocol

Name Description DICT FILE FTP FTPS HTTP HTTPS LDAP SCP SFTP TELNET TFTP VERBOSE

51 curl

Name curl.ProxyType — Defines constants for proxyType

Use the constants of this class to set the property proxyType Constants

Table 5.11. Constants of curl.ProxyType

Name Description HTTP Default use HTTP/1.1 HTTP_1_0 Use HTTP/1.0 SOCKS4 SOCKS4A SOCKS5 SOCKS5_HOSTNAME

52 curl

Name curl.SSHAuth — Defines constants for sshAuthTypes

This class defines constants for setting the property sshAuthTypes. Constants

Table 5.12. Constants of curl.SSHAuth

Name Description ANY HOST KEYBOARD PASSWORD PUBLICKEY

53 curl

Name curl.SSLVersion — Defines constants for sslVersion

Use the constants for setting the property sslVersion. Constants

Table 5.13. Constants of curl.SSLVersion

Name Description DEFAULT SSLv2 SSLv3 TLSv1

54 curl

Name curl.UseSSL — Defines constants for useSSL

Use the constants of this class to set the property useSSL Constants

Table 5.14. Constants of curl.UseSSL

Name Description ALL CONTROL NONE TRY

55 Chapter 6. Data Introduction

The data glue is a common database framework based on Poco Data. Poco Data is an abstraction layer which allows users to easily send/retrieve data to/from various different SQL databases. At the moment the following databases are supported: "SQLite", "ODBC" and "MySQL". To use them, use these name as argument to the constructor of data.Session The data glue is still in early development. Also note that only string, numbers and boolean can be used in the bind method of Statement for the moment. Reference

56 Data

Name data.Session — A Session holds a connection to a database and creates Statement objects.

Constructor

Session(String Connector, String Connection);

Creates a new session, using the given connector (MySQL, SQLite or ODBC), and connectionString. Properties connected

Boolean connected ;

Returns true if the session is connected transaction

Boolean transaction ;

Returns true when a transaction is in progress. Methods begin

begin();

Starts a transaction. close

close();

Closes the session. This is automatically done when the Session object is garbage collected. commit

commit();

Commits and ends a transaction. execute

57 Data

execute(String SQL);

Executes a SQL statement getFeature

Boolean getFeature(String Name);

Look up the state of a feature. getProperty

Any getProperty(String Name);

Look up the value of a property. prepare

data.Statement prepare(String SQL);

Prepares a data.Statement. rollback

rollback();

Rolls back and ends a transaction. setFeature

setFeature(String Name, Boolean State);

Set the state of a feature. setProperty

setProperty(String Name, Any Value);

Set the value of a property.

58 Data

Name data.Statement — A Statement is used to execute SQL statements.

Properties done

Boolean done ;

Returns if the statement was completely executed or if a previously set limit stopped it and there is more work to do. When no limit is set, it will always - after calling execute() - return true. Methods bind

bind();

Binds a value. At this time, only numeric, boolean and string values are allowed! execute

Integer execute(); toString

String toString();

Creates a string from the accumulated SQL statement

59 Data

Name data.RecordSet — RecordSet provides access to data returned from a query.

Recordset provides navigation methods to iterate through the recordset, retrieval methods to extract data, and methods to get metadata (type, etc.) about columns. To work with a RecordSet, first create a data.Statement, execute it, and create the RecordSet from the Statement, as follows:

var stmt = session.prepare("SELECT * FROM Person"); stmt.execute(); var rs = new RecordSet(stmt);

Constructor

RecordSet(data.Statement Statement);

Creates a new RecordSet object Properties columnCount

Integer columnCount ;

Returns the number of columns rowCount

Integer rowCount ;

Returns the number of rows Methods columnLength

columnLength(Integer Pos);

columnLength(String Name);

Returns the maximum length of the column. columnName

columnName(Integer Pos);

60 Data

Returns the name of the column. columnType

columnType(Integer Pos);

columnType(String Name);

Returns the type of the column. columnPrecision

columnPrecision(); moveFirst

Boolean moveFirst();

Moves the row cursor to the first row. Returns true if there is at least one row in the RecordSet, false otherwise. moveLast

Boolean moveLast();

Moves the row cursor to the last row. Returns true if there is at least one row in the RecordSet, false otherwise. moveNext

Boolean moveNext();

Moves the row cursor to the next row. Returns true if the row is available, or false if the end of the record set has been reached and no more rows are available. movePrevious

Boolean movePrevious();

Moves the row cursor to the previous row. Returns true if the row is available, or false if there are no more rows available. value

value();

61 Chapter 7. expat Introduction

The expat glue ports the expat [http://expat.sourceforge.net] XML parser to JavaScript. expat is a stream- oriented parser in which an application registers handlers for things the parser might find in the XML document (like start tags). Reference

62 expat

Name expat.Parser — Parse XML with the expat parser

Parser implements the expat [http://expat.sourceforge.net] XML parser. Constants

Table 7.1. Constants of expat.Parser

Name Description XML_STATUS_ERROR XML_STATUS_OK Constructor

Parser(String Encoding= null);

Constructs a new parser. Properties characters

String characters ;

When the onCharacter callback is not used, XMLParser will collect the characters in this property. It will be cleared when a start tag is read and it will be complete when an end tag is read. onCharacter

Function onCharacter ;

This function is called when contiguous text free of tags is found. Note that this function can be called more then ounce for the same tag. The function gets one argument: the received data. onComment

Function onComment ;

Set a handler for comments. This function gets one argument: all text inside the comment delimiters. onDefault

Function onDefault ;

The function hase one argument: any characters in the document which wouldn't otherwise be handled. This includes both data for which no handlers can be set (like some kinds of DTD declarations) and data

63 expat

which could be reported but which currently has no handler set. The characters are passed exactly as they were present in the XML document except that they will be encoded in UTF-8. Line boundaries are not normalized. Note that a byte order mark character is not passed to the default handler. There are no guarantees about how characters are divided between calls to the default handler: for example, a comment might be split between multiple calls. Setting this handler has the side effect of turning off expansion of references to internally defined general entities. Instead these references are passed to the default handler. onDefaultExpand

Function onDefaultExpand ;

This sets a default handler, but doesn't inhibit the expansion of internal entity references. The entity reference will not be passed to the default handler. The function has one argument: any characters in the document which wouldn't otherwise handled. onEndCData

Function onEndCData ;

This function is called at the end of a CDATA section. onEndElement

Function onEndElement ;

This function will be called everytime when a tag is ended (also for empty tags). The functions gets one argument: the name of the element. onEndNamespaceDecl

Function onEndNamespaceDecl ; onExternalEntityRef

Function onExternalEntityRef ;

Set an external entity reference handler. This handler is also called for processing an external DTD subset if parameter entity parsing is in effect. This function gets 5 arguments: XMLParser, context, base, systemId and publicId. The function must return an integer value: non-zero for success, zero for failure. onProcessing

Function onProcessing ;

This function will be called for processing instructions. It gets two arguments: target and data. A target is the first word in the processing instruction. The data is the rest of the characters in it after skipping all whitespace after the initial word. onSkippedEntity

64 expat

Function onSkippedEntity ;

The function has two arguments: the entity name and a boolean which will be true the entity is a parameter entity and false for general entity. This function is called in two situations:

• An entity reference is encountered for which no declaration has been read and this is not an error.

• An internal entity reference is read, but not expanded, because the onDefault handler has been called. onStartCData

Function onStartCData ;

This function is called at the beginning of a CDATA section. onStartElement

Function onStartElement ;

This function will be called everytime when a tag is started (also for empty tags). The functions get two arguments: the name of the element and an object with contains properties which you can access with the name of the attribute. Methods reset

Boolean reset();

Clean up the memory structures maintained by the parser so that it may be used again. After this has been called, parser is ready to start parsing a new document. parse

Integer parse(String Content, Boolean Final);

Parse some more of the document. Returns XML_STATUS_ERROR or XML_STATUS_OK.

The following example shows how easy it is to create a simple DOM structure in JavaScript.

var expat = require("expat");

// Constructor for a XMLElement object function XMLElement(parent, name, attrs) { this.parent = parent; if ( parent != null ) parent.elements[parent.elements.length + 1] = this; this.name = name; this.attrs = attrs;

65 expat

this.elements = new Array(); } var p = new expat.Parser(); p.currentElement = null; p.onStartElement = function(element, attrs) { this.currentElement = new XMLElement(this.currentElement, element, attrs); } p.onEndElement = function(element) { this.currentElement.data = this.characters;

if ( this.currentElement.parent != null ) this.currentElement = this.currentElement.parent; } p.parse('child', true); // p.currentElement points to the root tag now(tag1)

66 Chapter 8. fcgi Introduction

glue_fcgi is a FastCGI process. Use this to create dynamic webpages with JavaScript, E4X, ... on a webserver that supports FastCGI.

Download mod_fastcgi from FastCGI [], install it and configure it as follows:

LoadModule fastcgi_module modules/mod_fastcgi.dll FastCGIExternalServer "c:/xampp/htdocs/fcgi" -host localhost:9000 Options execCGI AllowOverride None Order allow,deny Allow from all

Before requesting pages, you need to start glue_fastcgi (no need to pass the port argument, because 9000 is the default). Example

Each request is run in its own context. The following objects are constructed before the script is run: fcgi which is a FCGI. This example is a simple echo program:

fcgi.write("Content-type: text/html; charset=iso-8859-1\r\n\r\n"); // cgi response: http://www.ietf.org/rfc/rfc3875 var params = fcgi.getParam(); for(i in params) { fcgi.write(""); fcgi.write(i); fcgi.write(""); fcgi.write(params[i]); fcgi.write("
"); }

Save this program in c:/xampp/htdocs/fcgi. Class Reference

67 fcgi

Name FCGI — Implements FastCGI

Methods getParam

Object getParam();

String getParam(String Param);

An object is returned containing all parameters as properties of the object, or a String is returned when a certain parameter is asked. read

String read(Integer Len);

Reads up to Len consecutive bytes from the input stream. When an empty string is returned, the end of the input has been reached. write

Integer write(String Data);

Integer write(core.Binary Buffer);

Writes a string or buffer into the output stream. The number of characters (or bytes) written are returned. flush

Integer flush(); writeError

Integer writeError(String Data);

68 Chapter 9. gd Introduction

gd ports the GD library [http://www.libgd.org] to JavaScript. GD is a graphics library. It allows your code to quickly draw images complete with lines, arcs, text, multiple colors, cut and paste from other images, and flood fills, and write out the result as a PNG or JPEG file. This is particularly useful in World Wide Web applications, where PNG and JPEG are two of the formats accepted for inline images by most browsers. Examples Drawing a pixel

A white pixel will be drawn in the middle of a black square using setPixel.

var gd = require("gd"); var img = new gd.Image({ width : 100, height: 100 }); // Background colour first var black = img.colorAllocate( { red: 0, green: 0, blue: 0 }); var white = img.colorAllocate( { red: 255, green : 255, blue: 255 });

img.setPixel({ x : 50, y: 50 }, white);

var jpeg = new gd.ImageJPEG(img); jpeg.write("c:\\temp\\pixel.jpg");

Drawing a line

A white line is drawn from the upper left corner to the bottom right corner using line

69 gd

var gd = require("gd"); var img = new gd.Image({ width : 100, height: 100 }); // Background colour first var black = img.colorAllocate( { red: 0, green: 0, blue: 0 }); var white = img.colorAllocate( { red: 255, green : 255, blue: 255 });

img.line({ x : 0, y : 0 }, { x : 99, y : 99 }, white);

var jpeg = new gd.ImageJPEG(img); jpeg.write("c:\\temp\\line.jpg");

Drawing a dashed line

This example shows how to draw a dashed line. A dashed white line is drawn from the upper left corner to the bottom right corner using setStyle and line

var gd = require("gd"); var img = new gd.Image({ width : 100, height: 100 }); // Background colour first var black = img.colorAllocate( { red: 0, green: 0, blue: 0 }); var white = img.colorAllocate( { red: 255, green : 255, blue: 255 });

var style = new Array(white, white, white, gd.transparent, gd.transparent, gd.transparent); img.setStyle(style); img.line({ x : 0, y : 0 }, { x : 99, y : 99 }, gd.styled);

var jpeg = new gd.ImageJPEG(img); jpeg.write("c:\\temp\\dashed.jpg")

70 gd

Drawing a triangle

A triangle is drawn using the polygon functions. This example will draw a white triangle on a black background. For a filled triangle, use filledPolygon.

var gd = require("gd"); var img = new gd.Image({ width : 100, height: 100 }); // Background colour first var black = img.colorAllocate( { red: 0, green: 0, blue: 0 }); var white = img.colorAllocate( { red: 255, green : 255, blue: 255 });

var points = new Array( { x : 50, y : 0 }, { x : 99, y : 99 }, { x : 0, y : 99 }); img.polygon(points, white);

var jpeg = new gd.ImageJPEG(img); jpeg.write("c:\\temp\\polygon.jpg");

Drawing a rectangle

A rectangle is drawn with rectangle.

var gd = require("gd"); var img = new gd.Image({ width: 100, height: 100 }); // Background colour first var black = img.colorAllocate( { red: 0, green: 0, blue: 0 }); var white = img.colorAllocate( { red: 255, green : 255, blue: 255 });

// Note that wxRect should be created with wxPoint to get the same // result as the example on the GD website. img.rectangle(25, 25, 74, 74, white);

71 gd

var jpeg = new gd.ImageJPEG(img); jpeg.write("c:\\temp\\rect.jpg");

Drawing a filled polygon

A filled polygon is created with filledPolygon.

var img = new gd.Image({ width: 100, height: 100 }); // Background colour first var black = img.colorAllocate({ red: 0, green: 0, blue: 0 }); var white = img.colorAllocate({ red: 255, green: 255, blue: 255 }); var red = img.colorAllocate({ red: 255, green: 0, blue: 0 });

var points = new Array({ x : 50, y : 0 }, { x : 99, y : 99 }, { x : 0, y : 99 }); img.filledPolygon(points, white); /* Outline it in red; must be done second */ img.polygon(points, red);

var jpeg = new gd.ImageJPEG(img); jpeg.write("c:\\temp\\filledpolygon.jpg");

Drawing a partial ellipse

arc is used to draw a partial ellipse centered at the given point, with the specified size in pixels.

var gd = require("gd"); var img = new gd.Image({width: 100, height: 50 }); // Background colour first var black = img.colorAllocate({ red: 0, green: 0, blue: 0 }); var white = img.colorAllocate({ red: 255, green: 255, blue: 255 });

img.arc({ x: 50, y : 25 }, { width: 98, height: 48}, 0, 360, white); var jpeg = new gd.ImageJPEG(img); jpeg.write("c:\\temp\\arc.jpg");

72 gd

Drawing a filled partial ellipse

filledArc is used to draw a partial ellipse centered at the given point, with the specified size in pixels.

var gd = require("gd"); var img = new gd.Image({width: 100, height: 50 }); // Background colour first var black = img.colorAllocate({ red: 0, green: 0, blue: 0 }); var white = img.colorAllocate({ red: 255, green: 255, blue: 255 });

img.filledArc({ x: 50, y : }, { width: 98, height: 48 }, 0, 360, white, gd.arc); var jpeg = new gd.ImageJPEG(img); jpeg.write("c:\\temp\\filledarc.jpg");

Alpha Blending

The alphaBlending function allows for two different modes of drawing on truecolor images. In blending mode, which is on by default, the alpha channel component of the color supplied to all drawing functions, such as setPixel , determines how much of the underlying color should be allowed to shine through. As a result, gd automatically blends the existing color at that point with the drawing color, and stores the result in the image. The resulting pixel is opaque. In non-blending mode, the drawing color is copied literally with its alpha channel information, replacing the destination pixel. Blending mode is not available when drawing on palette images.

var red, blue; var img = new gd.Image({ width : 100, height: 100}, true);

/* Background color */ red = gd.trueColor({ red: 255, green: 0, blue: 0 }); img.filledRectangle(0, 0, 100, 100, red);

/* Drawing color. Full transparency would be an alpha channel value of 127 (gd has a 7 bit alpha chnanel). 0 is opaque, 127 is transparent. So cut gdAlphaTransparent in half to get

73 gd

50% blending. */ blue = gd.trueColorAlpha( { red: 0, green: 0, blue: 255 }, gd.alphaTransparent / 2);

/* Draw with blending. Result will be 50% red, 50% blue: yellow (emitted light, remember, not reflected light. What you learned in Kindergarten is wrong here). */ img.alphaBlending(1); img.filledRectangle(0, 0, 25, 25, blue);

/* Draw without blending. Result will be 50% blue, 50% the background color of the image viewer or web browser used; results in browsers that don't support semi-transparent pixels are unpredictable! */ img.alphaBlending(0); img.filledRectangle(75, 75, 25, 25, blue);

var png = new gd.ImagePNG(img); png.write("c:\\temp\\alphablend.png");

Reference

74 gd

Name gd.Font — A wrapper class for the gd fonts

Following fonts are defined: gd.Font.small, gd.Font.large, gd.Font.mediumBold, gd.Font.giant and gd.Font.tiny. Properties w

Integer w ;

Returns the character width h

Integer h ;

Returns the character height size

Integer size ;

Returns the character size

75 gd

Name gd.ImageGIF — A class for reading or writing a GIF image.

Use this class to read a GIF image or to create a GIF image Constructor

ImageGIF(String Filename);

Creates an image from the given file. When the filename is relative the path will be resolved to the path of the active script.

ImageGIF(core.Binary Buffer);

Creates an image with the data from the buffer

ImageGIF(gd.Image Image);

Converts the given image into a GIF image.

This constructor can also be called as a function (without the new keyword) to convert an image to a GIF image. This example will create "test.gif" from img.

var gd = require("gd"); ... gd.ImageGif(img, "test.gif");

Methods write

Boolean write(String Filename);

Writes the image to a file. Returns false when the file can't be opened. writeToBuffer

core.BinaryString writeToBuffer();

Writes the image to a buffer.

76 gd

Name gd.Image — ports all image functions of the GD library

The Image class. Constructor

Image(Object size, Boolean trueColor= false);

Creates a new Image object. The object must have a width and height property.

Image(Integer width, Integer height, Boolean trueColor= false);

Creates a new Image object. Properties tile

gd.Image tile ; colorsTotal

Integer colorsTotal ;

Returns the number of colors currently allocated in a palette image. For truecolor images, the result of the property is undefined and should not be used. interlace

Integer interlace ;

interlace is used to determine whether an image should be stored in a linear fashion, in which lines will appear on the display from first to last, or in an interlaced fashion, in which the image will "fade in" over several passes. By default, images are not interlaced. (When writing JPEG images, interlacing implies generating progressive JPEG files, which are represented as a series of scans of increasing quality. Noninterlaced gd images result in regular [sequential] JPEG data streams.)

A nonzero value for interlace turns on interlace; a zero value turns it off. Note that interlace has no effect on other functions, and has no meaning unless you save the image in PNG or JPEG format; the gd and xbm formats do not support interlace.

When a PNG is loaded or a JPEG is loaded, interlace will be set according to the setting in the PNG or JPEG file.

77 gd

Note that many PNG and JPEG viewers and web browsers do not support interlace or the incremental display of progressive JPEGs. However, the interlaced PNG or progressive JPEG should still display; it will simply appear all at once, just as other images do. transparent

Integer transparent ;

Returns the current transparent color index in the image. If there is no transparent color, returns -1

Sets the transparent color index for the specified image to the specified index. To indicate that there should be no transparent color, use a color index of -1. Note that JPEG images do not support transparency, so this setting has no effect when writing JPEG images.

The color index used should be an index allocated by colorAllocate, whether explicitly invoked by your code or implicitly invoked by loading an image. In order to ensure that your image has a reasonable appearance when viewed by users who do not have transparent background capabilities (or when you are writing a JPEG-format file, which does not support transparency), be sure to give reasonable RGB values to the color you allocate for use as a transparent color, even though it will be transparent on systems that support PNG transparency. width

Integer width ;

Returns the width of the image. height

Integer height ;

Returns the height of the image. size

Object size ;

Returns an object with a width and height property trueColour

Boolean trueColour ;

Returns true if the image is a truecolour image clip

Object clip ;

Establishes a clipping rectangle. Once clip has been set, all future drawing operations will remain within the specified clipping area, until a new clip is set. For instance, if a clipping rectangle of 25, 25, 75, 75 has

78 gd

been set within a 100x100 image, a diagonal line from 0,0 to 99,99 will appear only between 25,25 and 75,75. When set the object must contain the following properties: x, y, width, height

If clip is never set, the clipping area will be the entire image. Methods colorAllocate

colorAllocate(Object Colour);

The object must contain a red, green and blue property

colorAllocate(Integer Red, Integer Green, Integer Blue);

colorAllocate finds the first available color index in the image, sets its RGB values to those requested, and returns the index of the new color table entry, or an RGBA value in the case of a truecolor image; in either case you can then use the returned value as a parameter to drawing functions. When creating a new palette- based image, the first time you invoke this function, you are setting the background color for that image.

In the event that all colors (256) have already been allocated, colorAllocate will return -1 to indicate failure. (This is not uncommon when working with existing PNG files that already use 256 colors.) Note that colorAllocate does not check for existing colors that match your request; see colorExact, colorClosest and colorClosestHWB for ways to locate existing colors that approximate the color desired in situations where a new color is not available. Also see colorResolve. colorDeallocate

colorDeallocate(Integer C);

colorDeallocate marks the specified color as being available for reuse. It does not attempt to determine whether the color index is still in use in the image. After a call to this function, the next call to colorAllocate for the same image will set new RGB values for that color index, changing the color of any pixels which have that index as a result. If multiple calls to colorDeallocate are made consecutively, the lowest- numbered index among them will be reused by the next colorAllocate call. colorAllocateAlpha

Integer colorAllocateAlpha(Object Colour, Integer A);

The object must contain a red, green and blue property

Integer colorAllocateAlpha(Integer Red, Integer Green, Integer Blue, Integer A);

colorAllocateAlpha finds the first available color index in the image specified, sets its RGBA values to those requested, and returns the index of the new color table entry, or an RGBA value in the case of a

79 gd

truecolor image; in either case you can then use the returned value as a parameter to drawing functions. When creating a new palette-based image, the first time you invoke this function, you are setting the background color for that image.

In the event that all colors (256) have already been allocated, colorAllocateAlpha will return -1 to indicate failure. (This is not uncommon when working with existing PNG files that already use 256 colors.) Note that colorAllocateAlpha does not check for existing colors that match your request; see colorExact, colorClosest and colorClosestHWB for ways to locate existing colors that approximate the color desired in situations where a new color is not available. Also see colorResolve colorClosest

colorClosest(Object Colour);

The object must contain a red, green and blue property

Integer colorClosest(Integer Red, Integer Green, Integer Blue);

colorClosest searches the colors which have been defined thus far in the image specified and returns the index of the color with RGB values closest to those of the request. (Closeness is determined by Euclidian distance, which is used to determine the distance in three-dimensional color space between colors.)

If no colors have yet been allocated in the image, colorClosest returns -1.

When applied to a truecolor image, this function always succeeds in returning the desired color.

This function is most useful as a backup method for choosing a drawing color when an image already contains 256 colors and no more can be allocated. (This is not uncommon when working with existing PNG files that already use many colors.) See colorExact for a method of locating exact matches only. colorClosestAlpha

Integer colorClosestAlpha(Object Colour, Integer A);

The object must contain a red, green and blue property

Integer colorClosestAlpha(Integer Red, Integer Green, Integer Blue, Integer A);

colorClosestAlpha searches the colors which have been defined thus far in the image specified and returns the index of the color with RGBA values closest to those of the request. (Closeness is determined by Euclidian distance, which is used to determine the distance in four-dimensional color/alpha space between colors.)

If no colors have yet been allocated in the image, colorClosestAlpha returns -1.

When applied to a truecolor image, this function always succeeds in returning the desired color.

80 gd

This function is most useful as a backup method for choosing a drawing color when a palette-based image already contains 256 colors and no more can be allocated. (This is not uncommon when working with existing palette-based PNG files that already use many colors.) See colorExactAlpha for a method of locating exact matches only. colorClosestHWB

Integer colorClosestHWB(Object Colour);

The object must contain a red, green and blue property

Integer colorClosestHWB(Integer Red, Integer Green, Integer Blue);

colorClosestHWB searches the colors which have been defined thus far in the image specified and returns the index of the color with hue, whiteness and blackness closest to the requested color. This scheme is typically superior to the Euclidian distance scheme used by colorClosest.

If no colors have yet been allocated in the image, colorClosestHWB returns -1.

When applied to a truecolor image, this function always succeeds in returning the desired color.

This function is most useful as a backup method for choosing a drawing color when a palette-based image already contains 256 colors and no more can be allocated. (This is not uncommon when working with existing palette-based PNG files that already use many colors.) See colorExact for a method of locating exact matches only. colorExact

Integer colorExact(Object Colour);

The object must contain a red, green and blue property

Integer colorExact(Integer Red, Integer Green, Integer Blue);

colorExact searches the colors which have been defined thus far in the image specified and returns the index of the first color with RGB values which exactly match those of the request. If no allocated color matches the request precisely, colorExact returns -1. See colorClosest for a way to find the color closest to the color requested.

When applied to a truecolor image, this function always succeeds in returning the desired color. colorExactAlpha

Integer colorExactAlpha(Object Colour, Integer A);

The object must contain a red, green and blue property

81 gd

Integer colorExactAlpha(Integer Red, Integer Green, Integer Blue, Integer A);

The same as colorClosestAlpha but returns an exact match only. colorResolve

Integer colorResolve(Object Colour);

The object must contain a red, green and blue property

Integer colorResolve(Integer Red, Integer Green, Integer Blue);

colorResolve searches the colors which have been defined thus far in the image specified and returns the index of the first color with RGB values which exactly match those of the request. If no allocated color matches the request precisely, then colorResolve tries to allocate the exact color. If there is no space left in the color table then colorResolve returns the closest color (as in colorClosest). This function always returns an index of a color.

When applied to a truecolor image, this function always succeeds in returning the desired color. colorResolveAlpha

Integer colorResolveAlpha(Object Colour, Integer A);

The object must contain a red, green and blue property

Integer colorResolveAlpha(Integer Red, Integer Green, Integer Blue, Integer A);

colorResolveAlpha searches the colors which have been defined thus far in the image specified and returns the index of the first color with RGB values which exactly match those of the request. If no allocated color matches the request precisely, then colorResolveAlpha tries to allocate the exact color. If there is no space left in the color table then colorResolveAlpha returns the closest color (as in colorClosestAlpha). This function always returns an index of a color.

When applied to a truecolor image, this function always succeeds in returning the desired color. red

red(Integer C);

Returns the red portion of the specified color in the image. green

82 gd

green(Integer C);

Returns the green portion of the specified color in the image. blue

blue(Integer C);

Returns the blue portion of the specified color in the image. setPixel

setPixel(Object Point, Integer ColourIndex);

setPixel(Integer X, Integer Y, Integer ColourIndex);

Sets a pixel to a particular color. line

line(Object From, Object To, Integer ColourIndex);

line(Integer X1, Integer Y1, Integer X2, Integer Y2, Integer ColourIndex);

line is used to draw a line between two endpoints (X1,Y1 and X2, Y2). The line is drawn using the color index specified. Note that the color index can be an actual color returned by colorAllocate or one of gd.Styled, gd.Brushed or gd.StyledBrushed.

When an object is passed, it must have a x and y property. For example:

var black = img.colorAllocate( { red: 0, green: 0, blue: 0 }); img.line({x : 0, y : 0}, {x : 99, y : 99 }, black);

polygon

polygon(Array Points, Integer ColourIndex);

polygon is used to draw a polygon with the verticies (at least 3) specified, using the color index specified. The array must contain objects with a x and y property.

83 gd openPolygon

openPolygon(Array Points, Integer ColourIndex);

openPolygon is used to draw a polygon with the verticies (at least 3) specified, using the color index specified. Unlike polygon the enpoints of the line sequence are not connected to a closed polygon. The array must contain objects with a x and y property. rectangle

rectangle(Object Rect, Integer ColourIndex);

Rect must contain a x, y, width and height property

rectangle(Integer X1, Integer Y1, Integer X2, Integer Y2, Integer ColourIndex);

rectangle is used to draw a rectangle using the color index specified. filledPolygon

filledPolygon(Array Points, Integer ColourIndex);

filledPolygon is used to fill a polygon with the verticies (at least 3) specified, using the color index specified. The array must contain objects with a x, y property filledRectangle

filledRectangle(Object Rect, Integer ColourIndex);

Rect must contain an x, y, width and height property

filledRectangle(Integer X1, Integer Y1, Integer X2, Integer Y2, Integer ColourIndex);

filledRectangle is used to draw a solid rectangle with the two corners (upper left first, then lower right) specified, using the color index specified. arc

84 gd

arc(Object Center, Object Size, Integer S, Integer E, Integer ColourIndex);

arc(Integer X, Integer Y, Integer Width, Integer Height, Integer S, Integer E, Integer ColourIndex);

arc is used to draw a partial ellipse centered at the given point, with the specified width and height in pixels. The arc begins at the position in degrees specified by S and ends at the position specified by E. The arc is drawn in the color specified by the last argument. A circle can be drawn by beginning from 0 degrees and ending at 360 degrees, with width and height being equal. E must be greater than S. Values greater than 360 are interpreted modulo 360. filledArc

filledArc(Object Center, Object Size, Integer S, Integer E, Integer ColourIndex, Integer Style);

filledArc(Integer X, Integer Y, Integer Width, Integer Height, Integer S, Integer E, Integer ColourIndex, Integer Style);

filledArc is used to draw a partial ellipse centered at the given point, with the specified width and height in pixels. The arc begins at the position in degrees specified by S and ends at the position specified by E. The arc is filled in the color specified by the second to last argument. A circle can be drawn by beginning from 0 degrees and ending at 360 degrees, with width and height being equal. E must be greater than S. Values greater than 360 are interpreted modulo 360. The last argument is a bitwise OR of the following possibilities: gd.arc, gd.chord, gd.pie (synonym for gd.chord), gd.noFill, and gd.edged. gd.arc and gd.chord are mutually exclusive; gd.chord just connects the starting and ending angles with a straight line, while gd.arc produces a rounded edge. gd.pie is a synonym for gd.arc. gd.noFill indicates that the arc or chord should be outlined, not filled. gd.edged, used together with gd.noFill, indicates that the beginning and ending angles should be connected to the center; this is a good way to outline (rather than fill) a 'pie slice'. filledEllipse

filledEllipse(Object Center,

85 gd

Object Size, Integer ColourIndex);

filledEllipse(Integer X, Integer Y, Integer Width, Integer Height, Integer ColourIndex);

filledEllipse is used to draw an ellipse centered at the given point, with the specified width and height in pixels. The ellipse is filled in the color specified by the last argument. fillToBorder

fillToBorder(Object Point, Integer BorderColorIndex, Integer ColourIndex);

fillToBorder(Integer X, Integer Y, Integer BorderColorIndex, Integer ColourIndex);

fillToBorder floods a portion of the image with the specified color, beginning at the specified point and stopping at the specified border color. For a way of flooding an area defined by the color of the starting point, see fill. The border color cannot be a special color such as gd.Tiled; it must be a proper solid color. fill

fill(Object Point, Integer ColourIndex);

fill(Integer X, Integer Y, Integer ColourIndex);

fill floods a portion of the image with the specified color, beginning at the specified point and flooding the surrounding region of the same color as the starting point. For a way of flooding a region defined by a specific border color rather than by its interior color, see fillToBorder. setAntiAliased

setAntiAliased(Integer ColourIndex);

"Antialiasing" is a process by which jagged edges associated with line drawing can be reduced by blending the foreground color with an appropriate percentage of the background, depending on how much of the pixel in question is actually within the boundaries of the line being drawn. All line-drawing functions, such as line, openPolygon and polygon, will draw antialiased lines if the special "color" gd.AntiAliased is used when calling them.

86 gd

setAntiAliased is used to specify the actual foreground color to be used when drawing antialiased lines.

Antialiased lines can be drawn on both truecolor and palette-based images. However, attempts to draw antialiased lines on highly complex palette-based backgrounds may not give satisfactory results, due to the limited number of colors available in the palette. Antialiased line-drawing on simple backgrounds should work well with palette-based images; otherwise create or fetch a truecolor image instead. setAntiAliasedDontBlend

setAntiAliasedDontBlend(Integer ColourIndex, Integer DontBlend);

Normally, when drawing lines with the special gd.AntiAliased "color," blending with the background to reduce jagged edges is the desired behavior. However, when it is desired that lines not be blended with one particular color when it is encountered in the background, the setAntiAliasedDontBlend function can be used to indicate the special color that the foreground should stand out more clearly against. setBrush

setBrush(gd.Image Brush);

Just as a paintbrush is not a single point, a brush image need not be a single pixel. Any gd image can be used as a brush, and by setting the transparent color index of the brush image with transparent, a brush of any shape can be created. All line-drawing functions, such as line, openPolygon and polygon, will use the current brush if the special "color" gd.Brushed or gd.StyledBrushed is used when calling them.

setBrush is used to specify the brush to be used in a particular image. You can set any image to be the brush. If the brush image does not have the same color map as the first image, any colors missing from the first image will be allocated. If not enough colors can be allocated, the closest colors already available will be used. This allows arbitrary PNGs to be used as brush images. It also means, however, that you should not set a brush unless you will actually use it; if you set a rapid succession of different brush images, you can quickly fill your color map, and the results will not be optimal. setTile

setTile(gd.Image Tile);

Any gd image can be used as a tile, and by setting the transparent color index of the tile image with transparent, a tile that allows certain parts of the underlying area to shine through can be created. All region- filling functions, such as fill and filledPolygon, will use the current tile if the special "color" gd.Tiled is used when calling them. setStyle

setStyle(Array Style);

It is often desirable to draw dashed lines, dotted lines, and other variations on a broken line. setStyle can be used to set any desired series of colors, including a special color that leaves the background intact, to be repeated during the drawing of a line.

To draw a line using the style, use the normal line function with the special color value gd.Styled.

87 gd

Style is an array of integers with the desired series of color values to be repeated. You can assign the special color value gd.Transparent to indicate that the existing color should be left unchanged for that particular pixel (allowing a dashed line to be attractively drawn over an existing image). boundsSafe

Boolean boundsSafe(Object Point);

Boolean boundsSafe(Integer X, Integer Y);

boundsSafe returns true if the specified point is within the current clipping rectangle, false if not. The clipping rectangle is set by clip and defaults to the entire image. getPixel

Integer getPixel(Object point);

Integer getPixel(Integer X, Integer Y);

getPixel retrieves the color index of a particular pixel. setThickness

setThickness(Integer thickness);

Sets the width of lines drawn by the gd.Image#line, gd.Image#polygon, gd.Image#openPolygon and related functions, in pixels. string

string(gd.Font Font, Object Point, String Str, Integer Colour);

string(gd.Font Font, Integer X, Integer Y, String Str, Integer Colour);

string is used to draw a string on the image. stringUp

stringUp(gd.Font Font, Object Point,

88 gd

String Str, Integer Colour);

stringUp(gd.Font Font, Integer X, Integer Y, String Str, Integer Colour);

stringUp is used to draw multiple characters on the image, rotated 90 degrees stringFT

Array stringFT(Integer Fg, String FontName, Double PointSize, Double Angle, Object Point, String Text);

Array stringFT(Integer Fg, String FontName, Double PointSize, Double Angle, Integer X, Integer Y, String Text);

stringFT draws a string of anti-aliased characters on the image using the FreeType library to render user- supplied TrueType fonts. We do not provide TrueType fonts (.ttf and .ttc files). Obtaining them is entirely up to you. The string is anti-aliased, meaning that there should be fewer "jaggies" visible. The fontname is the full pathname to a TrueType font file, or a font face name if the GDFONTPATH environment variable has been set. In the absence of a full path, the font face name may be presented with or without extension.

The string may be arbitrarily scaled (ptsize) and rotated (angle in radians). The direction of rotation is counter-clockwise, with 0 radians (0 degrees) at 3 o'clock and PI/2 radians (90 degrees) at 12 o'clock.

This method returns an array with 2 elements: one with a possible error message and one with another array containing the bounding rectangle (the smallest rectangle that completely surrounds the rendered string and does not intersect any pixel of the rendered string). This array contains the following elements: 0 = lower left corner, X position, 1 = lower left corner, Y position, 2 = lower right corner, X position, 3 = lower right corner, Y position, 4 = upper right corner, X position, 5 = upper right corner, Y position, 6 = upper left corner, X position, 7 = upper left corner, Y position

The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner seeing the text horizontally.

Use gd.stringFT to get the bounding rectangle without rendering. This is a relatively cheap operation if followed by a rendering of the same string, because of the caching of the partial rendering during bounding rectangle calculation.

The string is rendered in the color indicated by the Fg color index. Use the negative of the desired color index to disable anti-aliasing.

89 gd

An example:

var err, rect; var font = "C:\\WINDOWS\\Fonts\\Times.ttf"; [err, rect] = gd.stringFT(0, font, 40, 0, 0, 0, "Hello."); var img = new gd.Image(rect[2] - rect[6] + 6, rect[3] - rect[7] + 6);

var white = img.colorResolve(0, 0, 0); var black = img.colorResolve(255, 255, 255);

var x = 3 - rect[6]; var y = 3 - rect[7]; print("x = ", x, "\n"); print("y = ", y, "\n"); [err, rect] = img.stringFT(black, font, 40, 0, x, y, "Hello."); print(err, "\n");

var jpg = new gd.ImageJPEG(img); jpg.write("c:\\temp\\ttf.jpg");

stringFTCircle

String stringFTCircle(Object Center, Double Radius, Double TextRadius, Double FillPortion, String Font, Double Points, String Top, String Bottom, Index Fg);

String stringFTCircle(Integer X, Integer Y, Double Radius, Double TextRadius, Double FillPortion, String Font, Double Points, String Top, String Bottom, Index Fg);

Draws the text strings specified by Top and Bottom on image, curved along the edge of a circle of radius Radius, with its center at Center. Top is written clockwise along the top; Bottom is written counterclockwise along the bottom. TextRadius determines the "height" of each character; if textRadius is 1/2 of Radius, characters extend halfway from the edge to the center. FillPortion varies from 0 to 1.0, with useful values from about 0.4 to 0.9, and determines how much of the 180 degrees of arc assigned to each section of text is actually occupied by text; 0.9 looks better than 1.0 which is rather crowded. Font is a freetype font; stringFT. Points is passed to the freetype engine and has an effect on hinting; although

90 gd

the size of the text is determined by Radius, TextRadius, and FillPortion, you should pass a point size that "hints" appropriately -- if you know the text will be large, pass a large point size such as 24.0 to get the best results. Fg can be any color, and may have an alpha component, do blending, etc. copy

copy(gd.Image Source, Object DestPoint, Object SourceRect);

copy(gd.Image Source, Integer X, Integer Y, Integer SX, Integer SY, Integer Width, Integer Height);

copy is used to copy a rectangular portion of one image to this image. (For a way of stretching or shrinking the image in the process, see copyResized) The Source argument is the source image from which the region is copied. The DestPoint specifies the point in the image to which the region will be copied. The SourceRect specifies the region in the source image.

When you copy a region from one location in an image to another location in the same image, copy will perform as expected unless the regions overlap, in which case the result is unpredictable.

colorExactcolorAllocatecolorClosest copyResized

copyResized(gd.Image Source, Object DestRect, Object SourceRect);

copyResized(gd.Image Source, Integer X, Integer Y, Integer SX, Integer SY, Integer Width, Integer Height, Integer SWidth, Integer SHeight);

copyResized is used to copy a rectangular portion of one image to this image. The X and Y dimensions of the original region and the destination region can vary, resulting in stretching or shrinking of the region as appropriate. (For a simpler version of this function which does not deal with resizing, see copy) The Source argument is the source image from which the region is copied. The DestRect specifies the point in the image to which the region will be copied. The SourceRect specifies the region in the source image. The width and height of the source region can differ from the destination region, allowing a region to be scaled during the copying process.

91 gd

When you copy a region from one location in an image to another location in the same image, copyResized will perform as expected unless the regions overlap, in which case the result is unpredictable. Note Important note on copying between images: since different images do not necessarily have the same color tables, pixels are not simply set to the same color index values to copy them. copy will attempt to find an identical RGB value in the destination image for each pixel in the copied portion of the source image by invoking colorExact. If such a value is not found, copy will attempt to allocate colors as needed using colorAllocate. If both of these methods fail, copy will invoke colorClosest to find the color in the destination image which most closely approximates the color of the pixel being copied. copyResampled

copyResampled(gd.Image Source, Object DestRect, Object SourceRect);

copyResampled(gd.Image Source, Integer X, Integer Y, Integer SX, Integer SY, Integer Width, Integer Height, Integer SWidth, Integer SHeight);

copyResampled is used to copy a rectangular portion of one image to this image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity. The X and Y dimensions of the original region and the destination region can vary, resulting in stretching or shrinking of the region as appropriate. (For a simpler version of this function which does not deal with resizing, see copy. For a version which does not interpolate pixel values, see copyResized.)

The Source argument is the source image from which the region is copied. The DestRect specifies the point in the image to which the region will be copied. The SourceRect specifies the region in the source image. The width and height of the source region can differ from the destination region, allowing a region to be scaled during the copying process.

When you copy a region from one location in an image to another location in the same image, copyResized will perform as expected unless the regions overlap, in which case the result is unpredictable. Note Important note on copying between images: since different images do not necessarily have the same color tables, pixels are not simply set to the same color index values to copy them. copy will attempt to find an identical RGB value in the destination image for each pixel in the copied portion of the source image by invoking colorExact. If such a value is not found, copy will attempt to allocate colors as needed using colorAllocate. If both of these methods fail, copy will invoke colorClosest to find the color in the destination image which most closely approximates the color of the pixel being copied. copyRotated

92 gd

copyRotated(gd.Image Source, Object DestPoint, Object SourceRect, Integer Angle);

copyRotated(gd.Image Source, Integer X, Integer Y, Integer SX, Integer SY, Integer Width, Integer Height, Integer Angle);

copyRotated is used to copy a rectangular portion of one image to this image, or to another region of the same image. The SourceRect specifies the source area. The DestX and dstY coordinates specify the CENTER of the destination area. This important distinction is made because the rotated rectangle may or may not be parallel to the X and Y axes. The destination coordinates may be floating point, as the center of the desired destination area may lie at the center of a pixel (0.5 pixels) rather than its upper left corner. The angle specified is an integer number of degrees, between 0 and 360, with 0 degrees causing no change, and counterclockwise rotation as the angle increases.

When you copy a region from one location in an image to another location in the same image, copyRotated will perform as expected unless the regions overlap, in which case the result is unpredictable. If this presents a problem, create a scratch image in which to keep intermediate results. Note Important note on copying between images: since palette-based images do not necessarily have the same color tables, pixels are not simply set to the same color index values to copy them. If the destination image is not a truecolor image, colorResolveAlpha is used to choose the destination pixel. copyMerge

copyMerge(gd.Image Source, Object DestPoint, Object SourceRect, Integer Angle, Integer Pct);

copyMerge(gd.Image Source, Integer X, Integer Y, Integer SX, Integer SY, Integer Width, Integer Height, Integer Angle, Integer Pct);

copyMerge is almost identical to copy, except that it 'merges' the two images by an amount specified in the last parameter. If the last parameter is 100, then it will function identically to copy - the source image replaces the pixels in this image.

93 gd

If, however, the Pct parameter is less than 100, then the two images are merged. With Pct = 0, no action is taken. copyMergeGray

copyMergeGray(gd.Image Source, Object DestPoint, Object SourceRect, Integer Angle, Integer Pct);

copyMergeGray(gd.Image Source, Integer X, Integer Y, Integer SX, Integer SY, Integer Width, Integer Height, Integer Angle, Integer Pct);

copyMergeGray is almost identical to copyMerge, except that when merging images it preserves the hue of the source by converting the destination pixels to grey scale before the copy operation. paletteCopy

paletteCopy(gd.Image Source);

Copies a palette from one image to this image, attempting to match the colors in this image to the colors in the source palette. squareToCircle

squareToCircle(Integer Radius);

The image MUST be square, but can have any size. Creates a new image of width and height radius * 2, in which the X axis of the original has been remapped to theta (angle) and the Y axis of the original has been remapped to rho (distance from center). This is known as a "polar coordinate transform." See also stringFTCircle, which uses this function internally. sharpen

sharpen(Integer Pct);

Sharpens the specified image. Pct is a sharpening percentage, and can be greater than 100. Silently does nothing to non-truecolor images. Silently does nothing for Pct < 0. Transparency/alpha channel are not altered. alphaBlending

94 gd

alphaBlending(Integer Blending);

The alphaBlending function allows for two different modes of drawing on truecolor images. In blending mode, which is on by default, the alpha channel component of the color supplied to all drawing functions, such as setPixel, determines how much of the underlying color should be allowed to shine through. As a result, gd automatically blends the existing color at that point with the drawing color, and stores the result in the image. The resulting pixel is opaque. In non-blending mode, the drawing color is copied literally with its alpha channel information, replacing the destination pixel. Blending mode is not available when drawing on palette images. saveAlpha

saveAlpha(Integer Switch);

95 gd

Name gd.ImageJPEG — A class for reading or writing a JPEG image.

Use this class to read a JPEG image or to create a JPEG image. Constructor

ImageJPEG(String Filename);

Creates an image from the given file. When the filename is relative the path will be resolved to the path of the active script.

ImageJPEG(core.Binary Buffer);

Creates an image with the data from the buffer

ImageJPEG(gd.Image Image);

Converts the given image into a JPEG image.

This constructor can also be called as a function (without the new keyword) to convert an image to a JPEG image. This example will create "test.jpg" from img.

var gd = require("gd"); ... gd.ImageJPEG(img, "test.jpg");

Methods write

Boolean write(String Filename, Integer Quality= 100);

Writes the image to a file. Returns false when the file can't be opened. When the filename is relative the path will be resolved to the path of the active script.

The file may be a file URI or a path to a file (the path is converted to a URI internally). writeToBuffer

core.BinaryString writeToBuffer(Integer Quality= 100);

Writes the image to a buffer.

96 gd

Name gd.ImagePNG — A class for reading or writing a PNG image.

Use this class to read a PNG image or to create a PNG image. Constructor

ImagePNG(String Filename);

ImagePNG(core.Binary Buffer);

ImagePNG(gd.Image Image);

This constructor can also be called as a function (without the new keyword) to convert an image to a PNG image. This example will create "test.png" from img.

var gd = require("gd"); ... gd.ImagePNG(img, "test.png");

Methods write

Boolean write(String Filename, Integer Level= -1);

Writes the image to a file. Returns false when the file can't be opened. A compression level of 0 means "no compression." A compression level of 1 means "compressed, but as quickly as possible." A compression level of 9 means "compressed as much as possible to produce the smallest possible file." A compression level of -1 will use the default compression level at the time zlib was compiled on your system.

When the filename is relative the path will be resolved to the path of the active script. writeToBuffer

core.BinaryString writeToBuffer();

Writes the image to a buffer.

97 gd

Name gd

Class Methods useFontConfig

Boolean useFontConfig(Boolean Switch);

GD 2.0.29 introduced the ability to use fontconfig patterns rather than font file names as parameters to stringFT and stringFTCircle. For backwards compatibility reasons, the fontlist parameter to those functions is still expected to be a full or partial font file path name or list thereof by default. However, as a convenience, a single call to gd.useFontConfig with a nonzero parameter configures gd to expect the fontlist parameter to be a fontconfig pattern. Regardless of whether the flag argument is nonzero, this function returns true when the fontconfig library is available and false when it is not. When fontconfig is not available, the fontlist parameter always behaves as in previous versions of GD. trueColor

Integer trueColor(Object Color);

Integer trueColor(Integer Red, Integer Green, Integer Blue);

gd.trueColor returns an RGBA color value for use when drawing on a truecolor image. This method should not be used with palette-based images. If you need to write code which is compatible with both palette- based and truecolor images, use colorResolve. trueColorAlpha

Integer trueColorAlpha(Object Color, Integer Alpha);

gd.trueColor returns an RGBA color value for use when drawing on a truecolor image. This method should not be used with palette-based images. If you need to write code which is compatible with both palette- based and truecolor images, use colorResolve. Properties antiAliased

antiAliased ;

Used in place of a color when invoking a line-drawing function such as line or rectangle. When gd.AntiAliased is used as the color, the foreground color set with setAntiAliased is used, with antialiasing mechanisms to minimize any "jagged" appearance. For more information, see setAntiAliased.

98 gd brushed

brushed ;

Used in place of a color when invoking a line-drawing function such as line or rectangle. When gd.Brushed is used as the color, the brush image set with setBrush is drawn in place of each pixel of the line (the brush is usually larger than one pixel, creating the effect of a wide paintbrush). See also styledBrushed for a way to draw broken lines with a series of distinct copies of an image. maxColors

maxColors ;

The constant 256. This is the maximum number of colors in a palette-based PNG file according to the PNG standard, and is also the maximum number of colors in a palette-based gd image. This of course does not apply to truecolor images. styled

styled ;

Used in place of a color when invoking a line-drawing function such as line or rectangle. When gd.Styled is used as the color, the colors of the pixels are drawn successively from the style that has been set with setStyle. If the color of a pixel is equal to gd.Transparent, that pixel is not altered. (This mechanism is completely unrelated to the "transparent color" of the image itself; see transparent for that mechanism.) See also gd.StyledBrushed. styledBrushed

styledBrushed ;

Used in place of a color when invoking a line-drawing function such as line or rectangle. When gd.StyledBrushed is used as the color, the brush image set with setBrush is drawn at each pixel of the line, providing that the style set with setStyle contains a nonzero value (OR gd.Transparent, which does not equal zero but is supported for consistency) for the current pixel. (Pixels are drawn successively from the style as the line is drawn, returning to the beginning when the available pixels in the style are exhausted.) Note that this differs from the behavior of gd.Styled, in which the values in the style are used as actual pixel colors, except for gd.Transparent. tiled

tiled ;

Used in place of a normal color in filledRectangle, filledPolygon, fill, and fillToBorder. gd.Tiled selects a pixel from the tile image set with setTile in such a way as to ensure that the filled area will be tiled with copies of the tile image. See the discussions of fill and fillToBorder for special restrictions regarding those functions. transparent

99 gd

transparent ;

Used in place of a normal color in a style to be set with setStyle. gd.Transparent is not the transparent color index of the image; for that functionality please see transparent.

100 Chapter 10. memcache Introduction

The module MemCache provides a client api to a memcached server. memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load. GLUEscript uses the memcached client from Jellycan Code [http://code.jellycan.com].

How memcached works can be read at the memcached website [http://www.danga.com/memcached/]. memcached in JavaScript

Using memcached in GLUEscript is easy. Create a memcache.Client object and add a memcached server. When you set properties to the client object, a value will be stored in the cache. When you retrieve properties, a value will be retrieved from the cache. The key used to get the value, is the name of the property.

var memcache = require("memcache"); var client = new memcache.Client(); client.addServer("127.0.0.1:11211"); client.username = "franky"; print(client.username, "\n");

It is not possible to store a JavaScript object directly into the cache. The object will always be converted to a String. Instead JSON [http://www.json.org] can be a good alternative to store an object into the cache. Reference

101 memcache

Name memcache.Client — A JavaScript client for memcached

This is a client for memcached. You can set variables (only primitive values and strings are allowed) as properties to this class. For example:

var client = new memcache.Client(); client.addServer("127.0.0.1:11211"); client.user = "Franky";

The code above sets the username into the cache with key 'user'. Constants

Table 10.1. Constants of memcache.Client

Name Description NOREPLY NOSERVER NOTFOUND NOTSTORED OK

Constructor

Client();

Creates a new client. Methods addServer

Boolean addServer(String Server= localhost);

Add a server to the client. This method will fail only if the address is not a valid IP address or PORT. It will not fail if the server cannot be contacted but will instead continue to occasionally attempt connections to that server. The server is a string specified as IP[:PORT]. The port will default to 11211 if not supplied. add

Array add(String Key, Any Value);

102 memcache

Add an item to the cache. This will fail if the item already exists at the server. An array with two elements is returned: first element contains the result, second element contains the number of items with a successful result. append

Array append(String Key, Any Value);

Append data to an existing item in the cache. An array with two elements is returned: first element contains the number of items with a successful result. The second element is another array containing all result codes when an array is passed, or an integer element that contains the result code. clearServers

clearServers();

Disconnect from and remove all servers. prepend

Integer prepend(String Key, Any Value);

Prepend data to an existing item in the cache. set

Array set(String Key, Any Value, Integer TimeOut= 0);

Array set(Object KeyPairValue, Integer TimeOut= 0);

Sets the key in the cache. When you use the second form, each property of the object will be the key and the property value is the value which is cached. When you want to store complex objects, it is recommended to use JSON to generate a String value. Specify a timeout in seconds for the data to live on the server.

var memcache = require("memcache"); var client = new memcache.Client(); client.addServer("127.0.0.1:11211"); var [n, rc] = client.set({ FirstName : "Franky", LastName : "Braem" }); print("Number of keys added: ", n, "\n"); print("The return code for each key:\n"); for(i in rc) {

103 memcache

print("Rc: " + rc[i], "\n"); } print("FirstName: ", client.FirstName, "\n"); print("LastName: ", client.LastName, "\n");

get

String get(String Key);

Gets the value associated to this key in the cache and returns it as a string. 'null' is returned when the key is not found. replace

Array replace(String Key, Any Value, Integer TimeOut= 0);

Array replace(Object KeyPairValue, Integer TimeOut= 0);

Replace an item in the cache. This will fail if the item does not already exist at the server. The timeout is a time in seconds for the data to live on the server. removeServer

Boolean removeServer(String Server);

Delete a server from the client. The server should be specified as documented in addServer. increment

Array increment(String Key, Integer Diff, Boolean Reply= true);

Increment a value at the server. When a reply is requested (which is the default), an array with two values is returned: the return code and the new value of the key. decrement

Array decrement(String Key, Integer Diff, Boolean Reply= true);

Decrement a value at the server. When a reply is requested (which is the default), an array with two values is returned: the return code and the new value of the key.

104 Chapter 11. mysql Introduction

The MySQL glue makes the MySQL [http://www.mysql.com] database available in JavaScript. This module has been tested with MySQL version 5.0. If you use another version, and you encounter problems, you can try to rebuild this module with your MySQL version. Database

mysql.Database represents a database. Before you can use a database, you have to connect to it.

var mysql = require("mysql"); var db = new mysql.Database(); if ( db.connect("localhost", "root", "password", "dbname") ) { }

Executing SQL statements

SQL statements can be executed with query or prepare. With prepare you can bind JavaScript variables to the SQL statement.

db.query("CREATE TABLE person(name VARCHAR(30), nr INTEGER)");

var stmt = db.prepare("SELECT * FROM person WHERE nr = ?"); stmt.bind(0, 1); var row; while(row = stmt.fetchObject()) { print(row.name); print(row.nr); }

Class Reference

105 mysql

Name mysql.Database — Represents a MySQL database

The class is used for accessing a MySQL database. More information about the MySQL database server can be found at MySQL [http://www.mysql.com]. Constants

Table 11.1. Constants of mysql.Database

Name Description INIT_COMMAND Command to execute when connecting to the MySQL server. Will automatically be re-executed when reconnecting. OPTION_MULTI_STATEMENTS_OFF Disable multiple-statement support. OPTION_MULTI_STATEMENTS_ON Enable multiple-statement support OPT_COMPRESS Use the compressed client/server protocol. OPT_CONNECT_TIMEOUT Connect timeout in seconds. OPT_GUESS_CONNECTION For an application linked against libmysqld, this allows the library to guess whether to use the embedded server or a remote server. “Guess” means that if the hostname is set and is not localhost, it uses a remote server. This behavior is the default. MYSQL_OPT_USE_EMBEDDED_CONNECTION and MYSQL_OPT_USE_REMOTE_CONNECTION can be used to override it. This option is ignored for applications linked against libmysqlclient. OPT_LOCAL_INFILE If no pointer is given or if pointer points to an unsigned int != 0 the command LOAD LOCAL INFILE is enabled. OPT_NAMED_PIPE Use named pipes to connect to a MySQL server on NT. OPT_PROTOCOL Type of protocol to use. Should be one of the enum values of mysql_protocol_type defined in mysql.h. OPT_READ_TIMEOUT Timeout for reads from server (works only for TCP/ IP connections, and only for Windows prior to MySQL 5.0.25). You can this option so that a lost connection can be detected earlier than the TCP/IP Close_Wait_Timeout value of 10 minutes. OPT_RECONNECT Enable or disable automatic reconnection to the server if the connection is found to have been lost. Reconnect has been off by default since MySQL 5.0.3; this option is new in 5.0.13 and provides a way to set reconnection behavior explicitly. OPT_SSL_VERIFY_SERVER_CERT Enable or disable verification of the server's Common Name value in its certificate against the

106 mysql

Name Description hostname used when connecting to the server. The connection is rejected if there is a mismatch. This feature can be used to prevent man-in-the-middle attacks. Verification is disabled by default. Added in MySQL 5.0.23. OPT_USE_EMBEDDED_CONNECTION For an application linked against libmysqld, this forces the use of the embedded server for the connection. This option is ignored for applications linked against libmysqlclient. OPT_USE_REMOTE_CONNECTION For an application linked against libmysqld, this forces the use of a remote server for the connection. This option is ignored for applications linked against libmysqlclient. OPT_USE_RESULT This option is unused. OPT_WRITE_TIMEOUT Timeout for writes to server (works currently only on Windows on TCP/IP connections). READ_DEFAULT_FILE Read options from the named option file instead of from my.cnf. READ_DEFAULT_GROUP Read options from the named group from my.cnf or the file specified with MYSQL_READ_DEFAULT_FILE. REFRESH_GRANT Refresh the grant tables, like FLUSH PRIVILEGES. REFRESH_HOSTS Flush the host cache, like FLUSH HOSTS. REFRESH_LOG Flush the logs, like FLUSH LOGS. REFRESH_MASTER On a master replication server, remove the binary log files listed in the binary log index and truncate the index file, like RESET MASTER REFRESH_SLAVE On a slave replication server, reset the master server information and restart the slave, like RESET SLAVE. REFRESH_STATUS Reset status variables, like FLUSH STATUS. REFRESH_TABLES Flush the table cache, like FLUSH TABLES REFRESH_THREADS Flush the thread cache. REPORT_DATA_TRUNCATION Enable or disable reporting of data truncation errors for prepared statements via MYSQL_BIND.error. (Default: enabled) Added in 5.0.3. SECURE_AUTH Whether to connect to a server that does not support the password hashing used in MySQL 4.1.1 and later. SET_CHARSET_DIR The pathname to the directory that contains character set definition files. SET_CHARSET_NAME The name of the character set to use as the default character set.

107 mysql

Name Description SHARED_MEMORY_BASE_NAME Named of shared-memory object for communication to server. Should be same as the option --shared-memory-base-name used for the mysqld server you want to connect to.

Class Properties clientInfo

String clientInfo ; clientVersion

Integer clientVersion ; Constructor

Database();

Constructs a new Database object Properties affectedRows

Integer affectedRows ;

Returns the number of rows changed by the last UPDATE, deleted by the last DELETE or inserted by the last INSERT statement. May be called immediately after query for UPDATE, DELETE, or INSERT statements. For SELECT statements, affectedRows works like numRows characterSet

String characterSet ;

The character set used by GLUEscript errno

Integer errno ;

Returns the error number for the most recently invoked Database function. error

String error ;

108 mysql

A string containing the error message for the most recently invoked Database function that failed. If a function didn't fail, the return value may be the previous error or an empty string to indicate no error. fieldCount

Integer fieldCount ;

Returns the number of columns for the most recent query on the connection. hostInfo

String hostInfo ;

Returns a string describing the type of connection in use, including the server hostname. info

String info ;

Retrieves a string providing information about the most recently executed query. insertId

Integer insertId ;

Returns the value generated for an AUTO_INCREMENT column by the previous INSERT or UPDATE statement. Use this property after you have performed an INSERT statement into a table that contains an AUTO_INCREMENT field. Note that insertId returns 0 if the previous statement does not use an AUTO_INCREMENT value. If you need to save the value for later, be sure to store the value of insertId in a variable. moreResults

Boolean moreResults ;

This property is used when you execute multiple statements specified as a single statement string, or when you execute CALL statements, which can return multiple result sets.

moreResults returns true if more results exist from the currently executed statement, in which case the application must call next protoInfo

Integer protoInfo ;

Returns the protocol version used by current connection. serverInfo

109 mysql

String serverInfo ;

Returns the version number of the server as a String. serverVersion

Integer serverVersion ;

Returns the version number of the server as an integer. sqlState

String sqlState ;

Returns a string containing the SQLSTATE error code for the most recently executed SQL statement. stat

String stat ;

Returns a string containing information similar to that provided by the mysqladmin status command. This includes uptime in seconds and the number of running threads, questions, reloads, and open tables. warningCount

Integer warningCount ;

Returns the number of warnings generated during execution of the previous SQL statement. Methods autocommit

Boolean autocommit(Boolean Mode);

Sets autocommit mode on if mode is true, off if mode is false. changeUser

Boolean changeUser(String User, String Passwd= null, String Db= null);

Changes the user and causes the database specified by Db to become the default (current) database. In subsequent queries, this database is the default for table references that do not include an explicit database specifier.

changeUser fails if the connected user cannot be authenticated or doesn't have permission to use the database. In this case, the user and database are not changed.

110 mysql

The db parameter may be set to null if you don't want to have a default database.

This command always performs a ROLLBACK of any active transactions, closes all temporary tables, unlocks all locked tables and resets the state as if one had done a new connect. This happens even if the user didn't change. commit

Boolean commit();

Commits the current transaction. connect

Boolean connect(String Host= "", String User= "", String Passwd= "", String Db= "", Integer Port= 0, String UnixSocket= "");

Boolean connect(Object );

Connects to a Database database. When an object is passed, it must contain a host, user, password, database and port property. listDbs

mysql.Result listDbs(String Wild= "");

Returns a result set consisting of database names on the server that match the simple regular expression specified by the Wild parameter. Wild may contain the wildcard characters "%" or "_" or may be an empty string to match all databases listFields

mysql.Result listFields(String Table, String Wild= "");

Returns a result set consisting of field names in the given table that match the simple regular expression specified by the wild parameter. Wild may contain the wildcard characters "%" or "_", or may be an empty string to match all fields listProcesses

mysql.Result listProcesses();

Returns a result set describing the current server threads. This is the same kind of information as that reported by mysqladmin processlist or a SHOW PROCESSLIST query.

111 mysql listTables

mysql.Result listTables(String Wild= "");

Returns a result set consisting of field names in the given table that match the simple regular expression specified by the wild parameter. Wild may contain the wildcard characters "%" or "_", or may be an empty string to match all fields options

Integer options(Integer Option, Any Value);

Can be used to set extra connect options and affect behavior for a connection. This function may be called multiple times to set several options. ping

Integer ping();

Checks whether the connection to the server is working. If the connection has gone down, an automatic reconnection is attempted.

This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary.

Return Values: Zero if the connection to the server is alive. Non-zero if an error occurred. A non-zero return does not indicate whether the MySQL server itself is down; the connection might be broken for other reasons such as network problems. prepare

mysql.Statement prepare(String SQL);

Prepares an SQL statement. The application can include one or more parameter markers in the SQL statement by embedding question mark ("?") characters into the SQL string at the appropriate positions.

The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value. However, they are not allowed for identifiers (such as table or column names), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Language (DML) statements, and not in Data Definition Language (DDL) statements.

The parameter markers must be bound to application variables using bind before executing the statement.

On failure null is returned. query

mysql.Result query();

112 mysql

Executes the SQL statement. When a statement returns rows, mysql.Result object is returned. Otherwise null is returned. null is also returned on failure. You can use fieldCount to get the number of returned fields in a row. refresh

Integer refresh(Integer Options);

This functions flushes tables or caches, or resets replication server information. The connected user must have the RELOAD privilege.

The options argument is a bit mask composed from any combination of the following values. Multiple values can be OR'ed together to perform multiple operations with a single call.

Returns zero for success, non-zero if an error occurred. rollback

Integer rollback();

Rolls back the current transaction. selectDb

Integer selectDb(String Database);

Causes the database specified by Database to become the default (current) database on the connection specified by mysql. In subsequent queries, this database is the default for table references that do not include an explicit database specifier.

selectDb fails unless the connected user can be authenticated as having permission to use the database. setServerOption

Integer setServerOption(Integer Option);

Enables or disables an option for the connection. option can have one of the following values: mysql.Database.OPTION_MULTI_STATEMENTS_ON or mysql.Database.OPTION_MULTI_STATEMENTS_OFF sslSet

Integer sslSet(String Key, String Cert, String Ca, String CaPath, String Cipher);

Key is the pathname to the key file. Cert is the pathname to the certificate file. Ca is the pathname to the certificate authority file. CaPath is the pathname to a directory that contains trusted SSL CA certificates in pem format. Cipher is a list of allowable ciphers to use for SSL encryption.

113 mysql

Name mysql.Field — Represents a field retrieved from a mysql.Result.

Properties autoIncrement

Boolean autoIncrement ;

When true, the field has the AUTO_INCREMENT attribute. binary

Boolean binary ;

When true, the field has the BINARY attribute. catalog

String catalog ;

The catalog name. This value is always "def". db

String db ;

The name of the database that the field comes from. If the field is a calculated field, db is an empty string. def

String def ;

The default value of this field, as a null-terminated string. This is set only if you use listFields. length

Integer length ;

The width of the field, as specified in the table definition. maxLength

Integer maxLength ;

The maximum width of the field for the result set (the length of the longest field value for the rows actually in the result set.

114 mysql multipleKey

Boolean multipleKey ;

When true, the field is part of a non-unique key. name

String name ;

The name of the field. If the field was given an alias with an AS clause, the value of name is the alias. notNull

Boolean notNull ;

When true, field can't be null. orgName

String orgName ;

The name of the field. Aliases are ignored. orgTable

String orgTable ;

The name of the table. Aliases are ignored. primaryKey

Boolean primaryKey ;

When true, the field is part of the primary key. table

String table ;

The name of the table containing this field, if it isn't a calculated field. For calculated fields, the table value is an empty string. If the table was given an alias with an AS clause, the value of table is the alias. uniqueKey

Boolean uniqueKey ;

When true, the field is part of a unique key.

115 mysql unsigned

Boolean unsigned ;

When true, the field has the UNSIGNED attribute. zeroFill

Boolean zeroFill ;

When true, the field has the ZEROFILL attribute.

116 mysql

Name MySQL

117 mysql

Name mysql.Result — Keeps the result of a query.

Properties fieldTell

Integer fieldTell ;

The current offset of the field cursor. numFields

Integer numFields ;

Returns the number of columns in a result set. numRows

Integer numRows ;

Returns the number of rows in the result set. numRows is intended for use with statements that return a result set, such as SELECT. For statements such as INSERT, UPDATE, or DELETE, the number of affected rows can be obtained with affectedRows. Methods dataSeek

dataSeek(Integer Offset);

Seeks to an arbitrary row in a query result set. The offset value is a row number and should be in the range from 0 to numRows.

This function requires that the result set structure contains the entire result of the query, so dataSeek may be used only in conjunction with query. fetchField

mysql.Field fetchField();

Returns the definition of one column of a result. Call this function repeatedly to retrieve information about all columns in the result set. fetchField returns null when no more fields are left. fetchFieldDirect

mysql.Field fetchFieldDirect(Integer FieldNr);

118 mysql

Given a field number FieldNr (between 0 and (numFields - 1)) for a column within a result set, returns that column's field definition as a mysql.Field object. You may use this function to retrieve the definition for an arbitrary column fetchFields

Array fetchFields();

Returns an array of all fields for a result set. Each element represents one column of the result set. When an error occurs or no fields are found, a null is returned. fetchLengths

Array fetchLengths();

Returns an array with integer elements containing the size of each field value. The length for empty columns and for columns containing NULL values is zero. When an error occurs or no fields are found, a null is returned. fetchObject

Object fetchObject();

Returns an array with each field value as element. When an error occurs or there are no fields available a null is returned. fetchRow

Array fetchRow();

Returns an array with each field value as element. When an error occurs or there are no fields available a null is returned. next

Integer next();

This function is used when you execute multiple statements specified as a single statement string, or when you execute CALL statements, which can return multiple result sets.

If more statement results exist, next() reads the next statement result and returns the status back to the application. The result object is ready for retrieving the contents.

119 mysql

Name mysql.Statement — A class for handling a query.

Properties affectedRows

Integer affectedRows ;

Returns the total number of rows changed, deleted, or inserted by the last executed statement. errno

Integer errno ;

Returns the error code for the most recently invoked statement. error

String error ;

Returns a string containing the error message for the most recently invoked statement. insertId

Integer insertId ;

Returns the value generated for an AUTO_INCREMENT column by the previous INSERT or UPDATE statement. Use this property after you have performed an INSERT statement into a table that contains an AUTO_INCREMENT field. Note that insertId returns 0 if the previous statement does not use an AUTO_INCREMENT value. If you need to save the value for later, be sure to store the value of insertId in a variable. paramCount

Integer paramCount ;

Returns the number of parameters in the prepared statement sqlState

String sqlState ;

Returns a string containing the SQLSTATE error code for the most recently executed SQL statement. Methods bind

120 mysql

bind(Array Bindings);

bind(Integer Pos, Mixed Value);

The method bind is used to bind input data for the parameter markers in the SQL statement that was passed to prepare.

The array must contain one element for each "?" parameter marker that is present in the query. execute

Boolean execute();

Executes the prepared statement fetchArray

Array fetchArray();

Returns the next row as an array. fetchObject

Object fetchObject();

Returns the next row as an object. The name of the field is used as name of the property.

121 Chapter 12. net Introduction

net glues the POCO Net classes to JavaScript. These classes are also used by the Apache glue. Handling Form Input

Input elements of an HTML form can be retrieved with the getObject property of the net.HTMLForm class. Create a net.HTMLForm and pass the request as argument. Naming the elements

The name of the element is important. The getObject property will return an object with properties that are based on the name. You can use simple names as shown below:

First name:
Last name:

Now you can reach the elements as follows:

var form = new net.HTMLForm(request); var elements = form.getObject(); response.print("Firstname: " + elements.firstname + "\n"); response.print("Lastname: " + elements.lastname + "\n");

It's also possible to create objects. Use a dot between names and the object tree will be created automatically.

First name:
Last name:

These elements can be reached as follows:

var form = new net.HTMLForm(request); var customer = form.getObject().customer; response.print("Firstname: " + customer.firstname + "\n"); response.print("Lastname: " + customer.lastname + "\n");

122 net

When elements with the same name are used, you can retrieve them as arrays. Use [] in the name of the element.

First name:
Last name:

Use the following code to retrieve the elements:

var form = new net.HTMLForm(request); response.print("Firstname: " + form.getObject().name[0] + "\n"); response.print("Lastname: " + form.getObject().name[1] + "\n");

Arrays and objects can be combined:

First name:
Last name:

Note An array operator without an index can only be used on the last part of the name! Uploading files

HTMLForm is also used to handle file uploads. Use a net.PartHandler when constructing an HTMLForm:

var form = new net.HTMLForm(request, fileHandler);

fileHandler must be an object of type net.PartHandler. This type has a function that is called automatically when a file is uploaded. The function gets header information and a stream to read the body as arguments. This is a sample implementation:

var fileHandler = new net.PartHandler(); fileHandler.handlePart = function(header, stream) { var type = header.get("Content-Type", "(unspecified)"); if (header.has("Content-Disposition")) { var disp, params; [disp, params] = net.MessageHeader.splitParameters(header.get("Content-Disposition"), disp, params); var formElementname = params.get("name", "(unnamed)"); var fileName = params.get("filename", "(unnamed)");

123 net

var newFileName = "c:\\temp\\" + fileName; var fos = new system.FileOutputStream(newFileName); if ( fos ) { while(! stream.eof) { var buffer = stream.read(1024 * 1024); fos.write(buffer); response.print("write 1024 characters
"); } fos.close(); } else { response.print("can't create file: ", newFileName, "
"); } } } Class Reference

124 net

Name net.DatagramSocket — This class provides an interface to an UDP stream socket.

Prototype: net.Socket

Constructor

DatagramSocket();

DatagramSocket(Integer Family);

DatagramSocket(net.Socket Socket);

DatagramSocket(net.SocketAddress SocketAddress, Boolean ReuseAddress= false);

Creates a new DatagramSocket Properties broadcast

Boolean broadcast ;

Returns the IP address and port number of the peer socket. Methods bind

bind(net.SocketAddress Address, Boolean ReuseAddress= false);

Bind a local address to the socket. This is usually only done when establishing a server socket. If ReuseAddress is true, sets the SO_REUSEADDR socket option. Cannot be used together with connect. connect

connect(net.SocketAddress Address);

Restricts incoming and outgoing packets to the specified address. receiveBytes

Integer receiveBytes(core.Binary Buffer,

125 net

Integer Flags= 0);

Receives data from the socket and stores it in buffer. Up to length bytes are received. Returns the number of bytes received. receiveFrom

Integer receiveFrom(core.Binary Buffer, net.SocketAddress Address, Integer Flags= 0);

Receives data from the socket and stores it in buffer. Up to length bytes are received. Stores the address of the sender in address. Returns the number of bytes received. sendBytes

Integer sendBytes(core.Binary Buffer, Integer Flags= 0);

Sends the contents of the given buffer through the socket. Returns the number of bytes sent, which may be less than the number of bytes specified. sendTo

Integer sendTo(core.Binary Buffer, net.SocketAddress Address, Integer Flags= 0);

Sends the contents of the given buffer through the socket to the given address. Returns the number of bytes sent, which may be less than the number of bytes specified.

126 net

Name net.DialogSocket — This class provides an interface to an UDP stream socket.

Prototype: net.StreamSocket

Constructor

DialogSocket();

DialogSocket(net.Socket Socket);

DialogSocket(net.SocketAddress SocketAddress);

Creates a new StreamSocket Methods get

Integer get();

Reads one character from the connection. Returns -1 if no more characters are available. peek

Integer peek();

Returns the character that would be returned by the next call to get, without actually extracting the character from the buffer. Returns -1 if no more characters are available. receiveMessage

Array receiveMessage();

Returns an array with two elements: A boolean which is true when the message is read or false if the connection has been closed by the peer. The second element is the received string, delimited by CR-LF. receiveStatusMessage

Array receiveStatusMessage();

Returns an array with two elements. Receives a single-line or multi-line response from the socket connection. The format must be according to one of the response formats specified in the FTP (RFC 959) or SMTP (RFC 2821) specifications. The first line starts with a 3-digit status code. Following the status code is either a space character (' ' ) (in case of a single-line response) or a minus character ('-') in case

127 net

of a multi-line response. The following lines can have a three-digit status code followed by a minus-sign and some text, or some arbitrary text only. The last line again begins with a three-digit status code (which must be the same as the one in the first line), followed by a space and some arbitrary text. All lines must be terminated by a CR-LF sequence. The response contains all response lines, separated by a newline character, including the status code. The status code is returned as the first element of the array. If the response line does not contain a status code, 0 is returned. sendByte

sendByte();

Sends a single byte over the socket connection. sendMessage

sendMessage(String Message);

sendMessage(String Message, String Arg);

sendMessage(String Message, String Arg1, String Arg2);

Appends a CR-LF sequence to the message and sends it over the socket connection. sendString

sendString(String Str);

Sends the given string over the socket connection. sendTelnetCommand

sendTelnetCommand(Byte Command);

sendTelnetCommand(Byte Command, Byte Arg);

Sends a TELNET command sequence. synch

synch();

Sends a TELNET SYNCH signal over the connection.

128 net

Name net.Family — Defines constants for net.IPAddress

Constants

Table 12.1. Constants of net.Family

Name Description IPv4 IPv6

129 net

Name net.FilePartSource — An implementation of net.PartSource for plain files.

Prototype: net.PartSource

Constructor

FilePartSource(String Path);

FilePartSource(String Path, String MediaType);

FilePartSource(String Path, String Filename, String MediaType);

Constructs a new FilePartSource object. Returns null when the file can't be found. When no MediaType is given, The MIME type is set to application/octet-stream.

130 net

Name net.HTMLForm — HTMLForm is a helper class for working with HTML forms, both on the client and on the server side.

Prototype: net.NameValueCollection

Use HTMLForm to process the input of a HTTP request you received in the Apache module or use it to send a HTML form to a server. Constructor

HTMLForm();

Creates an empty HTMLForm and sets the encoding to "application/x-www-form-urlencoded".

HTMLForm(String Encoding);

Creates an empty HTMLForm that uses the given encoding. Encoding must be either "application/x-www- form-urlencoded" (which is the default) or "multipart/form-data".

HTMLForm(net.HTTPRequest Request);

Use this to create a HTMLForm for processing the GET or POST requests.

HTMLForm(net.HTTPRequest Request, net.PartHandler PartHandler);

Use this to create a HTMLForm for processing a POST request with files. The uploaded files are passed to the given net.PartHandler. Properties boundary

String boundary ;

Returns the MIME boundary used for writing multipart form data. encoding

String encoding ;

the encoding used for posting the form Methods prepareSubmit

131 net

prepareSubmit(net.HTTPRequest Request);

Fills out the request object for submitting the form.

If the request method is GET, the encoded form is appended to the request URI as query string. Otherwise (the method is POST), the form's content type is set to the form's encoding. The form's parameters must be written to the request body separately, with a call to write. If the request's HTTP version is HTTP/1.0:

• persistent connections are disabled

• the content transfer encoding is set to identity encoding

Otherwise, if the request's HTTP version is HTTP/1.1:

• the request's persistent connection state is left unchanged

• the content transfer encoding is set to chunked

132 net

Name net.Cookie — Represents a cookie

A cookie is a small amount of information sent by a Web server to a Web browser, saved by the browser, and later sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used for session management.

A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. This class supports both the Version 0 (by Netscape) and Version 1 (by RFC 2109) cookie specifications. By default, cookies are created using Version 0 to ensure the best interoperability. Class Methods escape

String escape(String Str);

Escapes the given string by replacing all non-alphanumeric characters with escape sequences in the form %xx, where xx is the hexadecimal character code. The following characters will be replaced with escape sequences:

• percent sign %

• less-than and greater-than < and >

• curly brackets { and }

• square brackets [ and ]

• parenthesis ( and )

• solidus /

• vertical line |

• reverse solidus (backslash /)

• quotation mark "

• apostrophe '

• circumflex accent ^

• grave accent `

• comma and semicolon , and ;

• whitespace and control characters unescape

133 net

String unescape(String Str);

Unescapes the given string by replacing all escape sequences in the form %xx with the respective characters. Constructor

Cookie(String Name, String Value);

Constructs a new net.Cookie object. Properties comment

String comment ;

The comment of the cookie. domain

String domain ;

The domain of the cookie. httpOnly

Boolean httpOnly ;

The domain of the cookie. maxAge

Integer maxAge ;

The maximum age in seconds for the cookie. name

String name ;

The name of the cookie. path

String path ;

The path of the cookie.

134 net secure

String secure ;

The value of the secure flag for the cookie. value

String value ;

The value of the cookie. version

String version ;

The version of the cookie 0 (denoting a Netscape cookie) or 1 (denoting a RFC 2109 cookie). Methods toString

String toString();

Returns a string representation of the cookie, suitable for use in a Set-Cookie header.

135 net

Name net.HTTPMessage — The prototype for net.HTTPRequest and net.HTTPResponse .

Prototype: net.MessageHeader

Defines the common properties of all HTTP messages. These are version, content length, content type and transfer encoding. Also methods for HTTP headers are part of this class. Properties chunckedTransferEncoding

Boolean chunckedTransferEncoding ;

Sets the Transfer-Encoding header to chunked. Otherwise, removes the Transfer-Encoding header. contentLength

Integer contentLength ;

The content length contentType

String contentType ;

Get/Set the content type

KeepAlive

Boolean KeepAlive ;

Sets the value of the Connection header field. The value is set to "Keep-Alive" if keepAlive is true, or to "Close" otherwise. version

String version ;

Get/Set HTTP version

136 net

Name net.HTTPRequest — This class is used for representing an HTTP request

Prototype: net.HTTPMessage Important When used with the Apache module, a request object is automatically created and can be reached as 'request'. Constructor

HTTPRequest();

Creates a GET / HTTP/1.0 HTTP request.

HTTPRequest(String Version);

Creates a GET / HTTP/1.x request with the given version (HTTP/1.0 or HTTP/1.1).

HTTPRequest(String Method, String URI);

Creates a HTTP/1.0 request with the given method and URI.

HTTPRequest(String Method, String URI, String Version);

Creates a HTTP request with the given method, URI and version. Properties cookies

net.NameValueCollection cookies ;

Returns the cookies. credentials

Array credentials ;

Returns the authentication scheme and additional authentication information as an array (scheme is the first element, the authentication information is the second element) contained in this request. host

137 net

String host ;

Set/Get the value of the Host header field. method

String method ;

Get/Set the HTTP method path

String path ;

Returns the path of the URI query

String query ;

Returns the query part. uri

String uri ;

Get/Set the requested URI.

138 net

Name net.HTTPRequestHandler

Create an object of this class in the createRequestHandler function of the class net.HTTPRequestHandlerFactory. When a request is handled, the function handleRequest will be called. handleRequest has two arguments: net.HTTPServerRequest and a net.HTTPServerResponse Constructor

HTTPRequestHandler();

Constructs a new HTTPRequestHandler object

139 net

Name net.HTTPRequestHandlerFactory — A factory for net.HTTPRequestHandler objects.

You must set createRequestHandler to a function that receives a net.HTTPServerRequest as argument and that returns a net.HTTPRequestHandler . Constructor

HTTPRequestHandlerFactory();

Constructs a new HTTPRequestHandlerFactory object

140 net

Name net.HTTPResponse — This class encapsulates an HTTP response

Prototype: net.HTTPMessage Important When used with the Apache module, a response object is automatically created and can be reached as 'response'. Constants

Table 12.2. Constants of net.HTTPResponse

Name Description ACCEPTED BAD_GATEWAY BAD_REQUEST CONFLICT CONTINUE CREATED EXPECTATION_FAILED FORBIDDEN FOUND GATEWAY_TIMEOUT GONE INTERNAL_SERVER_ERROR LENGTH_REQUIRED METHOD_NOT_ALLOWED MOVED_PERMANENTLY MULTIPLE_CHOICES NONAUTHORITATIVE NOT_ACCEPTABLE NOT_FOUND NOT_IMPLEMENTED NOT_MODIFIED NO_CONTENT OK PARTIAL_CONTENT PAYMENT_REQUIRED PRECONDITION_FAILED PROXY_AUTHENTICATION_REQUIRED

141 net

Name Description REQUESTED_RANGE_NOT_SATISFIABLE REQUESTENTITYTOOLARGE REQUESTURITOOLONG REQUEST_TIMEOUT RESET_CONTENT SEE_OTHER SERVICE_UNAVAILABLE SWITCHING_PROTOCOLS TEMPORARY_REDIRECT UNAUTHORIZED UNSUPPORTEDMEDIATYPE USEPROXY VERSION_NOT_SUPPORTED Constructor

HTTPResponse();

HTTPResponse(Integer Status);

HTTPResponse(Integer Status, String Reason);

HTTPResponse(String Version, Integer Status);

HTTPResponse(String Version, Integer Status, String Reason);

Constructs a new HTTPResponse. Properties cookies

Array cookies ;

Returns an array with all the cookies set in the response header. date

Date date ;

142 net

Get/Set the Date header status

Integer status ;

Get/Set the HTTP status code. reason

String reason ;

Get/Set the HTTP reason phrase. Methods addCookie

addCookie(net.Cookie Cookie);

143 net

Name net.HTTPServer — A subclass of net.TCPServer that implements a full-featured multithreaded HTTP server.

Prototype: net.TCPServer

A net.HTTPRequestHandlerFactory must be supplied. The net.ServerSocket must be bound and in listening state. To configure various aspects of the server, a net.HTTPServerParams object can be passed to the constructor. The server supports:

• HTTP/1.0 and HTTP/1.1

• automatic handling of persistent connections.

• automatic decoding/encoding of request/response message bodies using chunked transfer encoding.

var net = require("net");

var factory = new net.HTTPRequestHandlerFactory(); factory.createRequestHandler = function(request) { var handler = new net.HTTPRequestHandler(); handler.handleRequest = function(request, response) { response.print("It works!"); }

return handler; }

var httpServer = new net.HTTPServer(factory, new net.ServerSocket(50001), new net.HTTPServerParams()); httpServer.start();

Constructor

HTTPServer(net.HTTPRequestHandlerFactory Factory, net.ServerSocket ServerSocket, net.HTTPServerParams Params);

Constructs a new HTTPServer object

144 net

Name net.HTTPServerParams

Constructor

HTTPServerParams();

Constructs a new HTTPServerParams object Properties keepAlive

Boolean keepAlive ;

Returns true if and only if persistent connections are enabled. keepAliveTimeout

Integer keepAliveTimeout ;

Returns the connection timeout for HTTP connections. maxKeepAliveRequests

Integer maxKeepAliveRequests ;

The maximum number of requests allowed during a persistent connection, or 0 if unlimited connections are allowed. serverName

String serverName ;

The name and port (name:port) that the server uses to identify itself. softwareVersion

String softwareVersion ;

The server software name and version that the server uses to identify itself. timeout

Integer timeout ;

145 net

Returns the connection timeout for HTTP connections.

146 net

Name net.HTTPServerRequest — This class is used for representing an server-side HTTP request

Prototype: net.HTTPRequest

Properties clientAddress

net.SocketAddress clientAddress ;

Returns client's address. expectContinue

Boolean expectContinue ;

Returns true if the client expects a 100 Continue response. serverAddress

net.SocketAddress serverAddress ;

Returns server's address.

147 net

Name net.HTTPServerResponse — This class is used for representing server-side HTTP responses.

Prototype: net.HTTPResponse

Properties sent

Boolean sent ;

Returns true when the headers are already sent. Methods print

print(); sendFile

Boolean sendFile(String File, String Type); redirect

redirect(String URI); sendBuffer

sendBuffer(core.Binary Buffer); requireAuthentication

requireAuthentication(String Realm);

148 net

Name net.IPAddress — This class represents an internet (IP) host address

This class represents an internet (IP) host address. The address can belong either to the IPv4 or the IPv6 address family. See also net.Family. Constructor

IPAddress();

IPAddress(net.IPAddress Address);

IPAddress(Integer Family);

IPAddress(String Address);

IPAddress(String Address, Integer Family); Properties family

Integer family ;

Returns the address family (IPv4 or IPv6) of the address. broadcast

Boolean broadcast ;

Returns true if and only if the address is a broadcast address. globalMC

Boolean globalMC ;

Returns true if and only if the address is a global multicast address. ipv4Compatible

Boolean ipv4Compatible ;

Returns true if and only if the address is IPv4 compatible.

149 net ipv4Mapped

Boolean ipv4Mapped ;

Returns true if and only if the address is an IPv4 mapped IPv6 address. linkLocal

Boolean linkLocal ;

Returns true if and only if the address is a link local unicast address. linkLocalMC

Boolean linkLocalMC ;

Returns true if and only if the address is a link-local multicast address. loopback

Boolean loopback ;

Returns true if and only if the address is a loopback address. multicast

Boolean multicast ;

Returns true if and only if the address is a multicast address. nodeLocalMC

Boolean nodeLocalMC ;

Returns true if and only if the address is a node-local multicast address. orgLocalMC

Boolean orgLocalMC ;

Returns true if and only if the address is a organization-local multicast address. siteLocal

Boolean siteLocal ;

Returns true if and only if the address is a site local unicast address.

150 net siteLocalMC

Boolean siteLocalMC ;

Returns true if and only if the address is a site-local multicast address. unicast

Boolean unicast ;

Returns true if and only if the address is a unicast address. wellKnownMC

Boolean wellKnownMC ;

Returns true if and only if the address is a well-known multicast address. wildcard

Boolean wildcard ;

Returns true if and only if the address is a wildcard (all zero) address.

151 net

Name net.MailMessage — This class represents an e-mail message.

Prototype: net.MessageHeader

MailMessage supports both old-style plain text messages, as well as MIME multipart mail messages with attachments. Constructor

MailMessage();

Constructs a new MailMessage object Properties content

String content ; contentType

String contentType ; date

Date date ; sender

String sender ; subject

String subject ; recipients

Array recipients ;

152 net

Methods addAttachment

addAttachment(String Name, net.PartSource Source);

Adds an attachment to the mail message. Note The MailMessage object will take ownership of the Source object. This means that when this object is garbage collected, the Source object can't be used anymore! addContent

addContent(net.PartSource Source);

Adds a part to the mail message. Note The MailMessage object will take ownership of the Source object. This means that when this object is garbage collected, the Source object can't be used anymore! addRecipient

addRecipient(net.MailRecipient Recipient);

addRecipient(Object Recipient);

addRecipient(Integer Type, String Address);

addRecipient(Integer Type, String Address, String RealName);

Adds a recipient.

153 net

Name net.MailRecipient

Constants

Table 12.3. Constants of net.MailRecipient

Name Description BCC Blind-carbon-copy recipient CC Carbon-copy recipient PRIMARY Primary recipient

Constructor

MailRecipient(Integer Type, String Address);

MailRecipient(Integer Type, String Address, String RealName);

Constructs a new MailRecipient object Properties address

String address ;

Get/Set the address of the recipient. realName

String realName ;

Get/Set the real name of the recipient. type

Integer type ;

Get/Set type of the recipient. Use one of the constants.

154 net

Name net.MessageHeader

Prototype: net.NameValueCollection

A collection of name-value pairs that are used in various internet protocols like HTTP and SMTP. The name is case-insensitive. There can be more than one name-value pair with the same name. Class Methods splitElements

Array splitElements(String Str, Boolean IgnoreEmpty= true);

Splits the given string into separate elements. Elements are expected to be separated by commas. For example, the string

text/plain; q=0.5, text/html, text/x-dvi; q=0.8

is split into the elements

text/plain; q=0.5 text/html text/x-dvi; q=0.8

Commas enclosed in double quotes do not split elements. If ignoreEmpty is true, empty elements are not returned. splitParameters

Array splitParameters(String Str);

Splits the given string into a value and a collection of parameters. The value is returned as first element of the returned array. The parameters are stored in a net.NameValueCollection and can retrieved from the second element of the returned array. Parameters are expected to be separated by semicolons. Enclosing quotes of parameter values are removed. For example, the string

multipart/mixed; boundary="MIME_boundary_01234567"

is split into the value

multipart/mixed

and the parameter

boundary -> MIME_boundary_01234567 Constructor

155 net

MessageHeader();

Creates a new MessageHeader object Methods write

write(system.OutputStream OutputStream);

Writes the message header to the given output stream. The format is one name-value pair per line, with name and value separated by a colon and lines delimited by a carriage return and a linefeed character. See RFC 2822 for details.

156 net

Name net.MulticastSocket — A MulticastSocket is a special net.DatagramSocket that can be used to send packets to and receive packets from multicast groups.

Prototype: net.DatagramSocket

Constructor

MulticastSocket();

MulticastSocket(Integer Family);

MulticastSocket(net.Socket Socket);

MulticastSocket(net.SocketAddress SocketAddress, Boolean ReuseAddress= false);

Creates a new MulticastSocket Properties interface

net.NetworkInterface interface ;

Returns the interface used for sending multicast packets. loopback

Boolean loopback ;

Returns true if and only if loopback for multicast packets is enabled, false otherwise. timeToLive

Integer timeToLive ;

Returns the TTL/hop limit for outgoing packets. Methods joinGroup

joinGroup(net.IPAddress GroupAddress);

157 net

joinGroup(net.IPAddress GroupAddress, net.NetworkInterface Interface);

Joins the specified multicast group at the given interface or the default interface. leaveGroup

leaveGroup(net.IPAddress GroupAddress);

leaveGroup(net.IPAddress GroupAddress, net.NetworkInterface Interface);

Leaves the specified multicast group at the default interface or at the given interface.

158 net

Name Net

159 net

Name net.NameValueCollection — A collection of name-value pairs that are used in various internet protocols like HTTP and SMTP.

This class is a prototype of several classes like net.HTMLForm, net.HTTPMessage, net.HTTPResponse, net.HTTPServerRequest, net.HTTPServerResponse, net.MailMessage and net.MessageHeader. The name is case-insensitive. There can be more than one name-value pair with the same name. Properties empty

Boolean empty ;

Returns true if and only if the header does not have any content. size

Integer size ;

Returns the number of name-value pairs in the collection. Methods add

add(String Name, String Value);

Adds a new name-value pair with the given name and value. clear

clear();

Removes all name-value pairs and their values. erase

erase(String Name);

Removes all name-value pairs with the given name. get

String get(String Name, String Default= null);

160 net

Returns the value of the first name-value pair with the given name. When no value with the given name has been found, the defaultValue is returned. getArray

Array getArray(String Name);

Returns all values with the given name as array. An empty array is returned, when the name-value pair doesn't exist. getObject

Object getObject();

Returns all parameters as one object. For example: when the collection contains values for names 'firstname' and 'lastname' an object will be returned with 'firstname' and 'lastname' as property. Names that contains a [] are transfered to an array. See Naming the elements for more examples. has

Boolean has(String Name);

Returns true if there is at least one name-value pair with the given name. set

set(String Name, String Value);

Sets the value of the (first) name-value pair with the given name.

161 net

Name net.NetworkInterface — This class represents a network interface

NetworkInterface is used with net.MulticastSocket to specify multicast interfaces for sending and receiving multicast messages. Class Methods forAddress

forAddress(net.IPAddress Address);

Returns the NetworkInterface for the given IP address. forIndex

forIndex(Integer Index);

Returns the NetworkInterface for the given interface index. If an index of 0 is specified, a NetworkInterface instance representing the default interface (empty name and wildcard address) is returned. forName

forName(String Name);

Returns the NetworkInterface for the given name. If requireIPv6 is false, an IPv4 interface is returned. Otherwise, an IPv6 interface is returned. list

list();

Returns a list with all network interfaces on the system. Constructor

NetworkInterface();

Creates a network interface Properties address

net.IPAddress address ;

Returns the IP address bound to the interface.

162 net broadcastAddress

net.IPAddress broadcastAddress ;

Returns the IPv4 broadcast address for this network interface. displayName

String displayName ;

Returns the interface display name. index

Integer index ;

Returns the interface index. Only supported if IPv6 is available.

Name

String Name ;

Returns the interface name. subnetMask

net.IPAddress subnetMask ;

Returns the IPv4 subnet mask for this network interface. supportsIPv4

Boolean supportsIPv4 ;

Returns true if the interface supports IPv4. supportsIPv6

Boolean supportsIPv6 ;

Returns true if the interface supports IPv6.

163 net

Name net.PartSource — Prototype for net.FilePartSource and net.StringPartSource.

Properties filename

String filename ;

Returns the filename for the part or attachment. mediatype

String mediatype ;

Returns the MIME media type for this part or attachment.

164 net

Name net.PartHandler — The base class for all part or attachment handlers.

Part handlers are used for handling email parts and attachments in MIME multipart messages, as well as file uploads via HTML forms. A function handlePart will be called to process the file, part, ... For an example see: Uploading files. Constructor

PartHandler();

Creates a new part handeler

165 net

Name net.ServerSocket — This class provides an interface to a TCP server socket.

Constructor

ServerSocket();

ServerSocket(net.SocketAddress Address, Integer Backlog= 64);

ServerSocket(Integer Port, Integer Backlog= 64);

Constructs a new ServerSocket object Methods acceptConnection

net.StreamSocket acceptConnection();

Get the next completed connection from the socket's completed connection queue. If the queue is empty, waits until a connection request completes. Returns a new TCP socket for the connection with the client. bind

bind(net.SocketAddress Address, Boolean Reuse= false);

bind(Integer Port, Boolean Reuse= false);

Bind a local port to the socket. This is usually only done when establishing a server socket. If Reuse is true, sets the SO_REUSEADDR socket option. listen

listen(Integer Backlog= 64);

Puts the socket into listening state. The socket becomes a passive socket that can accept incoming connection requests. The backlog argument specifies the maximum number of connections that can be queued for this socket.

166 net

Name net.SMTPClientSession — This class implements an Simple Mail Transfer Procotol (SMTP, RFC 2821) client for sending e-mail messages.

With this class you can connect to an SMTP server to send mails. As an example I've configured Mercury/32 to listen to the port 2525 and use the SMTP server of my ISP to send the message (Mercury SMTP Client - relay version).

var smtp = new net.SMTPClientSession("localhost", 2525); smtp.login();

Use the class net.MailMessage to create an e-mail and add a recipient using the net.MailRecipient.

mail.addRecipient(net.MailRecipient.PRIMARY, "[email protected]"); mail.sender = "[email protected]"; // Important to set this!

Make sure you set the name of the sender and that it's allowed by your ISP (if you don't use your own SMTP server). For a simple text e-mail use content and send the message with sendMessage.

mail.content = "Hello world"; smtp.sendMessage(mail);

When you want to send attachments, you need to use addAttachment and addContent methods to build the message. Text content is added with net.StringPartSource, while an attachment is added with net.FilePartSource.

mail.addContent(new net.StringPartSource("Hello World")); var attachment = new net.FilePartSource("c:\\text.txt"); mail.addAttachment("text.txt", attachment);

Constructor

SMTPClientSession(String Host, Integer Port= 25);

Constructs a new SMTPClientSession object Properties timeout

Integer timeout ;

167 net

Get/Sets the timeout for socket read operations. Methods close

Boolean close();

Sends a QUIT command and closes the connection to the server. On error an exception is thrown. login

login();

login(Integer Method, String Username, String Password);

Logs in to the SMTP server using the given authentication method and the given credentials. open

open();

Reads the initial response from the SMTP server. Usually called implicitly through login(), but can also be called explicitly to implement different forms of SMTP authentication. Does nothing if called more than once. sendCommand

Object sendCommand(String Command, String Arg= null);

Sends the given command verbatim to the server and waits for a response. An object with two properties is returned: state and response. sendMessage

sendMessage(net.MailMessage Message);

Sends the given mail message by sending a MAIL FROM command, a RCPT TO command for every recipient, and a DATA command with the message headers and content.

168 net

Name net.SocketAddress — This class represents an internet (IP) endpoint/socket address.

This class represents an internet (IP) endpoint/socket address. The address can belong either to the IPv4 or the IPv6 address family and consists of a host address and a port number. Constructor

SocketAddress();

SocketAddress(net.SocketAddress Address);

SocketAddress(net.IPAddress Address, Integer Port);

SocketAddress(String Host, Integer Port);

SocketAddress(String HostAndPort);

The constructor without arguments creates a wildcard (all zero) IPv4 socket address. When only a string is passed, it creates a SocketAddress from an IP address or host name and a port number/service name. Host name/address and port number must be separated by a colon. In case of an IPv6 address, the address part must be enclosed in brackets. Properties family

Integer family ;

Returns the address family of the host's address. host

net.IPAddress host ;

Returns the host IP address. port

Integer port ;

Returns the port number.

169 net

Methods toString

String toString();

Returns a string representation of the address.

170 net

Name net.Socket — Socket is the prototype for net.StreamSocket, net.ServerSocket, net.DatagramSocket and other socket classes.

Class Properties supportsIPV4

Boolean supportsIPV4 ; supportsIPV6

Boolean supportsIPV6 ; Properties address

net.SocketAddress address ;

Returns the IP address and port number of the socket. available

Integer available ;

Returns the number of bytes available that can be read without causing the socket to block. blocking

Boolean blocking ;

Get/Set the blocking mode. keepAlive

Boolean keepAlive ;

Get/Set the value of the SO_KEEPALIVE socket option. linger

Object linger ;

Get/Set the value of the SO_LINGER socket option. The object must have a on and seconds property.

171 net noDelay

Boolean noDelay ;

Get/Set the value of the TCP_NODELAY socket option.

OOBInline

Boolean OOBInline ;

Get/Set the value of the SO_OOBINLINE socket option. receiveBufferSize

Integer receiveBufferSize ;

Get/Set the size of the receive buffer. receiveTimeout

Integer receiveTimeout ;

Get/Set the timeout in milliseconds. reuseAddress

Boolean reuseAddress ;

Get/Set the value of the SO_REUSEADDR socket option. reusePort

Boolean reusePort ;

Get/Set the value of the SO_REUSEPORT socket option. sendBufferSize

Integer sendBufferSize ;

Get/Set the size of the send buffer. sendTimeout

Integer sendTimeout ;

Get/Set the timeout in milliseconds.

172 net peerAddress

net.SocketAddress peerAddress ;

Returns the IP address and port number of the peer socket. Methods close

close();

Closes the socket. poll

Boolean poll(Integer TimeOut, Integer Mode);

Determines the status of the socket, using a call to select().

173 net

Name net.StreamSocket — This class provides an interface to an UDP stream socket.

Prototype: net.StreamSocket

Constructor

StreamSocket();

StreamSocket(Integer Family);

StreamSocket(net.StreamSocket Socket);

StreamSocket(net.SocketAddress SocketAddress);

Creates a new StreamSocket Methods connect

connect(net.SocketAddress Address);

connect(net.SocketAddress Address, Integer Timeout);

Initializes the socket and establishes a connection to the TCP server at the given address. connectNB

connectNB(net.SocketAddress Address);

Initializes the socket and establishes a connection to the TCP server at the given address. Prior to opening the connection the socket is set to nonblocking mode. receiveBytes

Integer receiveBytes(core.Binary Buffer, Integer Flags= 0);

Receives data from the socket and stores it in buffer. Up to length bytes are received. Returns the number of bytes received. sendBytes

174 net

Integer sendBytes(core.Binary Buffer, Integer Flags= 0);

Sends the contents of the given buffer through the socket. Returns the number of bytes sent, which may be less than the number of bytes specified. sendUrgent

Integer sendUrgent(Integer Char);

Sends one byte of urgent data through the socket. shutdown

shutdown();

Shuts down both the receiving and the sending part of the socket connection. shutdownReceive

shutdownReceive();

Shuts down the receiving part of the socket connection. shutdownSend

shutdownSend();

Shuts down the sending part of the socket connection.

175 net

Name net.StringPartSource — An implementation of net.PartSource for strings.

Prototype: net.PartSource

Constructor

StringPartSource(String Str);

StringPartSource(String Str, String MediaType);

StringPartSource(String Str, String MediaType, String Filename);

Constructs a new StringPartSource object. The MIME type is set to text/plain when MediaType is not given.

176 net

Name net.TCPServer — This class implements a multithreaded TCP server.

Constructor

TCPServer(net.TCPServerConnectionFactory Factory, net.ServerSocket ServerSocket, net.TCPServerParams Params= null);

Constructs a new TCPServer object Properties currentConnections

Integer currentConnections ;

Returns the number of currently handled connections. currentThreads

Integer currentThreads ;

Returns the number of currently used connection threads. maxConcurrentConnections

Integer maxConcurrentConnections ;

Returns the maximum number of concurrently handled connections. port

Integer port ;

Returns the port the server socket listens to. queuedConnections

Integer queuedConnections ;

Returns the number of queued connections. refusedConnections

177 net

Integer refusedConnections ;

Returns the number of refused connections. Methods start

start(); stop

stop();

178 net

Name net.TCPServerConnection

Constructor

TCPServerConnection(net.StreamSocket Socket);

Constructs a new TCPServerConnection object Properties socket

net.StreamSocket socket ;

Returns the underlying socket

179 net

Name net.TCPServerConnectionFactory

Constructor

TCPServerConnectionFactory();

Constructs a new TCPServerConnectionFactory object

180 net

Name net.TCPServerParams

Constructor

TCPServerParams();

Constructs a new TCPServerParams object Properties maxQueued

Integer maxQueued ;

The maximum number of queued connections. maxThreads

Integer maxThreads ;

The maximum number of simultaneous threads available. threadIdleTime

Integer threadIdleTime ;

The maximum thread idle time in milliseconds. threadPriority

Integer threadPriority ;

The priority of TCP server threads

181 Chapter 13. sqlite Introduction

The sqlite glue makes the SQLite [http://www.sqlite.org] database available in JavaScript. Database

sqlite.Database represents a database. When the database doens't exist, the database will be created.

var sqlite = require("sqlite"); var db = new sqlite.Database("person.db");

Executing SQL statements

SQL statements can be executed with exec or prepare. Use exec when you don't need information from the database:

db.exec("CREATE TABLE person(name TEXT, nr INTEGER)");

Use prepare when you need information from the database. prepare will return a sqlite.Statement object. sqlite.Statement allows you to iterate the results of the SQL statements.

var stmt = db.prepare("SELECT * FROM person"); var row; while(row = stmt.fetchObject()) { print(row.name); print(row.nr); }

Class Reference

182 sqlite

Name sqlite.Database — Implements a SQLite database

Constants

Table 13.1. Constants of sqlite.Database

Name Description ABORT Callback routine requested an abort AUTH Authorization denied BUSY The database file is locked CANTOPEN Unable to open the database file CONSTRAINT Abort due to constraint violation CORRUPT The database disk image is malformed DELETE DENY DONE step has finished executing EMPTY (Internal Only) Database table is empty ERROR SQL error or missing database FULL Insertion failed because database is full INSERT INTERNAL An internal logic error in SQLite INTERRUPT Operation terminated by sqlite_interrupt() IOERR Some kind of disk I/O error occurred LOCKED A table in the database is locked MISMATCH Data type mismatch MISUSE Library used incorrectly NOLFS Uses OS features not supported on host NOMEM A malloc() failed NOTFOUND (Internal Only) Table or record not found OK Successful result PERM Access permission denied PROTOCOL Database lock protocol error READONLY Attempt to write a readonly database ROW step has another row ready SCHEMA The database schema changed TOOBIG Too much data for one row of a table UPDATE

183 sqlite

Class Methods complete

Boolean complete(String SQL);

This function returns true if the given input string comprises one or more complete SQL statements. Constructor

Database(String Filename);

Constructs a new Database object.

When the filename is relative the path will be resolved to the path of the active script. Properties autocommit

Boolean autocommit ;

Test to see whether or not the database connection is in autocommit mode. Return TRUE if it is and FALSE if not. Autocommit mode is on by default. Autocommit is disabled by a BEGIN statement and reenabled by the next COMMIT or ROLLBACK. changes

Integer changes ;

This property returns the number of database rows that were changed (or inserted or deleted) by the most recently completed INSERT, UPDATE, or DELETE statement. Only changes that are directly specified by the INSERT, UPDATE, or DELETE statement are counted. Auxiliary changes caused by triggers are not counted. See totalChanges lastInsertRowID

Double lastInsertRowID ;

Each entry in an SQLite table has a unique integer key called the "rowid". The rowid is always available as an undeclared column named ROWID, OID, or _ROWID_. If the table has a column of type INTEGER PRIMARY KEY then that column is another an alias for the rowid.

This property returns the rowid of the most recent INSERT into the database from the database connection. If no inserts have ever occurred on this database connection, zero is returned.

If an INSERT occurs within a trigger, then the rowid of the inserted row is returned by this routine as long as the trigger is running. But once the trigger terminates, the value returned by this routine reverts to the last value inserted before the trigger fired.

184 sqlite errMsg

String errMsg ;

Returns the error message from the most recent sqlite method call. errNo

Integer errNo ;

Returns the error number from the most recent sqlite method call. onCommit

Function onCommit ;

Register a callback function to be invoked whenever a new transaction is committed. If the callback function returns non-zero, then the commit is converted into a rollback. onTrace

Function onTrace ;

Register a function that is called each time an SQL statement is evaluated. The function receives the SQL statement as argument. onRollback

Function onRollback ;

Register a callback to be invoked whenever a transaction is rolled back. onUpdate

Function onUpdate ;

Register a callback function with the database to be invoked whenever a row is updated, inserted or deleted.

The function gets 4 arguments: The first argument is one of Database.INSERT, Database.DELETE or Database.UPDATE, depending on the operation that caused the callback to be invoked. The second and third arguments to the callback contains the database and table name from the affected row. The final callback parameter is the rowid of the row. In the case of an update, this is the rowid after the update takes place. opened

Boolean opened ;

Returns true when the database was successfully opened

185 sqlite totalChanges

Integer totalChanges ;

Use this property to find the total number of changes including changes caused by triggers. See changes Methods exec

Integer exec(String SQL);

Executes an SQL statement immediately. prepare

sqlite.Statement prepare(String SQL);

To execute an SQL query, it must first be compiled into a byte-code program using prepare.

186 sqlite

Name SQLite

187 sqlite

Name sqlite.Statement — Implements an sqlite statement.

Use the prepare method to create a SQLite SQL statement. Properties columnCount

Integer columnCount ;

Return the number of columns in the result set returned by the prepared SQL statement. Methods bind

Integer bind(Integer Parameter, Mixed Value);

Integer bind(String Parameter, Mixed Value);

In the SQL strings input to prepare, one or more literals can be replace by a parameter "?" or ":AAA" or "$VVV" where AAA is an alphanumeric identifier and VVV is a variable name according to the syntax rules of the TCL programming language. The values of these parameters (also called "host parameter names") can be set using bind.

The first argument to bind is the index or the name of the parameter to be set. The first parameter has an index of 1.

The second argument is the value to bind to the parameter.

bind must be called after prepare or reset and before sqlite.Statement.method.step. Bindings are not cleared by the reset. Unbound parameters are interpreted as NULL.

bind returns Database.OK on success or an error code if anything goes wrong. Database.RANGE is returned if the parameter index is out of range. Database.NOMEM is returned if malloc fails. Database.MISUSE is returned if these routines are called on a virtual machine that is the wrong state or which has already been finalized.

Blobs are supported. Use a core.Binary instance as value. columnDeclType

String columnDeclType(Integer Column);

The declared type of the table column is returned. If the column of the result set is not a table column, then null is returned. For example, in the database schema:

188 sqlite

CREATE TABLE t1(c1 INTEGER);

And the following statement compiled:

SELECT c1 + 1, c1 FROM t1;

Then this method would return the string "INTEGER" for the second result column (Column==1), and nullL for the first result column (Column==0).

If the following statements were compiled then this method would return "INTEGER" for the first (only) result column.

SELECT (SELECT c1) FROM t1; SELECT (SELECT c1 FROM t1); SELECT c1 FROM (SELECT c1 FROM t1); SELECT * FROM (SELECT c1 FROM t1); SELECT * FROM (SELECT * FROM t1); columnName

String columnName(Integer Column);

This function returns the column heading for the column of this statement, columnOriginalName

String columnOriginalName(Integer Column);

If the column returned by the statement is a column reference, this function may be used to access the schema name of the referenced column in the database schema. If the column is not a column reference, NULL is returned. columnTableName

String columnTableName(Integer Column);

If the column returned by the statement is a column reference, this function may be used to access the name of the table that contains the column. If the column is not a column reference, null is returned. fetchArray

Array fetchArray();

This method calls step and returns the row in an array. An empty array will be returned when no rows are available anymore. fetchObject

Object fetchObject();

189 sqlite

This method calls step and returns the row as a JavaScript object. null will be returned when no rows are available anymore. step

Integer step();

After an SQL query has been prepared with a call to either prepare, then this method must be called one or more times to execute the statement. The return value will be either Database.BUSY, Database.DONE, Database.ROW, Database.ERROR, or Database.MISUSE.

• Database.BUSY means that the database engine attempted to open a locked database and there is no busy callback registered. Call step again to retry the open.

• Database.DONE means that the statement has finished executing successfully. step should not be called again on this virtual machine without first calling reset to reset the virtual machine back to its initial state.

• If the SQL statement being executed returns any data, then Database.ROW is returned each time a new row of data is ready for processing by the caller. Call step again to retrieve the next row of data.

• Database.ERROR means that a run-time error (such as a constraint violation) has occurred. step should not be called again on the VM. More information may be found in the property errMsg.

• Database.MISUSE means that the this routine was called inappropriately. Perhaps it was called on a virtual machine that had already been finalized or on one that had previously returned sqlite.ERROR or Database.DONE. Or it could be the case that a database connection is being used by a different thread than the one it was created it.

Database.MISUSE is also returned when the associated Database object is not available anymore. This can occur when the database is finalized (when the variable gets out of scope for example). Make sure the database object is still referenced somewhere by a local or global variable. reset

Integer reset();

The reset function is called to reset a prepared SQL statement obtained by a previous call to prepare back to it's initial state, ready to be re-executed.

190 Chapter 14. system Introduction

system provides classes for accessing the filesystem, the enviroment, processes, .... Reference

191 system

Name Global Functions — global functions

Methods glob

Array glob(String Pattern, Integer Options);

Creates a set of files that match the given pathPattern. The path may be give in either Unix, Windows or VMS syntax and is automatically expanded by calling expand. The pattern may contain wildcard expressions even in intermediate directory names. Note that, for obvious reasons, escaping characters in a pattern with a backslash does not work in Windows-style paths. Directories that for whatever reason cannot be traversed are ignored.

The available options are defined as properties on this function: CASELESS, DEFAULT, DOT_SPECIAL and FOLLOWING_SYMLINKS. An example:

var system = require("system"); var files = system.glob("/development/*.cpp", system.glob.CASELESS);

192 system

Name system.File — The File class provides methods for working with a file.

Constructor

File(system.Path Path);

File(String Path);

Creates a new File object. Properties canExecute

Boolean canExecute ;

Makes the file executable (if flag is true), or non-executable (if flag is false) by setting the file's permission bits accordingly. canRead

Boolean canRead ;

Makes the file non-writeable (if flag is true), or writeable (if flag is false) by setting the file's flags in the filesystem accordingly. canWrite

Boolean canWrite ;

Makes the file writeable (if flag is true), or non-writeable (if flag is false) by setting the file's flags in the filesystem accordingly. created

Date created ;

Returns the creation date of the file. Not all platforms or filesystems (e.g. Linux and most Unix platforms with the exception of FreeBSD and Mac OS X) maintain the creation date of a file. On such platforms, created returns the time of the last inode modification. directory

Boolean directory ;

193 system

Returns true when the file is a directory. exists

Boolean exists ;

Returns true when the file exists file

Boolean file ;

Returns true when the file is a regular file. hidden

Boolean hidden ;

Returns true if the file is hidden. On Windows platforms, the file's hidden attribute is set for this to be true. On Unix platforms, the file name must begin with a period for this to be true. lastModified

Boolean lastModified ;

Gets/Sets the modification date of the file. link

Boolean link ;

Returns true if the file is a symbolic link. size

Integer size ;

Gets/Sets the size of the file path

String path ;

Returns the path Methods copyTo

194 system

Boolean copyTo(String Path);

Copies the file (or directory) to the given path. The target path can be a directory. createDirectories

Boolean createDirectories();

Creates a directory (and all parent directories if necessary). createDirectory

Boolean createDirectory();

Creates a directory. Returns true if the directory has been created and false if it already exists or an error occurs. createFile

Boolean createFile();

Creates a new, empty file in an atomic operation. Returns true if the file has been created and false if the file already exists or when an error occurs. list

Array list();

Returns the names of all files in the directory. moveTo

Boolean moveTo(String Path);

Move the file (or directory) to the given path. The target path can be a directory. remove

Boolean remove(Boolean Recursive= false);

Deletes the file. If recursive is true and the file is a directory, recursively deletes all files in the directory. renameTo

Boolean renameTo(String Path);

Renames the file to the new name.

195 system

Name system.FileInputStream — An input stream for reading from a file.

Prototype: system.InputStream

Files are always opened in binary mode. When you need to handle text you need to use system.TextInputStream Note A stream is automatically closed when the object is garbage collected. When this is to late, you need to call the close method. Constructor

FileInputStream(String Filename);

Creates a new FileInputStream object. When the file doesn't exist null is returned. Methods close

close();

Closes the stream.

196 system

Name system.FileOutputStream — An output stream for writing data to a file.

Prototype: system.OutputStream

Files are always opened in binary mode. When you need to handle text you need to use system.TextOutputStream Note A stream is automatically closed when the object is garbage collected. When this is to late, you need to call the close method. Constructor

FileOutputStream(String Filename, Boolean Truncate= true);

Creates a new FileOutputStream object. When the file doesn't exist null is returned. When Truncate is true (which is the default), the file will be truncated. Methods close

close();

Closes the stream.

197 system

Name system.InputStream — Base class for all input streams.

Constants

Table 14.1. Constants of system.InputStream

Name Description SEEK_BEG SEEK_CUR SEEK_END

Properties count

Integer count ;

Get number of characters extracted by last unformatted input operation eof

Boolean eof ;

Returns true when the end of the file is reached. pos

Integer pos ;

Returns the absolute position of the get pointer. The get pointer determines the next location in the input sequence to be read by the next input operation. Methods ignore

ignore(Integer Size= 1);

Extracts characters from the input sequence and discards them. peek

Integer peek();

198 system

Reads and returns the next character without extracting it, i.e. leaving it as the next character to be extracted from the stream. read

core.BinaryString read(Integer Size);

Reads a block of data. seek

Boolean seek(Integer Pos);

Boolean seek(Integer Offset, Integer Direction);

Sets the position of the get pointer to the given position. False is returned on failure. unget

unget();

Decrements the internal get pointer by one, making the last character extracted from the input sequence available again as the next character to be read from the stream.

199 system

Name system.OutputStream — Base class for all output streams.

Constants

Table 14.2. Constants of system.OutputStream

Name Description SEEK_BEG SEEK_CUR SEEK_END

Properties pos

Integer pos ;

Returns the absolute position of the put pointer. The put pointer determines the next location in the output sequence where the next output operation is going to take place. Methods write

write(core.Binary Buffer);

write(String Buffer);

Writes a block of data. seek

Boolean seek(Integer Pos);

Boolean seek(Integer Offset, Integer Direction);

Sets the position of the get pointer to the given position. False is returned on failure. flush

flush();

200 system

Synchronizes the buffer associated with the stream to its controlled output sequence. This effectively means that all unwritten characters in the buffer are written to its controlled output sequence as soon as possible ("flushed").

201 system

Name system.Path — This class represents filesystem paths (including filenames) in a platform-independent manner

Unix, Windows and OpenVMS all use a different syntax for filesystem paths. This class can work with all three formats. A path is made up of an optional node name (only Windows and OpenVMS), an optional device name (also only Windows and OpenVMS), a list of directory names and an optional filename. Constants

Table 14.3. Constants of system.Path

Name Description GUESS NATIVE UNIX VMS WINDOWS

Class Properties current

String current ; home

String home ; roots

String roots ; null

String null ; pathSeparator

String pathSeparator ; separator

String separator ;

202 system temp

String temp ; Class Methods expand

String expand(String Path);

Expands all environment variables contained in the path. On Unix, a tilde as first character in the path is replaced with the path to user's home directory. find

Array find(String PathList, String Name);

Searches the file with the given name in the locations (paths) specified in pathList. The paths in pathList must be delimited by the platform's path separator (see pathSeparator()). A relative path may be given in name. If the file is found in one of the locations, the complete path of the file is stored in the path given as argument and true is returned. Otherwise false is returned and the path argument remains unchanged.

This method returns an array with two elements: the first element is a boolean indicating success or failure. The second element is a os.Path object. forDirectory

system.Path forDirectory(String Path);

Creates a path referring to a directory. Constructor

Path(Boolean Absolute);

Creates an empty absolute or relative path.

Path(String Path);

Creates a path from a string.

Path(String Path, Integer Style);

Creates a path from a string.

Path(String Path,

203 system

Integer Style);

Creates a path from a parent path and a relative path. The parent path is expected to reference a directory. The relative path is appended to the parent path.

Path(String Path, system.Path Relative);

Creates a path from a parent path and a relative path. The parent path is expected to reference a directory. The relative path is appended to the parent path.

Creates a new Path object. Properties basename

String basename ;

Set/Gets the basename (the filename sans extension) of the path. depth

Integer depth ;

Returns the number of directories. device

String device ;

Gets/Sets the device name. Setting a non-empty device automatically makes the path an absolute one. directoryName

String directoryName ;

Gets the directory name of the path (it's the same as calling directories with depth - 1) extension

String extension ;

Gets/Sets the file extension. filename

String filename ;

Gets/Sets the filename.

204 system node

String node ;

Gets/Sets the node name. isAbsolute

Boolean isAbsolute ;

Returns true when the path is absolute. isDirectory

Boolean isDirectory ;

Returns true when the path is a directory. isFile

Boolean isFile ;

Returns true when the path is a file. isRelative

Boolean isRelative ;

Returns true when the path is relative. parent

system.Path parent ;

Returns a path referring to the path's directory. Methods absolute

system.Path absolute();

system.Path absolute(system.Path Path);

Makes the path absolute taking the given path as base.

system.Path absolute(String Path);

205 system

Makes the path absolute taking the given path as base.

Makes the path absolute taking the current path as base. append

system.Path append(system.Path Path);

system.Path append(String Path);

Appends the given path assign

system.Path assign(system.Path Path);

Assigns the given path.

sytem.Path assign(String Path);

Assigns a string containing a path in native format.

system.Path assign(String Path, Integer Style);

Assigns a string containing a path. clear

clear();

Clears all components. directory

String directory(Integer N);

Returns the N'th directory in the directory list. If N == depth(), returns the filename. makeAbsolute

system.Path makeAbsolute();

Makes the path absolute if it is relative. The current working directory is taken as base directory.

system.Path makeAbsolute(system.Path Path);

Makes the path absolute if it is relative. The given path is taken as base.

206 system makeDirectory

system.Path makeDirectory();

If the path contains a filename, the filename is appended to the directory list and cleared. Thus the resulting path always refers to a directory. makeFile

system.Path makeFile();

If the path contains no filename, the last directory becomes the filename. makeParent

system.Path makeParent();

Makes the path refer to its parent. parseDirectory

system.Path parseDirectory(String Path);

system.Path parseDirectory(String Path, Integer Style);

The resulting path always refers to a directory and the filename part is empty. popDirectory

popDirectory();

Removes the last directory from the directory list. pushDirectory

pushDirectory(String Path);

Adds a directory to the directory list. resolve

system.Path resolve(system.Path Path);

Resolves the given path agains the current one. If the given path is absolute, it replaces the current one. Otherwise, the relative path is appended to the current path. toString

207 system

String toString();

Returns a string containing the path in native format.

208 system

Name system.Pipe — This class implements an anonymous pipe.

Pipes are a common method of inter-process communication - on Unix, pipes are the oldest form of IPC.

A pipe is a half-duplex communication channel, which means that data only flows in one direction. Pipes have a read-end and a write-end. One process writes to the pipe and another process reads the data written by its peer. Read and write operations are always synchronous. A read will block until data is available and a write will block until the reader reads the data.

Pipes are used through a system.PipeOutputStream or system.PipeInputStream. Constructor

Pipe();

Creates a new Pipe object.

209 system

Name system.PipeInputStream — An input stream for reading from a Pipe.

Prototype: system.InputStream

Constructor

PipeInputStream(system.Pipe Pipe);

Creates the PipeInputStream with the given Pipe.

210 system

Name system.PipeOutputStream — An output stream for writing to a Pipe.

Prototype: system.OutputStream

Constructor

PipeOutputStream(system.Pipe Pipe);

Creates the PipeOutputStream with the given Pipe.

211 system

Name system.Process — This class provides methods for working with processes.

Constructor

Process(String Command, Array Args, system.Pipe inPipe= null, system.Pipe outPipe= null, system.Pipe errPipe= null);

Creates a new Process object. The given arguments are passed to the command on the command line.

If inPipe, outPipe or errPipe is non-null, the corresponding standard input, standard output or standard error stream of the launched process is redirected to the system.Pipe. os.PipeInputStream.class or system.PipeOutputStream can be used to send receive data from, or send data to the process.

The same system.Pipe can be used for both outPipe and errPipe. After a system.Pipe has been passed as inPipe, only write operations are valid. After a system.Pipe has been passed as outPipe or errPipe, only read operations are valid. Important It is forbidden to pass the same pipe as inPipe and outPipe or errPipe. Properties pid

Integer pid ;

Returns the process id Methods wait

Integer wait();

Waits for the process to terminate and returns the exit code of the process.

212 system

Name system.TemporaryFile — The TemporaryFile class helps with the handling of temporary files.

Prototype: system.File

A unique name for the temporary file is automatically chosen and the file is placed in the directory reserved for temporary files (see temp). Obtain the path by calling the path() method (inherited from File).

The TemporaryFile class does not actually create the file - this is up to the application. The class does, however, delete the temporary file - either in the garbage collector, or immediately before the scripts terminates. Class Properties tempName

String tempName ; Constructor

TemporaryFile();

Creates a new system.TemporaryFile object. Methods keep

keep();

Disables automatic deletion of the file when the object is garbage collected. keepUntilExit

keepUntilExit();

The file will be deleted when the script ends. collected.

213 system

Name system.TextInputStream — An input stream for reading text from a file.

Prototype: system.FileInputStream

Unlike system.FileInputStream which opens a file in binary mode, TextInputStream can handle line endings and files with different encodings. GLUEscript uses UTF-8 internally. Note A stream is automatically closed when the object is garbage collected. When this is to late, you need to call the close method. Note Because this class uses a conversion stream internally, it's not possible to use seek and pos. Constructor

TextInputStream(String Filename, String LineEnding, core.Encoding Encoding= null);

Creates a new TextInputStream object. When the file doesn't exist null is returned. When no LineEnding argument is passed, the default of the operating system is used. When no encoding is specified, TextInputStream will try to detect the encoding based on the BOM. When a BOM is in the file, TextInputStream will discard it. Note Be carefull when a BOM is in the file: don't use seek to set the pointer to the beginning of the file, because when you start reading again you will read the BOM characters. Methods close

close();

Closes the stream. readAll

String readAll();

Reads all text. readLine

String readLine();

214 system

Returns the next line from the stream. The new line characters are not included.

215 system

Name system.TextOutputStream — An output stream for writing text to a file.

Prototype: system.FileOutputStream

Unlike system.FileOutputStream which opens a file in binary mode, TextOutputStream can handle line endings and can convert the file to another encoding. (GLUEscript uses internally UTF-8). Note A stream is automatically closed when the object is garbage collected. When this is to late, you need to call the close method. Note Because this class uses a conversion stream internally, it's not possible to use seek and pos. Constructor

TextOutputStream(String Filename, String LineEnding, core.Encoding Encoding= null, Boolean Truncate= true);

Creates a new TextOutputStream object. When no LineEnding argument is passed, the default of the operating system is used. When Truncate is true (default), the file will be truncated. Methods close

close();

Closes the stream writeLine

writeLine(String Text);

Writes the text to the file and appends a new line.

216 Chapter 15. tpl Introduction

TPL is a template engine for generating (X)HTML, XML, text, ... It is based on libtemplate [http:// www.lazarusid.com/libtemplate.shtml].

A template engine allows you to separate the logic of your application from the view. A template consists of literal text and elements. An element will be replaced by a value set in the template engine. When a template is parsed, the elements are replaced with their set values, and the parsed template is stored in an new element. The developer has the option of replacing any existing value for the template, or appending to the existing value. Template files

A template file can contain multiple templates. Each template must be enclosed between