For more information... RTFM!
NAVIGATION
PAGES THAT LINK HERE
ACCOUNT LOGIN

You are not logged in

Powered by Interchange version 5.7.0

Interchange Perl objects

Table of contents
1. $Carts
2. $CGI
3. $CGI_array
4. $Config
5. %Db
5.1. Keys
5.1.1. Key for a normal table with one primary key
5.1.2. Array reference key for a COMPOSITE_KEY table
5.1.3. Alternate hash reference key for a COMPOSITE_KEY table
5.1.4. Alternate null-separated key for a COMPOSITE_KEY table
5.2. Database access methods
5.2.1. Get a specific row/column from the table
5.2.2. Set a specific row/column in the table
5.2.3. Atomic increment of an element of the table
5.2.4. Return a complete hash of the database row (minus the key)
5.2.5. Return some columns from a row
5.2.6. Set some columns in a row (slice)
5.2.7. Alternate method for setting a slice
5.2.8. Specifying INSERT or UPDATE
5.2.9. Perform a SQL query, returning an array of arrays
5.2.10. Perform a SQL query, returning an array of hashes
5.2.11. See if a column's datatype is numeric
5.2.12. Quote a value for SQL query purposes
5.2.13. Check configuration of the database
5.2.14. Find the names of the columns (not including the key)
5.2.15. Check whether a column is in the table
5.2.16. Check whether a key is in the table
5.2.17. Create a subroutine to return a single column from the table
5.2.18. Create a subroutine to set a single column in the database
5.2.19. Create a subroutine to set a slice of the database
5.2.20. Return a complete array of the database (minus the key)
5.2.21. Delete a row from the table
6. $DbSearch
7. $Document
7.1. header
7.2. hot
7.3. insert
7.4. ref
7.5. replace
7.6. review
7.7. send
7.8. write
8. $Items
9. $Scratch
10. $Session
11. %Sql
12. $Sub
13. $Tag
14. $Tmp
15. $Values
16. $Variable
17. Subroutines
17.1. Debug
17.2. HTML
17.3. Log
17.4. errmsg
17.5. uneval
 

$Carts

This is a reference to the $Session->{carts} shopping cart hash.  The default cart is "main".  Shopping carts are stored as an array of hash references.  Here is an example of a session cart array, containing a main and a layaway cart.  $Items is an alias to the current cart, within the %$Carts hash.

{
    'main' => [
        {
            'code' => '00-0011',
            'mv_ib' => 'products',
            'quantity' => 1,
            'size' => undef,
            'color' => undef,
        },
        {
            'code' => '99-102',
            'mv_ib' => 'products',
            'quantity' => 2,
            'size' => 'L',
            'color' => 'BLUE',
        },
    ],
    'layaway' => [
        {
            'code' => '00-341',
            'mv_ib' => 'products',
            'quantity' => 1,
            'size' => undef,
            'color' => undef,
        },
    ],
}

In this cart array, "$Carts->{main}->[1]->{code}" is equal to "99-102".  This would be equivalent to the shorter "$Items->[1]->{code}", unless the [cart] tag has been used to make a cart other than "main" the default.

Global context

Global context

You cannot use this object in a global context, such as from within a global UserTag or a GlobalSub etc. Use the "$::Carts" hashref instead.

$CGI

This is a hash reference to %CGI::values, which contains the value of user variables submitted in the current page or form.

To get the value of a variable submitted as:

<input type="hidden" name="foo" value="bar">

You would use:

[perl]
    return "Value of foo is $CGI->{foo}";
[/perl]

Actually, you should not do that.  If someone sends you a value you should not output it willy-nilly, for security reasons.  Filter it first with the [filter] tag, which may be accessed via the $Tag object, as follows:

[perl]
    my $val = $Tag->filter('encode_entities',$CGI->{foo});
    return "Value of foo is $val";
[/perl]

Remember, multiple settings of the same variable are separated by an ASCII NUL character.  To get an array value, use $CGI_array.

Global context

Global context

You cannot use this object in a global context, such as from within a global UserTag or a GlobalSub etc. Use the "%CGI::values" hash (not hashref) instead.

$CGI_array

This is a hash reference to the %CGI::values_array, arrays containing the value (or values) of user variables as submitted in the current page or form.  To get the value of a variable submitted as:

<input type="hidden" name="foo" value="bar">
<input type="hidden" name="foo" value="baz">

You would use:

[perl]
    return "The values of foo are " . join(', ',@{$CGI_array->{'foo'}});
[/perl]

Global context

Global context

You cannot use this object in a global context, such as from within a global UserTag or a GlobalSub etc. Use the "%CGI::values_array" hash (not hashref) instead.

$Config

This points at the $Vend::Cfg hashref, and can be used to look up or set website configuration values.  For instance:

#
#    allow searches of the userdb table on this page only
#
$Config->{NoSearch} =~ s/\buserdb\b//;

Changes are not persistent;  They are reset upon the next page access.

Global context

Global context

You cannot use this object in a global context, such as from within a global UserTag or a GlobalSub etc. Use the "$Vend::Cfg" hashref instead.

%Db

A hash of database tables, shared with the [perl] tag's tables="foo" parameter.  Once a table is shared, it is open and can be accessed by any of its methods.  This will not work with SQL unless the Safe::Hole Link to an external page module is installed, or AllowGlobal is set for the website.

Note

Note

This object is not available when using the [calc], [calcn] and [PREFIX-calc] tags.

You can use the following to get a reference to a particular table:

my $db = $Db{tablename};
Note

Note

If you want to access a table from withing a local UserTag then your tag code may need to call "$Tag->perl({ table => "tablename" });" in order to initialize "$Db{tablename}".

Keys

The examples that follow make use of a "$key" which can be one of the following:

Key for a normal table with one primary key

$key = 'foo';

Array reference key for a COMPOSITE_KEY table

$composite_array_key = ['foo','bar','baz'];

Alternate hash reference key for a COMPOSITE_KEY table

$composite_hash_key = { key1 => 'foo', key2 => 'bar', key3 => 'baz'};

Alternate null-separated key for a COMPOSITE_KEY table

$composite_nullsep_key = join("\0", 'foo', 'bar', 'baz');

Database access methods

The available methods are as follows:

Get a specific row/column from the table

$value = $db->field($key, $column_name);

Set a specific row/column in the table

$db->set_field($key, $column_name, $value);

Atomic increment of an element of the table

$db->inc_field($key, $column_name, 1);

Return a complete hash of the database row (minus the key)

$hashref = $db->row_hash($key);

Return some columns from a row

my @columns = qw/sku price description/;
@values = $db->get_slice($key, \@columns);

Set some columns in a row (slice)

my $key = 'os28004';
my @columns = qw/price description/;
my @values = (5.95, "Ergo Roller");
$array_ref = $db->set_slice($key, \@columns, \@values);

Alternate method for setting a slice

my $key = 'os28004';
my %columns = ( price => 5.95, description => "Ergo Roller");
$array_ref = $db->set_slice($key, \%columns);

Specifying INSERT or UPDATE

Either:

my $key = 'os28004';
my %columns = ( price => 5.95, description => "Ergo Roller");
my %opt = ( dml => 'insert' );

my $array_ref = $db->set_slice([\%opt, $key], \%columns);

or:

my $key = 'os28004';
my %columns = ( price => 5.95, description => "Ergo Roller");
my %opt = ( dml => 'update' );

my $array_ref = $db->set_slice([\%opt, $key], \%columns);

The "dml" option may be set to either "insert", "update" or may be left unset.  If unset then the default will be to insert a new row or update an existing rows, as appropriate.

Availability

Availability

This facility was introduced in version 5.5.2, and is therefore not available for use with any earlier Interchange version.

Perform a SQL query, returning an array of arrays

This is the equivalent of DBI $sth->fetchall_arrayref.

$ary = $db->query($sql);

The following is the same, except that it also obtains hash reference of pointers to column positions and array reference containing list of columns:

my $sql = 'select * from products';
($ary, $index_hash, $name_ary) = $db->query($sql);
$columns_returned = join ",", @$name_ary;
$pointer_to_price = $index_hash->{price};

Perform a SQL query, returning an array of hashes

$ary = $db->query({ sql => $sql, hashref => 1 });

See if a column's datatype is numeric

$is_numeric = $db->numeric($column_name);

Quote a value for SQL query purposes

$quoted = $db->quote($value, $column_name);

Check configuration of the database

$delimiter = $db->config('DELIMITER');

Find the names of the columns (not including the key)

@columns = $db->columns();

#
#    insert the key column name
#
unshift @columns, $db->config('KEY');

Check whether a column is in the table

$is_a_column = defined $db->test_column($column_name);

Check whether a key is in the table

$is_present = $db->record_exists($key);

Create a subroutine to return a single column from the table

$sub = $db->field_accessor($column);
for (@keys) {
    push @values, $sub->($key);
}

Create a subroutine to set a single column in the database

$sub = $db->field_settor($column);
for (@keys) {
    $sub->($key, $value);
}

Create a subroutine to set a slice of the database

$sub = $db->row_settor(@columns);
for (@keys) {
    $sub->($key, @values);
}

Return a complete array of the database (minus the key)

@values = $db->row($key);

Delete a row from the table

$db->delete_record($key);

$DbSearch

This is a search object that will search a database table.  It is the same as Interchange's db searchtype.  Options are specified in a hash and passed to the object.  All multiple column options should be passed as array references.  Before using the $DbSearch object, it must be told which table to search.

To use the "foo" table, it must first have been shared with [perl tables=foo].

There are three search methods, as follows:

Method Description
array Returns a reference to an array of arrays (best).
hash Returns a reference to an array of hashes (slower).
list Returns a reference to an array of tab-delimited lines.

For example:

$DbSearch->{table} = $Db{foo};

$search = {
    mv_searchspec => 'Mona Lisa',
    mv_search_field => [ 'title', 'artist', 'price' ],
    mv_return_fields => [ 'title' ]
};

my $ary = $DbSearch->array($search);

return 'No match.' unless scalar(@$ary);

foreach (@$ary) {
    do_something($_);
}

Global context

Global context

You cannot use this object in a global context, such as from within a global UserTag or a GlobalSub etc. Use the "$Vend::DbSearch" hashref instead.

$Document

This is an object which will allow you to write and manipulate the output of your embedded Perl.  For instance, you can emulate a non-parsed-header program with the following:

[perl]
    $Document->hot(1);

    foreach (1 .. 20) {
        $Document->write("Counting to $_...<br>");
        $Document->write( " " x 4096);
        $Tag->sleep(1);
    }
    $Document->write("Finished counting!");
    undef;
[/perl]

Note the write of 4096 spaces.  Because Interchange's link program is parsed by default and your web server (and the link program) have buffers, you need to fill up the buffer to cause a write.  You can do it without the extra padding if you set the link up as a non-parsed-header program.  See your web server documentation on how to do that.

There are several methods associated with the $Document object, as follows:

Global context

Global context

You cannot use this object in a global context, such as from within a global UserTag or a GlobalSub etc. Use the "$Vend::Document" hashref instead.

header

Add a line to the HTTP header:

$Document->header($foo,$opt);

This can be used to change the page content type, cache options or other attributes.  The code below changes the content type (MIME type) to text/plain:

$Document->header("Content-type: text/plain");

There is an optional hash that can be sent, with the only valid value being "replace" The code below scrubs all previous header lines:

$Document->header("Content-type: text/plain",{ replace => 1 });

Once output has been sent with $Document->send(), the $Document->header() method no longer has any effect.

hot

If the parameter is true (in the Perl sense), then all $Document->write() operations will be immediately sent, until a $Document->hot(0) is called.

For instance, the following causes writes to be sent to the user's browser immediately:

$Document->hot(1);

Stop immediate writes:

$Document->hot(0);

insert

Insert a value to front of write buffer array:

$Document->insert($foo);

The following example will output "123":

$Document->write("23");
$Document->insert("1");
$Document->send();

while this example will output "231"

$Document->write("23");
$Document->write("1");
$Document->send();

ref

Get a reference to output buffer:

$ary_ref = $Document->ref();

replace

Replace contents of the write buffer with the contents of a supplied array:

$Document->replace(@ary)

review

Return the contents of the write buffer as an array:

my @ary = $Document->review();

send

Flush the write buffer array to the output, done automatically upon the end of the [perl] call.  This also clears the buffer and invalidates $Document->header().

$Document->send();

write

Append a value to the write buffer array

$Document->write($foo);

The above will write $foo to the page in a buffered fashion.  The buffer is an array containing the results of all previous $Document->write() operations.  If $Document->hot(1) has been set then the output will immediately be sent to the user's browser.

Also see the HTML subroutine.

$Items

This is a reference to the current shopping cart array.  This will normally be the same as $Carts->{main}, unless the Interchange [cart] tag has been used to make a cart other than "main" the default.

See the $Carts section for an example of the array structure.

Global context

Global context

You cannot use this object in a global context, such as from within a global UserTag or a GlobalSub etc. Use the "$Vend::Items" arrayref instead.

$Scratch

A reference to the scratchpad values ala [scratch foo].

$Scratch->{foo} = 'bar';

is equivalent to:

[set foo]bar[/set]

Global context

Global context

You cannot use this object in a global context, such as from within a global UserTag or a GlobalSub etc. Use the "$::Scratch" hashref instead.

$Session

A reference to the session hash maintained for the current user.

The following two blocks of code are equivalent:

Using Perl

[calcn]
    return $Session->{browser};
[/calcn]
Using the [data] tag

[data session browser]

Session values can also be set.  For instance, if the value of [data session source] needs to be changed, for some reason, then you could use the following:

$Session->{source} = 'New_partner';

The following keys are available in the $Session hash reference.

Name Description
accesses The number of pare requests performed for this session within the last 30 seconds.
arg The argument passed in an [area] tag.
browser The identification value sent by the user agent.
carts A reference to a Perl hash containing shopping carts.  See $Carts for more information.
host Interchange's note of the visitor's hostname (possibly modified by DomainTail).  If the hostname could not be looked up (HostnameLookups switched off or DNS error etc.) then the visitor's IP address will be stored here instead.
id The current session ID.
last_error The last error or status message from the error logging routine.
last_search The last non-SQL Interchange search specification invoked.
last_url The current Interchange path_info.
logged_in Will be true if the user is logged in.
ohost Interchange's note of the visitor's IP address when using a non-SSL link.  Also see shost.
pageCount Number of unique URIs generated by Interchange for this session.
payment_result A hash of result messages from payment module transaction attempts.  See examples in the Interchange payment modules documentation.
prev_url The previous path_info.
referer HTTP_REFERER string.
ship_message The last error messages from shipping.
shost Interchange's note of the visitor's IP address when using a SSL link.  Also see ohost.
spider Will be true if the user is a search engine spider.
source Source of original entry to Interchange.
teleport Date and time (in "%Y%m%d%H%M%S" format) for use with the PageTables directive.
time Time (seconds since 01 January 1970) of the last access.
user The REMOTE_USER string.
username Logged-in username.  See the Interchange user database page.

Global context

Global context

You cannot use this object in a global context, such as from within a global UserTag or a GlobalSub etc. Use the "$Vend::Session" hashref instead.

Warning

Warning

Make sure you know what you're doing before you start monkeying about with the values stored in the $Session hashref.

%Sql

A hash of SQL tables that you shared with [perl tables="foo"].  It returns the DBI database handle, so operations like the following can be performed:

[perl tables="products"]
    my $dbh = $Sql{products} or return 'Table is not defined';
    my $sth = $dbh->prepare(q{
        SELECT  sku, price
        FROM    products
    }
) or return "Couldn't prepare query 1";

    $sth->execute() or return "Couldn't execute query 1";

    my @row;
    while (@row = $sth->fetchrow()) {
        do_something(\@row);
    }

    $sth = $dbh->prepare(q{
        SELECT  foo, bar
        FROM    sometable
    }
) or return "Couldn't prepare query 2";

    $sth->execute() or return "Couldn't execute query 2";

    while (@row = $sth->fetchrow()) {
        do_something_else(\@row);
    }
    undef;
[/perl]


Note

Note

This object is not available when using the [calc], [calcn] and [PREFIX-calc] tags.

$Sub

The $Sub allows access to any Sub or GlobalSub subroutines you may have defined.

Note

Note

Safe Link to an external page mode will be in operation during the subroutine call, so unsafe operations will be trapped as usual.

Usage example:

[perl]
    my $result = $Sub->mysub('arg1','arg2');
    return $result;
[/perl]

Global context

Global context

You cannot use this object in a global context, such as from within a global UserTag or a GlobalSub etc. Use the "Vend::Subs" object instead.

$Tag

Using the $Tag object, most standard Interchange tags, and all user-defined tags can be accessed.

Note

Note

If the tag will access a database that has not been previously opened, the table name must be passed in the [perl] call.

Usage example:

[perl table="userdb"]
    return $Tag->data({
        table => 'userdb',
        column => 'name',
        key => $Session->{username},
    });
[/perl]

is the same as:

[data table=userdb column=name key="[data session username]"]

If the tag has a dash (-) in its name then use an underscore instead:

WRONG!!!

$Tag->shipping-desc('upsg');

Right

$Tag->shipping_desc('upsg');

There are two ways of specifying parameters.  Either use the positional parameters, shown in the specific tag's documentation, or specify all parameters with a single option hash.

For instance, the calls:

$Tag->data('products','title','00-0011');

and:

$Tag->data({
    table => 'products',
    column => 'title',
    key => '00-0011',
});

are equivalent for the [data] tag.

If using the option hash method, and the tag has container text, either specify it in the hash parameter body or add it as the next argument.

For instance, the calls:

$Tag->tmpn({
    'name' => 'foo',
    'body' => 'bar',
});

and:

$Tag->tmpn('foo',{},'bar');

are equivalent for the [tmpn] tag.

Note

Note

Names in the parameter hash are ALWAYS lower case.

See the Interchange tags category for documentation on each of the standard Interchange markup language tags, along with a list of the named and positional parameters that can be passed to each of the tags.

Global context

Global context

You cannot use this object in a global context, such as from within a global UserTag or a GlobalSub etc. Use the "Vend::Tags" object instead.

$Tmp

A reference to query results gathered by the current page.  See [query].

$Values

A reference to the user form values, ala [value foo].

[calcn]
$Values->{foo};
[/calcn]

is equivalent to:

[value foo]

Global context

Global context

You cannot use this object in a global context, such as from within a global UserTag or a GlobalSub etc. Use the "$::Values" hashref instead.

$Variable

A reference to the website's variables, as configured using the Variable and Variabledatabase local configuration directives.

A variable that can be accessed like this:

__FOO__

can also be accessed like this:

[calcn]
$Variable->{FOO};
[/calcn]

Global context

Global context

You cannot use this object in a global context, such as from within a global UserTag or a GlobalSub etc. Use the "$::Variable" hashref instead.

Subroutines

Debug

Create a new entry in the global DebugFile, if defined.  This is the same as calling ::logDebug() in a GlobalSub or a global UserTag.

For instance:

[perl]
    Debug('Debug log entry');
    undef;
[/perl]

HTML

Append a value to the write buffer array.  This is exactly the same as the $Document->write() method, described above.  For example:

HTML $foo;

Log

Send a message to the local ErrorFile.  This is the same as calling ::logError() in a GlobalSub or a global UserTag.

For instance:

[perl]
    Log('Error log entry');
    undef;
[/perl]

This prepends the normal timestamp with user and page information.  To suppress that information, begin the message with a backslash (\).

[perl]
    Log('\Error log entry without timestamp');
    Log("\\Another error log entry without timestamp");
    Log('Error log entry with timestamp');
    undef;
[/perl]


Note

Note

The second [Log], in the example above, used a double-backslash (\\) because double-quotes were used to enclose the message string.

errmsg

Translate the text provided as the first parameter according to the transformation text provided in your website's locale table, or in the global translation table provided by the Interchange admin system.  The return value will be either the translated text or, if no translation is found, the original text verbatim.

Usage example:

[calcn]
    errmsg('Your session ID is %s',$Session->{id});
[/calcn]

uneval

Encode a Perl hash/array reference into a string representation of the code used to build the reference.  This is the same as calling the [uneval] tag.

Usage example:

[calcn]
    $someref = {
        foo => [ 'bar', 'baz' ],
    };
    uneval($someref);
[/calcn]

Categories:  Interchange Perl usage | Interchange database
Last modified by: Kevin Walsh
Modification date: Thursday 15 May 2008 at 11:10 PM (EDT)
Home  |  Legal nonsense  |  Privacy policy  |  Donations  |  Contact us