Table of Contents

 

2. Turbine Variables and DataSets

This chapter introduces Turbine Variables and DataSets, which are the two ways of integrating data from the PHP Interface into the media templates - for example to specify an image to be loaded or to provide values into a Flash component.

 

 

 
Variables: What, Where and When

A Turbine variable allows you to define a value once and then use it multiple times on distinct places of loaded templates. Variables can be directly defined on the PHP script, loaded from database queries or they can be loaded from local or remote HTTP locations in a simple name=value pair format. After being defined, Turbine variables can be used on Flash and MML templates, and can be published into Flash Action Script variables, arrays or associative arrays.
Turbine variables are server-side - they are defined and used at server time, and are different from Flash Action Script variables (although they can be easily published into Action Script).
So, variables are basically a name-value pair - please have the following in mind when working with Turbine variables:

  • Variable names must be in the form {variable}, with the name enclosed between two curly brackets - for example {name}, {address}, {job}.
  • Variable names are case-insensitive - the variables {name} and {Name} and {NAME} can be used and refer to the one and same variable and value.
  • Naturally, variables can only be used after being defined, otherwise they will not be expanded.
  • The variable names must have a maximum of 52 characters. The allowed characters for a variable name are: all letters and numbers, plus the _ . , and $ characters.
  • Turbine variable values can have any size (machine memory permitting).

 

Using Variables


Variables can be used in most places of Flash or MML templates -  each instance of a variable will be replaced by the respective value.
For example suppose you have a Flash .swf template and define a variable named {Person} to have the value Mathilda - if you have a static or dynamic text block with this text: 

{Person} is nice. I once saw {Person} on the market.

when the Flash .swf template is loaded, the text block that includes this variable will be expanded into: 

Mathilda is nice. I once saw Mathilda on the market.

 
You can also use variables on MML templates, inside MML commands: 

<Image src="{Person}.jpg">

At generation-time this will expand into:

<Image src="Mathilda.jpg">

producing the desired behavior. Another example:

<Text>{Person}</Text>

will expand to: 

<Text>Mathilda</Text>

 
In JavaScript, for example a getURL:

getUrl("{Person}.htm"); 

will turn into: 

getUrl("Mathilda.htm");

 
What if you're using variables in an MML template and the variable's value contains forbidden XML characters, like the < or > characters? On this case you can have Turbine automatically XML-escape the variable values by using the syntax {&variable} - for example:

<Text>{&Person}</Text>

On this case, any special XML characters contained in the value of the {Person} variable would be conveniently escaped into XML entities - for example a < character would be expanded into a &lt; escape. Use this syntax if you expect the variable value to contain any of these forbidden XML characters. Note that this is only an issue on MML templates - Flash templates do not have any problem with special XML characters.

 

Defining variables

Before being used, Turbine variables need to be defined - they can be directly defined through the PHP Interface, for example:

$turbine->setVar("Person", "Mathilda");

Variables can also be defined by loading from a text file with the name=value format, with one definition per line:

Variable = value
Variable = value
...

Besides one variable=value pair per line, this file can also include comment lines (which will be ignored), that start by the hash (#) character, for convenience purposes.

Loading a such a file with variable definitions can be done on the PHP Interface like this:

$turbine->loadVar("varfile.txt");

Since they can be loaded from remote HTTP locations, you can also do:

$turbine->loadVar("http://example.com/getvars.php?id=2004");

Turbine Variables can also be defined or loaded inline in Flash or MML templates, by using the <Var> MML tag - for example to directly define variables inside MML:

<Var>
  Variable = value
  Variable = value
  Variable = value
</Var>

Or to load from an external variables file, right from MML templates:

<Var src="varfile.txt"/>
<Var src="http://example.com/getvars.php?id=2004"/>

 

Publishing to Flash Action Script

If you intend to use Turbine solely to generate Adobe PDF documents then you can skip this subsection because scripting is not exported to PDF.

Turbine variables, which live at the server-side, can be published into the client-side as Flash Action Script variables in a multitude of useful ways - to simple Flash Action Script variables, arrays and associative (named) arrays. As with other features, this functionality is both available on the PHP Interface and as an MML tag. On the PHP Interface we can do:

$turbine->publishVar("person,address");

The above would use the values of the {person} and {address} Turbine variables, to create two Flash Action Script variables named person and address. These Flash Action Script variables would then be available, after movie generation, when the movie is played on the client. The same can be accomplished with this MML tag:

<PublishVar name="person,address"/>

 

Special Variables

Turbine automatically defines a number of special, utility variables for information like random numbers, current time and date. The following special variables can be used:

Time:

Variable Description Formatting
{Time.Year} The current year yyyy (ex. 1999)
{Time.Year2} The current year yy (ex. 99)
{TimeMonth} Current month 1 - 12 m or mm (ex. 2)
{Time.Month0} Current month 01 - 12 always mm, left-pads with 0 (ex. 02)
{Time.MonthName} January, February ... -
{Time.WeekDay} Day of the week, between 1 and 7 d
{Time.WeekDayName} Sunday, Monday... -
{Time.Day} Day of the month 1 - 31 d or dd (ex. 4)
{Time.Day0} Day of the month 01 - 31 DD left-pads with 0 (ex. 04)
{Time.Hour} Hour 0 - 23 h or hh (ex. 8)
{Time.Hour0} Hour 00-23 hh left-pads with 0 (ex. 08)
{Time.HourAmPm} Hour 00 - 11 hh left-pads with 0 (ex. 08)
{Time.AmPm} Am or Pm, depending on actual time tt (ex. Am)
{Time.Minute} Current minute 0 - 59 m or mm (ex. 7)
{Time.Minute0} Current minute 00 - 59 always mm left-pads with 0 (ex. 07)
{Time.Second} Current second 0 - 59 s or ss (ex. 57)
{Time.Second0} Current second 00 - 59 Ss left-pads with 0 (ex. 57)
{Time.Canonic} A date in the format:
YYYYMMDDHHMMSS
-

An example of usage of the Time variables: 

    Today is {Time.Day} / {Time.Month} / {Time.Year}
that would display (for example): 
    Today is 1/1/2004

 
Random Values:

Variable Description Formatting
{Random.NewN} Generates a new random number each time it's used. The number has N digits up to a maximum of 6 digits.  N digits
{Random.SameN} Generates a random number that's unique across the whole movie (but different for each movie). The number has N digits up to a maximum of 6 digits. N digits
{Random.NewN[min..max]} Generates a new random number, between min and max. The number is formatted to N digits (up to a maximum of 6 digits).  N digits
{Random.SameN[min..max]} Generates a random number that's unique across the whole movie (but different for each movie), between min and max. The number is formatted to N digits (up to a maximum of 6 digits).  N digits
{Random.NewColor} and
{Random.NewColorAlpha}
Generates a new random color in HTML style with the format RRGGBB or AARRGGBB
-
{Random.SameColor} and
{Random.SameColorAlpha}

Generates a random color in HTML style with the format RRGGBB or AARRGGBB
This color is unique across the whole movie (but different for each movie).

-

An example of usage of the Random variables would be this MML tag: 

    <Image src="ad{Random.Same1}.gif"/>
This command would include a random image, supposing you have images named ad0.gif, ad1.gif, ..., ad9.gif on the same directory as the PHP script.

 

Media and System Global Variables

Besides the Special variables above, Turbine includes two automatically defined families of variables that contain contextual information about the media being generated, as well as a number of system settings and defaults - the Media and System variable families:

Media:

Variable Description Example
{Media.Width} The output native Width in pixels 550
{Media.Height} The output native Height in pixels 400
{Media.FrameRate} The number of frames per second 12
{Media.Color} The native background color to be output #FFFFFF
{Media.NumFrames} Total number of frames 20
{Media.Flash.Version} The numeric version to use when generating Flash 6
{Media.Debug} A boolean value that specifies whether the Turbine Window will be included on the generated media. On Flash, also defines if a native debug tag will be emitted, allowing the movie to be debugged on the browser/Flash editor Yes
{Media.Protect} Whether the output media will be protected - for example when generating Flash this means the "protect from import" flag No
{Media.Compress} If non-zero, specifies the level of output compression, from 1 to 9, with 9 being the best compression. If 0 or "No", no compression is applied. On Flash, applies Flash 6+ compression to the generated movie 9
{Media.Script} The complete URL path to the executed PHP script /turbine/script.php
{Media.Query} The QUERY_STRING used to call the script person=Mathilda
{Media.Location} The path and query string used to request this script - very useful for self-referencing /turbine/script.php?
person=Mathilda
{Movie.Self} The path and query string used to request this script, for use with the GenerateHTMLFirst command, for self-referencing /turbine/script.php?
person=Mathilda&
_media


Media.PDF:

When generating Adobe PDF documents, Turbine also uses these variables:

Variable Description Example
{Media.PDF.Version} The numeric PDF version to use when generating PDF.
For Acrobat PDF viewer 6, use 5, for Acrobat PDF viewer 5 use 4 and so on. Default is version 2, requiring Acrobat PDF viewer 3.
2
{Media.PDF.Title} The title of the PDF document. Visible in the document properties My Title
{Media.PDF.Subject} The subject of the PDF document. Visible in the document properties My Subject
{Media.PDF.Author} The author of the PDF document. Visible in the document properties My Name
{Media.PDF.UserPassword} When defined causes the PDF document to be encrypted. The user must provide this password in order to open it MyPassword
{Media.PDF.OwnerPassword} When defined causes the PDF document contents to be encrypted MyPassword
{Media.PDF.Permissions}

PDF document permissions, a combination of:
noPrinting - the PDF user can't print the document
noChanging - the PDF user can't change the document
noContentCopying - the user can't copy the document contents
noCommenting - the user can't comment the document.

This variable only has any effect if the PDF document is encrypted. To encrypt a PDF document set {Media.PDF.UserPassword} or {Media.PDF.OwnerPassword}

noPrinting


System:

Default values for System variables are read from the system.settings file on the Turbine installation directory - this file is read during webserver start/restart time.
The following System variables are defined:

Variable Description Example
{System.Log} The log level, a combination of:
errors - log errors
warnings - log warnings
info - log information messages
errors, warnings
{System.LogTo} Where to log into, a combination of:
media - log into the Turbine Window
file - log to the turbine.log file
media
{System.Debug} The default value to use in the {Media.Debug}, if not specified by user No
{System.Protect} The default value to use in the {Media.Protect} variable, if not specified No
{System.Compress} The default value to use in the {Media.Compress} variable, if not specified No
{System.FontName} The default font name to use when not specified in a <Text> tag Arial
{System.FontStyle} The default font style to use when not specified in a <Text> tag bold, italic
{System.FontSize} The default font size to use when not specified in a <Text> tag. Must be expressed in a value where the size in pixels is multiplied by 20 - for example a 20 pixel font size should be specified here as
20 * 20 = 400
400
{System.FontColor} The default text color to use when not specified in a <Text> tag #000000
{System.FontMapSans}
{System.FontMapSerif}
{System.FontMapTypewriter}

The font names to be used (mapped) when a font is not available and needs to be mapped.
Far East users might prefer to use other font faces - for example MS Gothic or MS Mincho or Arial Unicode MS

Arial
{System.ImageEncodeFlags} Default encoding for images, when not specified in the <image> tag. Can be 0, to use the image's native encoding or one of:
1 - JPEG encoding
2 - ZLIB encoding,
3 - use one of JPEG or ZLIB that produces better compression
3
{System.ImageEncodeQuality} Default encoding quality, in percentage, to use when not specified on the <Image> tag. Similar to common JPEG quality /compression settings 85
{System.ImageSmooth} Default smoothening to use if not specified on the <Image> tag. Use 0 for no smoothening 0
{System.ImageResampleMethod} The image resizing method to use if not specified on an <Image> tag. One of:
0 - raw pixel resize
1 - average pixel resize
2 - bilinear resize
3 - bicubic resize
2
{System.MMLTagRequired} A boolean value that specifies whether MML tags used in Flash .swf templates must have be enclosed in <mml> ... </mml> tags.
Should be used if there's the danger of unintended MML tags used in Flash templates being parsed by Turbine.
No
{System.MMLWarnUnknownTags} Boolean value that specifies whether unknown MML tags raise warnings. Good during development to find locate misspellings in MML tags Yes
{System.AutoLayout} The default mode used on the AutoLayout functionality - one of horizontal, vertical or off vertical

 

Expression Variables

Turbine variables with numeric values can be used in expressions by using a {=...} syntax. For example - suppose we have two Turbine variables, {a} and {b}, with values 10 and 20, respectively. To add these two Turbine variables we can use:

{= a + b}

Which when expanded, would be substituted by the sum of their values, the number 30. All the common operations are available on these expressions, including parenthesis, producing the expected expression results. Some examples of valid expressions are:

{= a - 1}
{= (a + b) / 2}
{= a * (b + c) - 1}

Expressions are useful for example on situations where values relative to a certain variable are needed - this is very frequent for example when drawing shapes with the <Shape> MML tag.

 

DataSets

Tabular information is hard to manage using simple Turbine variables - for example displaying a text table can be a pain if you need to define and display all the individual variables, one by one. Turbine includes support for a structured, table-like type of variables named DataSets. An example of a Turbine DataSet is: 

<name, address, age>
"John Doe", "Street Nine 7", 41
"Carlo Marini", "Naples Blvd 15", 17
"Maria Caillias", "Rue de Progresse 11", 32

So DataSets are basically tables - but what do you gain with that?
By defining a DataSet you will be able to use its data on a variety of DataSet-driven MML commands where table-like information is needed: for example commands like the <Chart>, <AutoMedia>, <AutoImage> or <AutoMovieClip> tags.

DataSets can be defined in a number of ways, similar to Turbine variables. And also like Turbine Variables, DataSets can also be published into player-time Flash Action Script variables, arrays or named arrays.
 

DataSet Cells and Turbine Variables

A useful feature of DataSets is that individual cells can be accessed like normal Turbine variables by using the Turbine variable {} syntax, with the following format:

{DataSetName$ColumnName.RowNumber}

RowNumber starts at 0 - the first row is row number 0. For example on the above DataSet, the age of Carlo Marini, which is located at the 2nd row in the Age column (that is on row number 1), can be referenced by:

{People$Age.1}

this assumes the above DataSet name was defined as the 'People' DataSet.

 
DataSet Ranges

Suppose you need to reference row sections of the same DataSet - for example on the first screen of a product list you just want to display the first 5 products (the first 5 rows of the DataSet). Anywhere a DataSet name can be used, you can have Turbine use just a range of the rows by using the following syntax:

dataSetName[first_row..last_row]

so the first 5 items of the DataSet would be specified as People[0...4] , the next 5 items as People[5...9] , and so on.
Additionally you can avoid specifying the last_row:

dataSetName[first_row..]

This refers to a range of rows starting on row first_row till the last existing row of the DataSet.

 

Using DataSets

DataSets can be used in several MML commands - for example:

  • Chart command: displays charts based on DataSet's numeric columns.
  • AutoMovieClip command: display lists or grids of movie clips
  • AutoImage command: display lists or grids of images
  • AutoMedia command: display lists or grids of any MML elements

As with Turbine variables, DataSets naturally need to be defined before being used in any of these commands. Since commands are parsed when an MML or Flash template is loaded, DataSets should usually be defined before template loading is performed.

 

Loading a DataSet from a File

DataSets can be defined in a number of different ways - for example they can be loaded from a special text format:

<col1_name, col2_name,  col3_name,  ...>
col1_value, col2_value, col3_value, ...
col1_value, col2_value, col3_value, ...
col1_value, col2_value, col3_value, ...
...

On this format, the first line defines the names of the involved DataSet columns and must be specified inside a < > block by coma-separated values. After this header, each line defines a DataSet row by having the values separated by commas. The following rules are needed:

  • Strings must be delimited by " double-quote characters - no problem if there are any comas inside the string
  • To use a double-quote character inside a string, escape it with the backslash (\) character like this: \"
  • For convenience, the DataSet file can also include comment lines (which will be ignored), starting by the hash (#) character.

So the above DataSet would be formatted in a text file as:

<name, address, age>
"John Doe", "Street Nine 7", 41
"Carlo Marini", "Naples Blvd 15", 17
"Maria Caillias", "Rue de Progresse 11", 32

To load a DataSet from a such a file, in an PHP script we would use the following command:

$turbine->loadDataSet("datasetfile.txt", "dataSetName");

From an MML script we could use the <DataSet> tag:

<DataSet src="datasetfile.txt" dataSet="dataSetName"/>

As in other commands and tags, both local files and remote HTTP locations can be accessed.
Both this PHP call and the MML tag can also read DataSets from XML files in the format described below.

 

Manually Creating a DataSet

DataSets can also be manually created in a row-by-row basis from inside PHP scripts - please see the following example:

...

# create a DataSet named People with three columns:
$turbine->makeDataSet("People", "name, address, age");

# add first row:
$turbine->addDataSetRow("
John Doe, Street Nine 7, 41");

# add second row:
$turbine->addDataSetRow("
Carlo Marini, Naples Blvd 15, 17");

' add third row:
$turbine->addDataSetRow("
Maria Caillias, Rue de Progresse 11, 32");

... 

Another possibility is to define a DataSet from a string containing the entire DataSet, with column name definitions and DataSet rows - on the same format as when loading from a file:

$turbine->dataSetFromString(
               "<name, address, age>\nJohn Doe...",
               "People");

And yet another way is by loading from an XML string, which also can be accomplished using the DataSetFromString, with a few extra parameters.

 

Loading a DataSet from XML

DataSets can also be loaded from XML documents by specifying which tags to use for the DataSet rows and which tags or attributes to use for the DataSet column values inside each row. The basic principle is the one outlined on this example - suppose the following XML document:

<book>

 <name>Gone with the rain</name>
 <author>Arabian Bruce Lawrence</author>
 <price>$39</price>

 <chapter>
   <title id="1">First Launch</title>
   <pages>45</pages>
   <interesting>90%</interesting>
   <topics>Love, hate, adventure</topics>
 </chapter>

 <chapter>
   <title id="2">Second Launch</title>
   <pages>71</pages>
   <interesting>30%</interesting>
   <topics>Love</topics>
 </chapter>

</book>
 

From this XML, we'd like to extract a DataSet with the book chapter information - it should end up in a DataSet like this:

<title, pages, interesting, topics>
"First Launch", 45, "90%", "Love, hate adventure"
"Second Launch", 71, "30%", "Love"

We'd be interested on the <chapter> tag to be the tag that marks each DataSet row, and on the title, pages, interesting and topic tags to be our columns inside each of those DataSet rows. To load a DataSet from this XML document, we could use the LoadDataSet command we've seen above, with two extra parameters:

$turbine->loadDataSet("book.txt",
                      "dataSetName",
                      "chapter",                       "title,pages,interesting,topics");

The first parameter is the absolute or relative local path, or remote HTTP location of the file, which should contain a well-formed XML document. The second parameter is the DataSet name, next is the name of the tag to use for each row, last is a comma-separated list of tags to fill in as DataSet columns. The row tag and column tags can be specified in a few different ways, for example you can specify tag attributes to use as column values.
With this information, XML data can be conveniently assimilated into Turbine DataSets, available for further use on any DataSet-driven command.

 

Defining DataSets from Database Queries

By using the PHP engine you can access information from several types of data sources, notably from several well-known relational databases. On this section we will describe how you can integrate PHP Turbine with content accessed from a database, such as MySQL or ODBC connected Databases. The idea is that a Turbine DataSet will be created from database query results.

Let's see an example of how to do this accessing a MySQL database - we'll query the full name and address of some customers. Let's start by connecting to the database on the regular PHP manner:

    $conn = mysql_connect("host", "user", "password");
    mysql_select_db("customers");
Next, we do the actual database query to the Customer table - since we want to retrieve a list of customer full name and addresses:

$query = "Select FullName and Address from Customers";
$recordSet = mysql_query($query, $conn);

At this point we have a $recordSet with the query results - we're now interested on creating a Data Set with the contents of this query. To do so we can use the functions a PHP script available on the libraries directory of the PHP Turbine installation, the dataset_import.php script. To require the script we could simply (depending on the executing script path):

    require_once("../../libraries/dataset_import.php");

The dataset_import.php script defines functions that import the query results from specific databases (for example MySQL or ODBC) into Turbine. Since these functions are external to Turbine, functions to import query results from any other database can easily be created in this manner. The dataset_import.php file originally includes functions to import from MySQL and ODBC:

    loadDataSetMySQL($turbine, $recordSet, "dataSetName");
    -and-
    loadDataSetODBC($turbine, $recordSet, "dataSetName");

The preferred format for the name of these import functions is loadDataSetDatabase where Database is the type of the accessed Database.
So to fetch our customers into a Turbine Data Set we would do:

    loadDataSetMySQL($turbine, $recordSet, "Customers");

This will define a DataSet named Customers with two columns - "FullName" and "Address", and as many lines as the ones returned from the above query. This DataSet can be used in any commands that require a DataSEt, to automatically generate movie clips, charts, etc.
The complete source for the above is:

<? 
# create the turbine object:
$turbine = new FlashTurbine();

# load the dataset_import.php library:
require_once("../../libraries/dataset_import.php");

# connect to database:
$conn = mysql_connect("host", "user", "password");
mysql_select_dB("customers");

# query:
$query = "Select FullName and Address from Customers";
$recordSet = mysql_query($query, $conn);

# import the query results as a Turbine DataSet:
loadDataSetMySQL($turbine, $recordSet, "Customers");

# which .swf Flash template to use:
$turbine->load("customers.swf");

# now generate the movie to the web browser:
$turbine->generateFlash();

?>

 

Publishing DataSets to Flash Action Script

If you intend to use Turbine solely to generate Adobe PDF documents then you can skip this subsection because scripting is not exported to PDF.

As with Turbine variables, DataSets live at the server-side, however they can be published into the client-side as Flash Action Script variables in a multitude of useful ways - as simple variables, arrays and named arrays. As with other features, this functionality is both available on the PHP Interface and as an MML tag. On the PHP Interface we can do:

$turbine->publishDataSet("dataSetName");

The above would publish the values contained inside the DataSet into Flash Action Script variables, arrays or name arrays, which are available when the movie is played on the client. The next MML tag would accomplish the same effect:

<PublishDataSet dataset="dataSetName"/>

Variable and DataSet publishing allows you to easily bridge data from the server side into the player side, making it available for further processing

 

Table of Contents

 
Flash and Macromedia Flash are trademarks of Macromedia, Inc.