Reference Manual

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Product and documentation by Aparajita Fishman

Copyright and Trademarks

All trade names referenced in this document are the trademark or registered trademark of their respective holder.

Active4D is copyright Aparajita Fishman and Victory-Heart Productions.

4th DIMENSION, ACI, ACI US, and 4D Compiler are registered trademarks and 4D, 4D Server, 4D Client, and 4D Insider are trademarks of ACI/ACI US, Inc. or 4D, Inc.

Windows is a trademark of Microsoft Corporation.

Macintosh and Mac OS are trademarks of Apple Computer, Inc.

JavaScript and Java are trademarks of Sun Microsystems, Inc.

Acknowledgements

First of all, thanks to the makers of PHP for giving me the vision of a better way.

Thanks to the client who asked me to generate every single character of HTML in 4D code, which inspired me to come up with a better way.

Thanks to Mike Erickson for his ongoing inspiration and support and for convincing me that Active4D was worth doing. I hope he is right.

Thanks to Steve Willis and Jim Crate of Deep Sky Technologies for their invaluable assistance with the web server.

Thanks to all of the users for their feedback and encouragement.

And thank you to David Adams for so kindly including a chapter about Active4D in "The 4D Web Companion" and for allowing me to include his HTTP chapter with these docs.

Table of Contents

Acknowledgements ii

Table of Contents iii

Introduction 1

What is Active4D? 1

HTTP Web Server 1

Server-Side 2

HTML-Embedded 2

Scripting Language 2

Development Environment 3

An Example 4

What Can Active4D Do? 4

Database and Protocol Support 5

A Brief History of Active4D 5

Installation 7

Plugin Archive Contents 7

Into MAC4DX/WIN4DX Folder 7

Documentation Folder 8

Shell Archive Contents 8

Main Folder 8

Active4D Folder 8

Active4D Uploads 9

MAC4DX/WIN4DX Folder 9

"web" Folder 9

"web decoy" Folder 9

Documentation Archive Contents 9

Demo Archive Contents 9

Key Files 10

Key File Installation 10

Key File Info 10

Version Checking 10

License Types 11

Timeouts 11

Trial License 11

Developer License 11

Deployment License 11

OEM License 12

Installation Options 12

Starting a Database from Scratch 12

Installing into a Non-Active4D Database 13

Updating an Existing Active4D 2.0 Database 14

Moving an Active4D Database from 4D 6.5 to 4D 6.7+ 14

Post-Installation Configuration 15

Configuring for 4D 15

Configuring for ITK 15

Configuring 4D Client as a Web Server 16

Using the Pre- and Post-Execute Hooks 17

Pre-Execute Hook 17

Post-Execute Hook 18

Configuration 19

The Active4D Directory 19

Libraries and the Active4D Directory 19

Configuration Files 20

The Default Directory 20

Path Format 20

The Standard Search Path and Path Lists 22

Active4D.ini 22

ExtensionMap.ini 24

Realms.ini 24

VirtualHosts.ini 24

Deprecated Plugin Configuration Commands 24

Security 27

Source Code Security 27

Web Server Security = Source Code Security 27

Circumventing Active4D 27

The Whole Fortune 500 Can't Be Wrong 28

Source Code Encryption 29

Potential Attacks 29

Executing/Accessing Non-Web Files 29

The "safe script dirs" Config Option 29

Misusing Document Commands 30

The "safe doc dirs" Config Option 30

Spoofing Form Variables 30

The "auto create vars" Config Option 31

Uploading Huge Files 31

HTTP Server 33

What Is a Web Server? 33

Active4D + TCP Layer = Web Server 34

Web Server Issues 34

HTTP Fundamentals 35

Active4D HTTP Request Handling 35

Executable vs. Non-executable Files 35

Request Header Parsing 36

POST Handling with the 4D 6.5 Web Server 37

POST Handling With the 4D 6.7+ Web Server 37

POST Handling With Stream-based TCP Layers 37

File Upload Handling With 4D's Web Server 38

Executable Request Handling 38

Non-Executable Request Handling 40

Configuration 41

Active4D.ini 41

ExtensionMap.ini 43

User Authentication 44

Realms.ini 45

Virtual Hosting 46

VirtualHosts.ini 47

A Virtual Host Example 47

HTTP Error Handling 48

Invoking Active4D 51

Types of Execution 51

Request Execution 51

A4D Execute <type> request Parameters 51

A4D Execute <type> request 52

A4D Execute BLOB request 56

A4D Execute request 56

A4D Execute stream request 57

A4D Execute 4D request 57

StatusCallback 59

ReceiveCallback 59

Direct Execution 60

Uses for Direct Execution 60

Interpreter 61

Flow of Execution 61

Embedding Source Code 61

Input Parsing 62

Language Syntax 64

Source Code Structure 64

Case Sensitivity 65

Expression-based 65

Comments 65

Identifiers 66

Data Types 66

Compiler Declarations 67

Array Support 67

Pointer support 67

Literals 68

User-defined constants 68

Typing of Values 68

Operators 69

New Active4D Operators 69

Picture Operators 70

Enhanced Operators 70

Control Structures 71

for each/end for each 71

break 71

return 71

continue 71

exit 72

Examples 72

Working with Paths 73

URL-Style Paths 73

Absolute vs. Relative Paths 73

Path Utilities 74

Path Limits 74

Including Other Files 74

Uses of Included Files 75

Including only once 75

Calling 4D Methods 75

Parameter Passing 76

Indirect Method Calls (aka Poor Man's method pointers) 76

Collections 77

Collection Handles 77

Local vs. Global Collections 77

Using Collections 78

Referencing Collection Values 78

Iterating Over a Collection 79

HTTP Data Access 80

Request Data 80

Auto Variable Creation 81

Testing Form Buttons 82

Response Data 83

Working with Character Sets 83

Platform Character Set 84

Output Character Set 84

Output Encoding 85

HTTP Request Decoding 85

Working with Files 85

Error Handling 86

Script Timeout 86

Methods 87

Defining Methods 87

Method Declaration 87

Method Name 87

Method Parameter Declaration 88

Method Parameters 88

Parameter Type 88

Scope 89

Referencing "Global" Local Variables 90

Pass by Reference 90

Default Parameters 91

Returning Values 92

Libraries 95

Library Definition 95

Importing Libraries 96

Load Errors 97

The "lib dirs" Config Option 97

The "lib extension" Config Option 97

Library Namespace 97

Name Resolution 97

Library scope 98

The "global" library 99

Refreshing Libraries 99

The "auto refresh libs" Config Option 99

The "refresh interval" Config Option 100

Differences from Active4D 1.0 100

Event Handlers 103

Modifying the Active4D Library 103

Event Handler Methods 104

On Application Start 104

On Application End 104

On Request 104

On Authenticate 105

On Session Start 106

On Session End 106

On Execute Start 107

On Execute End 107

Command Reference 109

4D Commands 109

4D 6.5 Commands 109

Using a Default Table 109

4D Command List 110

4D Command List (cont.) 111

Active4D Commands 112

Active4D Command List 113

Command Syntax 115

Arrays 116

add element 117

append to array 117

clear array 118

is array 118

join array 119

multisort arrays 120

multisort named arrays 120

resize array 121

SELECTION/SELECTION RANGE TO ARRAY 121

set array 122

Collections 124

collection 125

new collection 125

new local collection 126

new global collection 126

collection to blob 127

blob to collection 127

copy collection 128

merge collections 128

clear collection 129

get collection 129

get collection array 130

get collection array size 131

get collection item 131

get collection keys 132

set collection 132

set collection array 133

is a collection 134

collection has 134

count collection items 135

delete collection item 135

Database 136

Trigger Errors 136

get field numbers 137

get field pointer 137

QUERY 138

QUERY SELECTION 138

SET QUERY DESTINATION 139

Date and Time 140

UTC Commands 140

day of year 141

get utc delta 141

local datetime to utc 141

local time to utc 142

utc to local datetime 142

utc to local time 142

week of year 143

Debugging 144

current line number 145

current method name 145

dump locals 146

write to console 146

Error Handling 147

get error page 148

get log level 148

in error 148

log message 149

set error page 149

set log level 150

File Uploads 151

How File Upload Works 151

Referencing File Uploads 151

The Importance of Filename Extensions 152

Uploads and 4D's Web Server 152

Upload Auto-Deletion 152

copy upload 153

count uploads 153

get upload content type 154

get upload encoding 154

get upload extension 154

get upload remote filename 155

get upload size 155

save upload to field 156

Form Variables 157

Form Variable Items 157

Multiple-choice Form Fields 157

form variables 158

form variables has 158

get form variable 158

get form variable choices 159

get form variable count 160

get form variables 161

count form variables 162

Globals 163

Locking and Unlocking the Globals 163

globals 165

globals has 165

get global 165

get global array 166

get global array size 167

get global item 167

get global keys 168

set global 168

set global array 169

count globals 169

delete global 170

lock globals 170

unlock globals 170

Iterators 171

Using for each 171

Using Iterators 171

Iterator Validity 172

for each/end for each 173

more items 173

next item 174

get item key 174

get item value 174

get item type 175

get item array 175

is an iterator 175

Language 176

call 4d method 177

call method 177

choose 178

define 180

EXECUTE 182

global 182

import 183

include 184

include into 184

longint to time 185

redirect 186

require 186

throw 187

time to longint 187

Math 188

max of 189

min of 189

random between 190

Pictures 191

write gif 192

write jpeg 192

write jpg 193

Queries 194

QUERY/QUERY SELECTION 195

ORDER BY 195

Query Params 196

Query Params Items 196

Duplicate Query Parameters 196

query params 197

query params has 197

get query param 197

get query param choices 198

get query param count 199

get query params 199

count query params 200

build query string 200

Request Cookies 202

request cookies 203

get request cookie 203

get request cookies 203

count request cookies 204

Request Info 205

request info 206

get request info 206

get request infos 206

count request infos 207

Request Value 208

get request value 209

Response Buffer 210

buffer size 211

response buffer size 211

clear buffer 211

clear response buffer 211

get response buffer 212

save output 212

end save output 213

set output charset 214

get output charset 214

set output encoding 215

get output encoding 216

write 216

write blob 217

writebr 218

writeln 218

writep 219

write raw 219

= 220

Response Cookies 221

Cookie Fields 221

Limitations with the 4D 6.7 Web Server 221

response cookies 222

get response cookie 222

get response cookies 223

set response cookie 223

set response cookie domain 224

get response cookie expires 224

set response cookie domain 224

get response cookie domain 225

set response cookie path 225

get response cookie path 226

count response cookies 226

delete response cookie 226

abandon response cookie 227

Response Headers 228

response headers 229

get response header 229

get response headers 229

set response header 230

count response headers 230

delete response header 230

Response Properties 231

get cache control 232

set cache control 232

get expires 232

set expires 233

get expires date 233

set expires date 233

get content type 234

set content type 234

get content charset 234

set content charset 235

Script Environment 236

current platform 237

get license info 237

get time remaining 238

get version 238

parameter mode 239

set platform charset 239

get platform charset 240

set script timeout 240

get script timeout 240

set current script timeout 241

get current script timeout 241

Selecting Records 242

Loading Related Records 242

Configuring Related Record Auto-loading 242

Compatibility with Active4D 2.0.x 243

Examples 243

auto relate 245

FIRST/LAST/NEXT/PREVIOUS RECORD 245

GOTO RECORD 246

GOTO SELECTED RECORD 246

Sessions 247

The Active4D Session Architecture 247

Session ID 247

Session Events 248

When Active4D Sends Session Cookies 248

Session Lifetime 249

Cookieless Sessions 249

Memory Caching of Sessions 250

Session Timeout and Memory Usage 250

Monitoring Memory Usage 251

Session Configuration 251

session 253

session to blob 253

blob to session 253

get session 254

get session array 254

get session array size 255

get session item 255

get session keys 256

set session 256

set session array 257

session has 257

count session items 258

delete session item 258

abandon session 259

session id 259

session internal id 259

session local 260

session query 260

hide session field 260

set session timeout 261

get session timeout 261

get session stats 262

Strings 263

URL Encoding/Decoding 263

String Commands and Multibyte Character Sets 264

capitalize 265

cell 265

compare strings 266

concat 266

enclose 267

first not of 268

first of 268

identical strings 269

last not of 269

last of 269

left trim 270

mac to html 270

param text 271

Position 273

right trim 273

split string 274

String 275

trim 275

url decode 276

url decode path 276

url decode query 276

url encode 277

url encode path 277

url encode query 277

System Documents 278

Document Paths 278

Document Command Enhancements 278

Affected Commands 279

Append document 280

Create document 280

current file 280

current path 281

default directory 281

DELETE FOLDER 282

directory of 282

directory separator 282

extension of 283

filename of 283

get root 283

native to url path 284

Open document 284

RECEIVE PACKET 284

requested url 285

SEND PACKET 285

SET DOCUMENT POSITION 285

url to native path 286

Timestamps 287

Timestamp Format 287

Timestamp Time 287

Timestamp Normalization 287

Using Timestamps 288

timestamp 290

add to timestamp 291

timestamp string 291

timestamp date 292

timestamp time 292

get timestamp datetime 293

timestamp year 293

timestamp month 293

timestamp day 294

timestamp hour 294

timestamp minute 295

timestamp second 295

timestamp millisecond 295

User Authentication 296

auth password 297

auth type 297

auth user 297

authenticate 298

current realm 298

Variables 299

defined 300

get local 301

local variables 301

set local 301

type descriptor 302

undefined 302

variable name 303

Plugin Commands 304

Plugin Command List 304

A4D FLUSH LIBRARY 305

A4D Get root 305

A4D GET SESSION DATA 305

A4D GET SESSION STATS 306

A4D GET LICENSE INFO 307

A4D Get time remaining 307

A4D Get version 307

A4D Import library 308

A4D Native to URL path 308

A4D RESTART SERVER 308

A4D SET ROOT 309

A4D STRIP 4D TAGS 309

A4D URL decode path 309

A4D URL decode query 310

A4D URL encode path 310

A4D URL encode query 310

A4D URL to native path 311

Standard Libraries 313

Using the Standard Libraries 313

a4d.web 314
a4d.utils 315
Batch 316
RowSet 317

Enter the RowSet 317

Using RowSets 319

Debugging 323

Standard Library Methods 323

a4d_web 323

dump array 324

dump collection 324

dump form variables 325

dump query params 325

dump request info 325

dump session 325

dump session stats 326

The Session Editor 327

Using the Session Editor 327

The Session Monitor 329

Displaying the Session Monitor 329

Using the Session Monitor 330

The Active4D Debugging Console 332

Using the Debugging Console 332

Filtering Console Messages 333

Error Handling 335

The Default Error Message 335

Using a Custom Error Page 336

The "error page" Option 336

The "set error page" Command 337

Error Page Variables 337

The Active4D Error Log 338

Log Levels 338

Index of Commands 341

ISO Language Codes 349

Named Constants 351

Grouped by Function 351

Alphabetical 353

 

Introduction

Welcome to Active4D! You have chosen the ultimate environment for building world-class web applications with 4D.

What is Active4D?

A dynamic web scripting environment has four layers: a TCP communications layer, an HTTP server layer, a scripting layer, and a database layer. The different layers can be pictured like this:

The HTTP server builds on top of the TCP layer, and the scripting layer builds on top of the HTTP server. The database is in a separate, independent layer.

Active4D is both an HTTP web server and a server-side HTML-embedded scripting language and development environment.

That's a mouthful. Let's break down the sentence and look at what it means.

HTTP Web Server

An HTTP (HyperText Transfer Protocol) web server is a piece of software that receives HTTP requests, processes those requests and sends an appropriate response to the origin. In essence, this is what a web server does.

4D's built-in web server handles TCP communications and handles most of the HTTP protocol.

Internet Toolkit , better known as ITK, is just what it says -- not an HTTP server, but a toolkit that allows you to write an HTTP server. ITK comes with samples which implement a web server well for most purposes.

HTTP Server Deux is a 4D component that implements a full-fledged HTTP server on top of 4D Internet Commands or ITK.

Active4D implements a full-fledged HTTP server in a plugin. As an HTTP server, it offers:

Ease of setup
  • Active4D is ready to run out of the box. There is no complicated setup needed.
Speed
  • As a plugin, Active4D always runs at native compiled speed, even in an interpreted database. This can mean huge gains in productivity during development.
Features
  • Active4D adds a wealth of advanced features like Virtual Hosting that offer you some of the benefits of dedicated web servers like WebStar.
Server-Side

Scripting languages like JavaScript and Java download their source code to the client browser and execute it there. Active4D, on the other hand, is executed on the server and the source code is removed before the page is sent to the client.

HTML-Embedded

Before the advent of Active4D, to create a dynamic web site using 4D you had to generate all or part of the HTML within 4D methods.

Active4D turns that model inside out -- dynamic HTML generation is directly embedded inside the HTML page.

4D's semi-dynamic tag system, while providing some of the benefits of embedded scripting, still requires you to write many, many 4D methods to handle simple tasks like queries and ordering. In Active4D this is handled directly within the web page. In fact, with Active4D all of your application code can (and in most cases should) exist entirely outside of 4D itself.

Scripting Language

To generate dynamic HTML you must have a programming language. Active4D is a full 4D interpreter in a plugin. To program in Active4D you don't need to learn a new syntax or specialized tag language. In many cases you can literally copy 4D code from a method and paste it into a web page to be executed by Active4D.

Active4D supports all 4D data types except for 2D arrays. It implements over 150 of the most important 4D commands, as well as over 200 new commands which add unmatched power to your web application.

Active4D also adds several often-requested extensions to the language, such as the break and return keywords, as well as pass-by-reference.

Development Environment

Active4D comes with a plethora of built-in debugging tools, both on the client side and on the 4D side. In conjunction with all of the other features Active4D provides, there simply is no more powerful or more productive web development environment for 4D, period. Nothing else comes close.

The fully dynamic, embedded scripting implementation in Active4D is the cutting edge of dynamic web technology. And by using this approach you are in good company. Here are just a few little web sites that use fully dynamic embedded scripting:

barnesandnoble.com
capitalone.com (Visa)
compaq.com
dell.com
deltaairlines.com
firstusa.com (Visa)
gateway.com
geico.com (insurance)
homedepot.com
macconnection.com / pcconnection.com
macmall.com
macwarehouse.com
microsoft.com
sears.com
staples.com
walmart.com

My research shows that over 75% of the Fortune 500 uses dynamic embedded scripting languages in their corporate, client and e-commerce web sites. And the numbers are growing.

An Example

Here's a simple example of what an Active4D page looks like:

<html>

<body>

Here are 5 good reasons to use Active4D:<br>

<%

for ($i;1;5)

writebr("It rocks!")

end for

%>

</body>

</html>

Note that the code is fully embedded in the page, and that except for the writebr command, which writes an expression to the HTML page, the embedded code is 4D code.

During execution, Active4D passes straight HTML through, executes everything inside the <% %> tags, and spits out the following:

<html>

<body>

Here are 5 good reasons to use Active4D:<br>

It rocks!<br>

It rocks!<br>

It rocks!<br>

It rocks!<br>

It rocks!<br>

</body>

</html>

The source code has been replaced with the output of the Active4D code. You can find out more about programming with Active4D in See Interpreter

What Can Active4D Do?

Active4D can do anything that 4D can do in the context of a web page, plus quite a few tricks that would be time-consuming if not impossible to implement in 4D.

If Active4D's commands don't fit the bill, you can write methods and libraries of methods completely within Active4D, using plain text files. And if you need to use a command or plugin that is not in Active4D's language, you can call any 4D method, passing parameters of any type and receiving a result of any type.

Primarily, however, Active4D is designed to act as a conduit between the database and the web page. As such, it excels at the following essential tasks:

  • Collecting information from forms and queries for easy access within your web application
  • Managing user sessions
  • Querying and manipulating data without having to write specialized 4D methods
  • Handling file uploads
  • Formatting text for output to HTML
  • Handling character set issues
Database and Protocol Support

Active4D comes with built-in support for 4D's built-in database engine. You could, without much work, write wrapper methods for the various connectivity plugins that would allow you to work with other databases such as Sybase and Oracle.

In addition, you could also easily write method wrappers around the 4D Internet Commands to allow you to access other internet protocols like SMTP.

A Brief History of Active4D

Several years ago I had the occasion to use another dynamic embedded scripting language called PHP. I was amazed at the power it provided, and more importantly I realized the advantages of the embedded scripting model.

A little later I was hired to work on a vertical market, web-based application that used 4D. I was asked to add a new module to the existing application. To my amazement, this application (which used NetLink) generated every single character of HTML programmatically in a 4D method. This was before 4D offered its web tag system.

Having been exposed to embedded scripting, I quickly saw that this was a fundamentally flawed approach, and I said to myself, "There has to be a better way." So I set about creating one.

I never intended to create Active4D -- it just sort of happened. A few months after I began with a simple 4D-based parser that replaced variable and field names, I had a full working 4D interpreter in a plugin.

A few features and a few months later, Active4D 1.0 was released. That was November of 2000. Since then I had a chance to use Active4D heavily in web projects, and decided it was time to fill in all of the holes in its feature set.

I systematically went down the list of every important feature in the world's leading embedded scripting language, Microsoft's Active Server Pages, also known as ASP (from which Active4D takes its name), and implemented each and every one. And wherever possible I added a few features that ASP doesn't have.

The result is what you see here: Active4D 2.0, the ultimate 4D web environment.

 

Installation

  1. Installation of Active4D is a fairly simple matter and should take no more than a few minutes.

First you must of course download the appropriate files from http://aparajitaworld.com/products/Active4D/downloads.html . Because Active4D supports a number of different platforms and environments, the downloads are organized so that you can easily mix and match just what you need.

There are four elements to Active4D:

Plugin
  • You must choose the platform on which you will run Active4D (Mac or Windows) and download the appropriate archive.
Shell
  • You must choose the appropriate shell for the environment in which you are running Active4D. The shell acts as a conduit between the TCP/IP communications layer and Active4D.
Documentation
  • This manual is part of the plugin archives, but you may also download the documentation separately.
Demo
  • This 4D 6.8 database and web site demonstrates many of the key techniques you will use with Active4D.

Once you have downloaded one of the above archives, you will need to decompress it. Mac archives are in Stuffit 5 format, so you will need Stuffit Expander 5 or better to decompress them. Stuffit Expander is free and readily available from www.aladdinsys.com . Windows archives are in Zip format. There are millions of free Zip expanders available for Windows.

Plugin Archive Contents

Once you decompress the plugin archive, you will find a single folder.

Into MAC4DX/WIN4DX Folder

This folder contains the Active4D plugin itself, which must be placed either in a local or shared MAC4DX folder (on Macintosh) or WIN4DX folder (on Windows).

When you download the ITK or TCP Server Deux shells, there will be other files and plugins which support those shells. They should be placed together with Active4D in a 4DX folder.

Documentation Folder

This folder contains important release information as well as this manual.

Shell Archive Contents

Once you decompress the shell archive, you will find a number of files and folders.

Main Folder

The main folder contains a complete working shell which illustrates how to integrate Active4D with either 4D's web server, ITK, or TCP Server Deux. In addition, the shell contains the forms and methods which implement the server-side debugging features of Active4D.

Active4D Folder

This folder contains libraries and config files which are used by Active4D.

a4d_utils.a4l
  • An Active4D library which implements various useful non-web-related utilities.
a4d_web.a4l
  • An Active4D library which implements various useful web-related utilities. This library makes use of the a4d_utils library.
Active4D.a4l
  • A special Active4D library that contains global event handlers for your application. For more information on event handlers, see See Event Handlers
Active4D.ini
  • A config file which sets most of the options in Active4D.
ExtensionMap.ini
  • A config file which maps filename extensions to Macintosh file types and MIME types.
Realms.ini
  • A config file which maps portions of a URL to security realms.
VirtualHosts.ini
  • A config file which provides the routing table for virtual hosts. For more information on virtual hosts, see See Virtual Hosting.

For more information on libraries, see See Libraries For more information on config files, see See Configuration

Active4D Uploads

This empty folder is used by Active4D to temporarily store uploaded files.

MAC4DX/WIN4DX Folder

This folder contains plugins which are necessary to use Active4D (in addition to the Active4D plugin).

"web" Folder

This folder is where the pages of your web site will go.

"web decoy" Folder

This purposely empty folder is a critical security device which is explained in See Circumventing Active4D.