TweetFollow Us on Twitter

REALbasic CGIs

Volume Number: 16 (2000)
Issue Number: 4
Column Tag: Programming

REALbasic CGI’s

by Diana Cassady
Contributiong Editor, Erick Tejkowski

About REALbasic

REALbasic is an object-oriented implementation of the BASIC programming language for Mac OS, and is available from REAL Software at <http://www.realsoftware.com>. It's a language that can be mastered, even by a novice, in days. Its drag and drop builder allows programmers to create stand alone applications with windows, menu bars, text areas, radio buttons, checkboxes, and all the usual user interface features found in commercial programs that have taken months to write. REALbasic programs can send and receive Apple events to communicate with other scriptable programs, including webservers. REALbasic can be used to create a customized, stand alone CGI with an interface for webmasters to store program preferences. Real time logging results can also be displayed in a REALbasic interface.

In this article, I present a framework for writing CGI's for Mac OS Web servers using the REALbasic environment. It is assumed the reader is already familiar with the basics of authoring CGI's.

CGI Basics

A CGI for Mac OS needs to accomplish three main tasks:

  1. Accept the Apple event from the web server.
  2. Process the data contained in the Apple event.
  3. Return an Apple event to the web server containing the requested data.

Accepting the Apple Event

REALbasic contains a built-in event handler to accept Apple events within a class. The application contains an event called HandleAppleEvent. This handler will contain the code to interpret incoming Apple events.

Start a new REALbasic program by opening your REALbasic application. Create a new class by choosing New Class from the File menu. Access the properties of this new class by highlighting it in the project window and choosing Show Properties under the Window menu. Choose Application beside Super in the new class properties. This application class will be the location of the Apple event handler. The new class' default name is Class1.

Double-click Class1 in the project window. The first item on the left of the Class1 window is Events. Double-click on Events. A list of events will appear. The last event in the list is HandleAppleEvent. Double-click on HandleAppleEvent to open the code window.

Three variables are provided within this handler: event as AppleEvent, eventClass as String, and eventID as String. The eventClass and eventID are used to identify the Apple event. The Apple event coming from the web server will have an eventClass of WWWOmega. The Omega sign is made with command z on the keyboard. The eventID will be sdoc. The variable event contains the data. The data coming from the web server is broken up into parameters. A list of these parameters can be found at <http://www.biap.com/DataPig/mrwheat/cgiParams.html> courtesy of Biap Systems, Inc. These parameters are for the WebStar webserver, but are common to most Macintosh webservers. A four character keyword identifies each parameter within the Apple event. Form data passed using the post method in a form action is identified by the keyword post. The event variable contains all the parameters, including the post parameter. To isolate the post parameter within the event variable, use event.Stringparam("post"). This function provides the form data as one long strong.

The code in the Apple event handler should verify that the incoming Apple event is the proper type. A string variable also needs to be initialized to contain the isolated form data.

Dim post_args as string

if eventClass="WWWOmega" and eventID="sdoc" then
	post_args=event.Stringparam("post")
end if

Sending a Reply

The program can now accept the Apple event and isolate the data it contains. If the program wanted to collect raw form data and return a simple thank you to the user, no further code is necessary except for a reply. The reply statement sends a string back to the server which is then returned to the browser. The return string should contain a header and HTML to be returned to the user. You may want to build the return_string in pieces to make your code easier to read. The carriage Return Line Feed variable stands for control return line feed.

crlf=chr(13)+chr(10)
return_string="HTTP/1.0 200 OK" + crlf + "Server: WebSTAR/2.0 ID/ACGI" 
 	+ crlf + "MIME-Version: 1.0" + crlf + "Content-type: text/html" + crlf + crlf
return_string=return_string+"<html><body><h2>Thanks for submitting your info.
	</h2></body></html>"
event.ReplyString=return_string

This much code will function as a CGI. It won't do anything with the form data, but it will accept and respond to the Apple event and the web server will return the response to the browser.

The CGI will be much more useful if it can work with the information sent from the web server. Some of this information can be dealt with as is. For example, you could get the username of a user who has logged into a password protected realm by using the keyword user instead of post. You could also get the name of the web browser they're using with the keyword Agnt.

Dim the_user as string
Dim the_agnt as string

if eventClass="WWWOmega" and eventID="sdoc" then
	the_user=event.Stringparam("user")
	the_agnt=event.Stringparam("Agnt")
	event.ReplyString="Hi " + the_user + ". I see you're using " + the_agnt + "."
end if

If-then statements can be incorporated to send back different replies depending on the data contained in the various Apple event parameters, or other data from the system brought in by REALbasic functions such as date and time of day.

Data Processing

Form parameters require more processing before the contents of the form can be interpreted. Form parameters are sent as a string with field names and values delimited with equal signs and ampersands. Spaces are represented by either "+" or encoded as "%20" (the hexidecimal value for a space character) depending on the browser. A typical form containing field names first name, last name, address and phone might look like this:

first+name=Joe&last+name=Cool&address=123+Summer+Brook+
Lane&phone=555-1212

Field and value pairs are divided by ampersands and the field names are separated from the value pairs by equal signs. Separating the field and value pairs and isolating the values is the first step in decoding form data.

Several variables need to be defined for this process:

Dim post_args, one_field, field_value, field_label as string
Dim num_fields, x_field as integer
Count the number of fields on the form.
num_fields=CountFields(post_args, "&")
Use a For Next loop to process every field.
For x_field=1 to num_fields
	one_field=NthField(post_args, "&", x_field)
	field_label=NthField(one_field, "=", 1)
	field_value=NthField(one_field, "=", 2)
Next

The first line in the loop isolates a field name and value pair. The second line isolates the field name of that pair. The third line isolates the value.

If the form data consisted of one word field names and one word options with no special characters then no further processing would be needed, but most likely, the data contains spaces and other encoded special characters.

Plus signs need to be replaced with spaces within each isolated field and field label:

the_field=ReplaceAll(the_field, "+", " ")

A percent sign within the field means that it still contains encoded characters. Use the REALbasic inStr() function to get the position of the first percent sign in the string. If zero is returned, the string does not contain a percent sign. There is nothing more to decode within the isolated field.

loc_hex=inStr(a_deplus, "%")

If a value greater than zero is returned, a percent sign exists. Use the REALbasic Mid() function to isolate the character pair after the percent sign.

a_hex=Mid(a_deplus, loc_hex+1, 2)

The two characters following the percent sign are the hexadecimal version of the original character. They need to be converted to their ascii equivalent before the chr() function can be used to restore them to their original identity.

To convert the characters to their ascii equivalent, convert each to a number, multiple the first number by sixteen, and add the result to the second number.

Each character will be zero through nine or A through F as a string. Zero through nine can be taken at Its face value. A through F corresponds to the values ten through fifteen. Use the left() and right() functions to isolate each character of the pair.

char1=left(a_hex, 1)
char2=right(a_hex, 1)

Use a case statement to map the appropriate numbers to the characters.

Select Case char1
Case "0"
	num1=0
Case "1"
	num1=1
End Select

Include case statements for numbers zero through nine mapping to zero through nine and letters A through F mapping to ten through fifteen. The resulting num1 will be the ascii equivalent of the first character. Repeat the process for the second character.

Select Case char2
Case "0"
	num2=0
Case "1"
	num2=1
End Select

Multiply num2 by sixteen and add that to num1 to get the ascii equivalent of the encoded character.

ascii_equiv=(num1*16)+num2

Convert the ascii equivalent back to the original character using the REALbasic chr() function.

de_hex=chr(ascii_equiv)

Plug the decoded character back in to the field in place of the percent sign and character pair.

the_field=ReplaceAll(the_field, "%"+a_hex, de_hex)

So far, only the first instance of an encoded character in the field has been addressed. The ReplaceAll() function has eliminated all occurances of that encoding within the field, but there may still be other encoded characters that need to be sent through this process. Every encoded character will start with a percent sign. A while loop should be used to send the field through the process until inStr(a_deplus, "%") is no longer greater than zero.

Making the Code Efficient

Repetitive code may be eliminated with subroutines. Subroutines are stored as methods in REALbasic programs. The case select code that converts a character to zero through fifteen would be a good piece of code to include as a subroutine. One set of case statements could accept a character and return a numeric value.

Define a new method in the class by choosing New Method under the Edit menu. A window appears with fields for name, parameters, and return type. Name the new method with a simple one word description like Dehex. This method accepts one character to convert to a numeric value. The character being accepted is the parameter for the method. Define that parameter in the blank provided. Include the data type.

char as string

The method returns a numeric value. Integer can be chosen to describe this value as the return type by using the pop down menu to the right of the return type field.

Enter the select case statement in the method. Send char1 and char2 through the subroutine to get num1 and num2 without wasteful code repetition.

num1=Dehex(char1)
num2=Dehex(char2)

Expanding REALbasic CGI's

This method of decoding can be applied to field names and values in post args and search args. Once field names are decoded, they may be referred to in if-then statements to format and arrange their corresponding decoded field values. Decoded data may be set to variables and sent to a text file or a scriptable application for further processing and storage. Results containing decoded data may be returned to the user to assure them that their information has been received.

Code Shortcut

The complex code for decoding search and post arguments need not be written from scratch. A code shell is available for download on the site index page of the VivaLaData web site at <http://www.vivaladata.com>.

Conclusion

If you happen to run across a web automation task for which you have no cgi, or if you're already running an applescript application as a cgi, you should consider using REALbasic to accomplish your goal. Several users have reported that REALbasic cgi's performed faster than their existing applescript cgi's.

REALbasic cgi's can be used to interface with scriptable programs for which no commercial cgi's have been developed. REALbasic is also a quick way for shareware authors to provide a cgi for their scriptable applications. In addition to working with other applications, REALbasic provides lots of built in functions for sending and receiving mail as well as other network protocols and data processing functions.

If you want to add a new function to your Macintosh web site, but feel a $500+ commercial solution is overkill, REALbasic's flexible, rapid development environment and reasonable price tag may be just the solution for you.


Diana Cassady is a freelance consultant in Danbury, Connecticut. Her web site is http://www.vivaladata.com. She can be reach at diana@vivaladata.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.