APE_DOC by keralaguest


									A Reference Guide for APE 4.0

               A Reference Guide for APE 4.0
                                February, 3rd 2010
                                   Version 1.2

Added Section on Creation Applications 02/03
Added An Extended Example for APE_form_validate 02/03
     Started section 7 detailing the different use of forms 02/03Table   of Contents
          1.   Introduction
          2.   File Structure and Loading Sequence
          3.   File and Folder Descriptions
               3.1 APE/bin
               3.2 APE/core
               3.3 APE/css
               3.4 APE/libs
          4.   Constants
               4.1 Application Constants
               4.2 Engine Constants
               4.3 Debugging Constants
               4.4 SQL Table Constants
          5.   Reports and Graphing
               5.1 printdata[table][row][column][element]
               5.2 data[][]
               5.3 Settings Array for Forms
               5.4 Settings Array Examples
               5.5 Creating Reports
               5.6 An Extended Example

A Reference Guide for APE 4.0

          6.   Creating Applications
               6.1 Default files and folders
               6.2 Creating Database Entries
          7.   Forms and Memory TODO
     7.1 Standard HTML forms
     7.2 Forms created with APE_form_validate
     7.3 Directly calling APE_form_element and APE_form_builder
     7.4 APE_form_element a Complete Listing
     7.5 APE_sql_display_record and related table related functions
          8.   Appendixes TODO
1.0 Introduction
The Application Programming Engine (APE) is a PHP framework intended to facilitate
the rapid development of browser-based applications and tools. At the core APE is a
collection of folders, functions, external libraries and best practice methods in code

The principle ideas of APE were originally written as a proof of concept (Interactive
Voice Response) IVR control panel in 2000. Since that time it has come to have several
major built in component features. In 2002 the focus shifted away from utilizing APE for
in an IVR control situation proceeded to introduce a help desk ticket management

In 2007 work began on what is known internally as APE 4.0. There was a need
identified to build out a user management and control system specifically to tie together
several existing browser based statistics reporting applications. APE 4.0 was a from
scratch rewrite of methods and lessons learned in earlier versions. It was for the first
time designed to be a platform for ongoing application development.

Today APE contains several functional components; a secure and flexible permissions
based registration system for user management, a robust ticket creation and
management system, data reporting capabilities involving tables, graphs and several
types of export options, a modular monitoring system for servers, SQL records and

In some situations where tools like a ticketing system are needed APE can be utilized
without further independent development. Requests for features can be submitted to the
primary development team and included in future releases.

The intention of this document is to introduce developers to APE and provide an
overview of the specifics needed to begin independent development. The idea of APE is
maximum flexibility with minimum overhead. That is to provide a base of reusable code,

A Reference Guide for APE 4.0

methods and techniques that can be extended and altered with little impact on any
single developers preferred style or procedures in writing PHP based applications.

APE is configured to use SVN code management and those checkouts provided to
external developers are to be kept in sync with the primary development base where
possible. While it is entirely possible to develop a complete application without any
alternation to the APE core it is likely that in the process of development that the need
for extensions, fixes and edits will be encountered.

The ultimate goal of APE is to provide a common development platform across teams,
sections and divisions. A catalyst that initiates faster production cycles while providing a
common structure that facilitates the ability for diverse projects to share and contribute
new ideas, lessons learned and knowledge advancement through independent
2.0 File Structure and Loading Sequence

APE as a core is a system of organizing key php files and folders into a structure that
can be easily understood and extended. The major effort here is to make the APE and
all of it‟s included folder and files functionally compatible with any application developed
for the platform. Essentially a system of consistency built on loose cooperation.

While a particular install of APE might utilize engine elements that another may not all
external instances of APE are checked out of the primary development product via
SVN. For continued developer support any changes made are required to be
compatible with the source when checked in. Major updates are welcome and can be
submitted for review and implementation.

The files as packaged:


The following sections of this document will break down each file in detail and describe
the process that occurs when when a client browser sends a page request.
(ie. http://APE-server/application)

The server loads index.php which by default includes two files.

• config.php
• APE/starter.php

A Reference Guide for APE 4.0

Is the primary engine level configuration and can be customized per install of APE. (See
config.php description in the following sections.

A core file and the start of engine initialization and begins the load into server memory
of variables, paths, constants, tables and other resources. While processing starter.php
other important files and libraries are also called for inclusion.

The primary functions library. Any function deemed to be of value to any application or
required for core abilities.

The primary classes library. Any class deemed to be of value to any application or
required for core abilities.

Remove any foreign characters from values and text submitted via $_GET[] and
$_POST[] variables.

Defines functions and elements related to using the included APE form creation and
processing abilities.

The SQL support and library. A set of wrapping functions to manager different database types.

A third party library for handling out going email via smtp and imap services.

Defines functions and resources required in support of the APE temporary memory system.

All applications include a keys.php file for the setup and connection to one or more databases.

Login authentication, cookie processing, permission checks, language constants, acting
checks, time and date configurations and the definition of constants associated to the
active user account. (See Constants section)

If the user is not logged in on an application that does not provide for unauthenticated
guests as level 1 a redirection to the the login dialog screen occurs.


A Reference Guide for APE 4.0

Looks for the runonce.php located in APE/bin this code is run after check.php but before
any page output occurs.

Represents the image as shown on the login screen. A different logo.png can be placed
in each application‟s root directory.

The final element of starter is to load the primary design (template.html) as well as
optional or situational layouts ie. print.html and maintenance.html.

The inclusion of a custom template.html file in the root of any application will override
the provided template.html.

Using the query string variable where ?template=layout will attempt to load a file called
layout.html from the application‟s root or APE/template as the active template.

Any template.html is a standard HTML file with proper headers, meta and formatting.
Optionally the APE/core file close.php is also includes at the end of a template file. This
code is responsible for debugging elements, page statistics and other commands
processed after a given page is finished loading.

It is responsible for including the requested page file ($APE_page) A path to a file
defined in starter.php. When included; $APE_page (APE/core/page.php) determines if a
page is requested and what to load. (ie. ?page=hello)

If a page is requested (ie. ?page=hello) then APE will attempt to load the requested file
from the local application‟s bin folder if the file is not present a check for the file will be
made in APE/bin. In this way any file included in APE/bin can been overloaded by a
local applications version if major customizations are required.

If the $_GET[“page”] variable in the query string is null, blank or not present then a
check is done for a constant called APP_START_PAGE if this constant is defined in the
application options APE will attempt to load a file from the local applications bin folder of
the same name (with a php extension). If the file requested is not found in the local
application bin folder then a check will be made in the APE/bin folder.

If APP_START_PAGE is not defined and a specific page is not requested then APE will
attempt to load a file called index.php from the application‟s bin folder. If one is not
present then APE will load the standard index.php found in APE/bin/.

If a requested page file cannot be found a 404 will occur.

A Reference Guide for APE 4.0

A Reference Guide for APE 4.0

3.0 File and Folder Descriptions

The previous section describes the process and files involved with from the initial page
request through the successful rendering of default.html in the clients browser. While
not involved with every page load APE contains a number of important folders, files and

--attachements A legacy folder for the support of file attachments.
--bin (Section 3.1)
--cache Used by the PEAR Cache library
--core (Section 3.2)
--css (Section 3.3)
--gfx Contains all images and engine related art
--templates (Contains templates; template.html, print.html, maintenance.html)
--libs (Section 3.3)
--mem Used by APE‟s export subsystem to facilitate caching of files.
--photoicon Stores all users uploaded profile images and photos.
--scripts Contains JQuery and related files and custom JS files (ie. tfnnet.js)
cleanup_cache.php Manually purges the current PEAR Cache.
dbg-wizard.php Third party functions related to debugging options.
download.php Legacy file download conduit.
export.php Handler for the packaging and download of Excel, XML and PDF files.
login.php Primary login dialog screen.
starter.php Primary engine setup and initialization.
xmlrpc.php Contains all available remote procedure calls.
3.1 APE/bin

For the APE engine and all developed applications the bin folder serves to contain all
the files used by the page request mechanism when loaded by APE/core/page.php.

Included with APE are about two dozen files containing the options and procedures of
the engine. Any APE/bin file can be replaced in an application bin folder.

A Reference Guide for APE 4.0

The account profile page and dashboard for each registered user.

A page showing contact cards for all users who have been active in the last month.

A web traffic statistics package. (Unfinished).

Create, manage and delete applications.

A client view and management of personal bookmarks.

View tickets by categories, tags, blog or see latest responses, files, views and calendar.

Displays a large calendar and items created if applicable.

Presents a user a form for updating their account profile information.

A listing of all user accounts by personal Contacts, Application Contacts a Lookup
search and an Administrate listing for application administrators to find accounts quickly.

edit (folder, contains files related to utilizing the edit.php screen for items)

edit bookmarks.php
Called when editing personal bookmarks.

edit language.php
Called when editing language value strings.

edit levels.php
Called when editing application level values and descriptions.

edit links.php
Called when editing application links.

A Reference Guide for APE 4.0

edit response.php
Called when editing item responses.

Primary edit screen for items (Tickets). Includes more files from the APE/bin/edit folder.

A form to email a given user‟s provided email and includes an option to CC APE

Displays the complete listing of historical events and revisions for any given item.

A simple message manager for APE messaging.

The default index (start page) for APE applications. Three column layout with Modules,
Links or Applications listings; a blog style listing of unclosed items and a user panel with
personal contacts, support contacts and bookmarks.

The primary rendering and display of a requested item.

Called when needing a blog styled view of items in reverse chronological order.

Called when needing a compact titles view of items.

A complete listing with parameters (a report) of all tickets in the application.

Used for searching and displaying the language table values.

Used for displaying the levels table titles and values.

Used for displaying current applications listing of links.

Used for displaying and managing an applications installed modules.

A Reference Guide for APE 4.0

Used for displaying and managing an applications available options.

Used for displaying and managing an applications category and subcategories. To be

Used to change the active users password. Old password required.

Displays items that have been pinned and/or deemed important.

Displays all users for a given item who have viewed a ticket since creation and since

Used by an admin to create a new user account.

Display and manage application contacts (support) and who is On Call and/or
Secondary On Call.

The report engine‟s primary header.

reset password.php
Allows an admin to reset a given users password given a valid username.

Allows an admin to reset a given users password or username.

Searches tickets and responses for the given input.

Displays a given servers event history.

Internally included file used in server monitoring.

Displays a listing of monitored servers per application.

A Reference Guide for APE 4.0

Sends a short message to a user‟s provided SMS email gateway address.

Allows the active user to set their status, location and a profile color.

Shows all users who have a subscription to a given item.

Allows a user to display and mange all item subscriptions.

Allows for the display and management of item (ticket) form templates.

An administrator view for all APE users, allows the setting of permissions per

3.2 APE/core

Common functions, features and support files related to engine operation.

A flexible calendar example ready for inclusion.

Checks permissions and settings. (See Section 2.0)

Primary common class library.

Primary method and functions involved with rendering graph data.

Contains a case structure to return the called template.html element.

Closing error handler, debug values, statistics and post page operations.

Collection of functions and constants relating to the use of APE_forms.

A Reference Guide for APE 4.0

Primary collection of common APE_functions.

Primary collection of APE functions related to image gd_lib image processing.

A colored “led” resource. Called directly with query string values. Black, Red, Green,
Blue, Yellow.

Determines and loads the requested page.

Resource for handling the upload and update of user uploaded profile photos.

A third party library used to thoroughly check and clean incoming values (ie $_POST).

Included from starter.php and is responsible for the setup and display of header tabs.

Functions and classes used for the creation and intercept of xml data.

3.3 APE/css

Default customization of the design and layout.

Customization of the default login form and page.

Customization of the template used when viewing a given page for printing.

3.4 APE/libs

dcl - “Donny Core Library”
A set of services used in the development of cmd line based APE applications. Primarily
used in the development and operation of the server and services monitor.

A collection of functions related to the included debugging features.

A Reference Guide for APE 4.0

A library used to support the custom error handler for APE.

Contains the third party class library phpMailer used in outgoing emails.

Contains the third party class library pChart used in graphing operations.

Contains a function library used in the page performance testing .

Contains a third party class library used in the export of PDF documents.

A wrapping library for standard PHP SQL functions related to various types of database
support. (ie. mySQL, MSSQL, ODBC)

A set of functions that utilize the PEAR Cache to create methods for temporarily storing
values and other settings.4.0 Constants

When working in the APE environment a key benefit is access to all elements of the
page load as a series of defined constants. These constants relate to several key areas;
the application, the user, debugging and the engine itself.

4.1 Application Constants

Application constants always start with the prefix APP and are defined in starter.php.

Except for APP_SERVER_NAME all APP constants are created from the
APE_applications table field names and values. These settings are intended to be
updated via the Application Options page within each application.

Defined in from the PHP server variable $_SERVER[„SERVER_NAME‟]

The string identifier for an application which in turn corresponds to the applications root
directory name. In the case of APE itself the value is blank.

Currently always set to APE and not yet implemented.

A Reference Guide for APE 4.0

An MD5 identifier for the selected user.

Plain text name for the application.

Plain text name for the application in French.

An MD5 identifier for the selected user.

Currently always set to the same value (ie. tfnnet) and not yet implemented.

Currently set to the same value (ie. TFN) and not yet implemented.

Allows for a custom url to be associated with the application.

The applications timezone offset from GMT with an appended zone identifier as listed in
the APE_timezones table.

Plain text name description of the application.

Plain text name description of the application in French.

A url or path to an image used in the template or other locations.

A url or path to an image used in the template or other locations.

A color in hex used in the template or other locations. (ie. #ffffff)

A color used in the template or other locations. (ie. #ffffff)

A color used in the template or other locations. (ie. #ffffff)

A Reference Guide for APE 4.0

A color used in the template or other locations. (ie. #ffffff)

Can be used to inject CSS formatting for an application.

The level 1-9 at which a user can update, edit and sometimes delete content.

The level 1-9 at which a user can update, edit, delete and control all content.

The level 1-9 at which a user must be in order to load the application.

The level 1-9 at which a user can update, edit and create language strings.

Used to set a status message for the application when needed. (ie. Maintenance)

Used to disable an application when required by an issue or schedule.

Sets a numeric value used in the default index.php for ordering applications.

Sets a plain text value for an applications modules. (ie. Reports)

Sets a plain text value for an applications modules in french. (ie. Rapports)

Sets a flag such that an application cannot be deleted by any user or administrator.

Sets a flag such that the application is not generally shown in application listings.

Sets a plain text value for the title of items. (ie. Tickets, Documents, Articles)

Sets a plain text value for the title of items in French. (ie. Tickets, Documents, Articles)


A Reference Guide for APE 4.0

Sets the name of the file located in APE/bin or the applications bin folder to be loaded
by default.

4.2 Engine Constants

APE or engine constants always use the APE prefix and are defined in config.php,
starter.php and check.php.


A flag if set that indicates maintenance mode is enabled.

A flag set if the error handling intercept is enabled.

Inherited from $_SERVER['HTTP_HOST'] as set by the server.

A string identifier to describe the root application

Default time zone from GMT for APE. DST is not applied.

Default time zone from GMT with a specific location code. (ie. -5014)

A MD5 for a user account used for users not that are not logged in.

Default level assigned to new accounts in register.php

Generic APE configuration for showing year, month, day. Set to “Y-m-d”.

Describes the folder path location of APE in the web server‟s file system from its root.
ie. C:\\ or \ on a linux server. Internally set if $APE_root_path is not used.

Describes the active application‟s directory name as read from:

A Reference Guide for APE 4.0

A path to the APE engine, utilizes the $APE_root_path variable for setting custom

Sets a value of the query string variable $_GET[“page”].

Updated for each revision via external SVN file.

Updated for each revision via external SVN file.

Updated for each full 1.0 upgrade. Currently set at version 4, P4-YYYY-MM-DD

Sets the IP or hostname for the SMTP server used for outgoing email.

Sets the port for the SMTP server used for outgoing email.

Default salt value for APE_encrypt and APE_decrypt.

Set internally and/or by an application definition and/or by setting $APE_quietmode.
Used when invoking the APE engine without requiring any headers or rendered output.

Sets a value of the query string variable $_GET[“tab”].

Sets the string value associated to the english language. (eng)

Sets the string value associate to the english language (fre)

Sets a boolean to enable database storage of attachments. File attachments if false.



A Reference Guide for APE 4.0

Path to graph line drawer as constant.

Path to graph bar drawer as constant

See Section 4.3.

A full http path for the currently active application with a trailing slash.

The value of APE_microtime_float() before loading and rendering the template output.


Internally built constant that is APE_TZ_GMT with DST applied if applicable.

Internally built constant to describe the active application‟s time string.

An internal flag automatically updated for Daylight Savings Time.

A construct of APE_SERVER_NAME - APE_PAGE.

4.3 USER Constants

User constants always use the APE_USER prefix and are defined check.php.

Stores a value associated to the user‟s account record for remembering their login

The currently active user id (MD5) as determined from the table APE_users table when
authenticated. Guest account identifier is 33e9232989576b5cfaa06654217d7a1a.

The currently active user name (ie. hxf148) as determined from the table APE_users
table when authenticated.

A Reference Guide for APE 4.0

The currently active user‟s chosen first name as determined from the table APE_users
table when authenticated.

The currently active user‟s chosen last name as determined from the table APE_users
table when authenticated.

The currently active user‟s email as determined from the table APE_users table when

The currently active user‟s chosen language as determined from the table APE_users
table when authenticated. (eng or fre)

The currently active user‟s account creation date as determined from the table
APE_users table when authenticated.

The currently active users‟s computer IP address as determined from the server value

The currently active users‟s selection of time zone. Default user time zone is same as
APE‟s and/or the active application.

The currently active user level (1-9) as determined from the table APE_permissions
table when authenticated. Changes per application.

The currently active user level (1-9) as determined from the table APE_permissions
table when authenticated. Consistent across all applications.

The currently active user level title as determined from the table APE_levels table when
authenticated. Changes per application.

The currently active user status color as set by the user.


A Reference Guide for APE 4.0

An internally calculated value given the users selection of time zone.

An internally calculated value to decide if the the users selection of time zone is
observing Daylight Savings Time.

An internally constructed text phrase to describe the users time, time zone and Daylight
Savings Time.

4.3 Debugging Constants

APE or engine constants always use the DEBUG prefix and are defined in config.php.

A flag to enable the page load performance profiling.

A flag to enable the output of all executed SQL statements at the foot of each page.

A flag to enable the output of all rendered language statements at the foot of each page.

A flag to enable the output of APE‟s volatile memory at the foot of each page.
A flag to enable the output of APE‟s internal memory at the foot of each page.

4.4 SQL Table Constants

All table constant values are constructed from combining $APE_sql_db as set in
keys.php and the ape_tablename in the primary APE database.


A Reference Guide for APE 4.0

APE_TABLE_STATS_TYPES5.0 Reports and Graphing

5.1 printdata[table][row][column][element]

Defines settings see APE_printarray in functions.php for specific details.

=> all - references all tables
=> table# - references specific table, auto incremented by APE (1+)

=> all - all - X Axis
=> data - all rows that contain data
=> header - header of table headings
=> footer - total or summary line
=> format - used to set X Axis Format in graphs. values: number, date, time, metric,
=> unit - used to set the X axis units for graphs. units: km, m/s, liter, etc

A Reference Guide for APE 4.0

=> column# (0 based) (Y Axis)
=> format - used to set Y Axis Format in graphs, values: number, date, time, metric,
=> unit - used to set the Y axis units for graphs, use units like km, m/s, liter, ...

=> basic HTML elements
=> format
=> align
=> skip
=> color
=> preformatted - overrides the rendering engine for HTML output
=> ...

5.2 data[][]

The values for the graph should be for the data[][] format.

row[0] = headers
row[0+X] = data
row[last] = totals if enabled

5.3 Settings Array for Forms

$settings = array(
elements => array (
'elementName' => array (

- "fieldtype" : a APE_form_element, or local form_element
- "defaultvalue" : Default value;
- "elementparameter" : (mixed, array) Any special parameters
- "label" : Element label
- "sameline" : (boolean) The next element will be on the same line;
- "elementnote" : Small text at the right of the form element (side note);
- "skipmemory" : (boolean) Doesn't save in memory value. Applies default value;

) // end of elementname
) // end of elements

'refresh' => value :The report refresh rate in seconds, defaults to 180

A Reference Guide for APE 4.0

'connectionname' => The database connection to use

) // end of settings array

5.4 Settings Array Example

$settings = array(
'elements' => array(
'queues[]' => array(

'fieldtype' => 'queues','label' => "Queues"),
'from' => array('fieldtype' => 'date','label' => 'From',),
'to' => array('fieldtype' => 'date','label' => 'To','defaultvalue' => 'now','skipmemory' =>
'qreport' => array('fieldtype' => 'qreporttype','label' => 'Report Type','defaultvalue' =>

'refresh' => 90,
'connection' => DB_CONN,

5.5 Creating Reports

Create a form using the settings array
Create a report handler call back function

• populate the dataset as defined by form values and/or constraints

• populate the table/graph formatting using $printdata

• call APE_printarray($dataset, $printdata) to plot data table

• call APE_graph_table($data2,
                array(data colours),
                DatasetHeaderRow (usually 0),
                array(dataset rows for data),
                XTitle (can be ""),
                YTitle (can be ""),

A Reference Guide for APE 4.0

                      Legend (can be NULL),
                      width (px),
                      height (px),
                      total line includes (bool),
                      XInterval (usually 1),
                      DoNotGraph (bool - usually true),
                      'type (line or bar)') to plot data graphically

• call APE_export($dataset, $printdata, $APEForm) to enable export options
5.6 An Extended Example

The following is an abbreviated walkthrough of APE/bin/items.php (?page=items) and
how it utilizes APE_forms and APE_printarray functions to control and display a table of

Begin by calling APE_form_range(); finds the APE_mem value or set the starting point
for the mySQL perpage limit. Then an array of form elements is defined.


       $settings = array(
                  'elements' => array(
                             * Flags:
                             * - "fieldtype" : What type of field (See the switch statement in APE_form_element);
                             * - "defaultvalue" : Well, the default value;
                             * - "elementparameter” : (mixed, array) Any special parameters you pass
        * - "label” : The text of the form element;
                             * - "sameline" : (boolean) The NEXT element will be on the same line;
                             * - "elementnote" : Small text at the right of the form element (side note);
                             * - "skipmemory" : (boolean) Doesn't read the moemry value. Applies default value;
                            'i_user_id'                    => array(
                                        'fieldtype'        => 'APE_createdby',
                                        'label'                     => APE_lang_get('VT100')
                            'i_assignee'          => array(
                                        'fieldtype'                 => 'APE_app_users',
                                        'defaultvalue'     => 1,
                                        'label'                     => APE_lang_get('245')

Note: It is possible to create custom fieldtype‟s by creating and including a function
called form_element in the local application.

Once all the form fields have been created in the settings array a call to
APE_form_validate is called, passing the name of your handler function, and the
settings array just created. this function will create and manage the html form.
       APE_form_validate('example_handler', null, $settings);

Now it is time to create the report_handler function as passed to APE_form_validate.
The handler function defines and constructs the table as presented in the browser,

A Reference Guide for APE 4.0

reads in the values submitted in the form or those settings found in memory by calling
back to the function.

        function example_handler($APEform) {

                  $MEM = $APEform['MEM'];

Once defined the $MEM array can now call back to the form emements by name, for
example; $MEM[„i_user_id‟]

Now columns of the output table are defined to match those values in the record set that
will be used.

        $table1_cols[0] = 'i_priority';
        $table1_cols[1] = 'i_level';
        $table1_cols[2] = 'i_number';
        $table1_cols[3] = 'i_app_id';

An array called $printdata is defined next. This array contains formatting and control
information for the data. $printdata is used in html tables, graphing and export options.
See Section 5.1 for more information.

        //define the formating
        $printdata['table1']['all'][0]['align'] = 'center';
        $printdata['table1']['all'][1]['align'] = 'center';
        $printdata['table1']['all'][2]['align'] = 'center';
        $printdata['table1']['all'][3]['align'] = 'center';
        $printdata['table1']['all'][11]['skip'] = true;

The next key step is to setup the sorting of the rendered table and to define how many
records will be shown per page. APE_sorter is passed the default column and direction
to sort by as well as the matching column definition array.

        // Sort
        $SORT = APE_sorter("i_date_updated",$table1_cols,"DESC");

        // If not mem setting for perpage then define one
        if (!$MEM["perpage"]) $MEM["perpage"] = 20;

Typically there is some custom logic and decision making done at this point before
proceeding to executing the primary SQL select statement to create the record set. If it
is a SQL recordset at all.

Note: the use of SQL_CALC_FOUND_ROWS as this is important in getting an acurate
count of returned records. Also note the ORDER BY and LIMIT values.

$SORT[“c”] = column, default or user selected as returned by APE_sorter.
$SORT[“c”] = direction, default or user selected as returned by APE_sorter.
$_GET[“fr”] = Determined in APE_form_range or by a link value.

// Main Query

A Reference Guide for APE 4.0

$cmd = "SELECT SQL_CALC_FOUND_ROWS i_text, i_priority, i_level, i_app_id, app_name, i_id, i_number,
i_status, i_private, i_title, i_responses, i_date_created, i_date_updated, i_updated_userid, i_user_id, i_assignee,
CONCAT(a1.lastname, \", \", a1.firstname) as Updated_Lastname, CONCAT(a2.lastname, \", \", a2.firstname) as
Assigned_Lastname ...
                    GROUP BY i_id
                    ORDER BY $i_example {$SORT["C"]} {$SORT["D"]}
                    LIMIT {$_GET["fr"]}, {$MEM["perpage"]}";

Typical handling of the SQL statement is now completed.
         $res = APE_sql_query($cmd,APE_DB_CONNECTION);
         $result = APE_sql_query("SELECT FOUND_ROWS()",APE_DB_CONNECTION);
         $total = APE_sql_fetch_row($result);
         $countrows = $total[0];

It is now possible call a builder function that will create a new associative array of the
working record set as well as apply html only formatting to individual rows and cells.
See the build_example function at the end of this section.
         $data1 = build_example($res,$printdata);

Settings for the table(s) to be displayed are now set.
         $printdata['table1']['total'] = false;
         $printdata['table1']['name'] = APE_lang_get('81');
         $printdata['table1']['title'] = APE_lang_get('81');
         $printdata['table1']['hidetitle'] = true;

Finally to display a functional html table APE_printarray is called and passed the array
returned from the builder function and the $printdata settings array.

         $result = APE_printarray($data1, $printdata);

Control functions like APE_pagination_numline will output navagiation objects when
passed related values.

         APE_pagination_numline(APE_PAGE, $_GET["fr"], $MEM["perpage"], $countrows);

The use of tabs, graphs and export are also wrapped in convient functions. The
following is an example demonstrates all of these.

         //Numberline control
         $ticket_tab .= APE_printarray($data1, $printdata);
         $ticket_tab .= APE_pagination_numline(APE_PAGE, $_GET["fr"], $MEM["perpage"], $countrows);

         $tabs = APE_tabs_add($tabs, APE_lang_get('114'), $ticket_tab);
         $tabs = APE_tabs_add($tabs, APE_TABS_EXPORT, APE_export(array($data1), $printdata, $APEform));

         return APE_tabs_print($tabs);

There are several examples using APE_forms and related functions throughout the
APE/bin files.

Examples of tables without control forms are also prevliant throughtout the APE
functionality when tables are used to display information and settings.

A Reference Guide for APE 4.0

The build_example function:

//note how $printdata is bassed by reference as to retain
//it‟s values in and out of the builder function
function build_example($res, &$printdata) {

         //the header row columns are defined with language strings
         $resultset[0][0] = APE_lang_get("116");
         $resultset[0][1] = APE_lang_get("VT114");
         $resultset[0][2] = APE_lang_get("HF5651");
         $resultset[0][3] = APE_lang_get("CT105");

         //begin a counter
         $c = 1;

         //standard SQL record set processing
         while ($data = APE_sql_fetch_array($res)) {

                  //printdata “preformated allows for html table cells contents to be altered or manipluated
                  $printdata["table1"][$c][9]["preformatted"] = APE_getbyid($updated_by);
                  $printdata["table1"][$c][10]["preformatted"] = APE_getbyid($data["i_assignee"]);

                  //a resultset array is defined from the SQL
                  $resultset[$c][0] = $data["i_priority"];
                  $resultset[$c][1] = $data["i_level"];
                  $resultset[$c][2] = round($data["i_number"]);
                  $resultset[$c][3] = $data["i_app_id"];


         return $resultset;
6.0 Creating Applications
There are two ways to create an application with the APE environment. By default a tool
is provided in the APE/bin/applications.php page. When file system permissions conflict
or an external application is being written the following process will enabled the creation
of a new application.

6.1 Default Files and Folders

Create a folder to contain the application; usually this is placed in parallel to the APE
folder but an application can sit anywhere in the web servers file structure. The name of
the folder will correspond to the APE_DIR constant as the active application identifier.
This is also the value of APP_ID as set in the ape_applications table as described

Within the created application folder create the bin subfolder. The bin folder contains the
php files directly related to your application. When required APE/bin files can be
superseded by custom or extended local versions.

A Reference Guide for APE 4.0

Also within the application folder create the includes subfolder. This folder should
contain any custom extensions of APE/core/functions.php, keys.php for database
connections or other local configuration or libraries.

Two files are required in the application folder.

The first file in the APE sequence is where custom library‟s, functions and other
resources are included an application. By default it includes the main APE config.php
and APE/starter.php. A variable $APE_root_path can be used to describe the custom
location of an application not installed in parallel.

// Toll-Free Reporting

// Include required scripts for app
$scripts = array('tfnfilter.js');

// Required files for APE integration

// Custom library and database connections.

An applications xmlrpc.php file should by default call the one provided in
APE/xmlrpc.php. Custom events and functions built for an application can be placed


An typical file structure will look like the following figure:


A Reference Guide for APE 4.0


6.2 Creating Database Entries

When possible the default APE/bin/applications.php form in Manage Applications
should be used to create the database entries for a new application. Even when it‟s not
possible to create the files and folders with this tool it should still create the values
needed in the database.

When it is not possible to create the table entries with the Manage Applications tool the
following entries can be made into the database manually or with scripting.

Insert into ape_applications
The values of the listed fields corresponds the constant descriptions in Section TODO.

app_id, app_type, app_manager, app_name, app_name_fre, app_owner, app_server,
app_group, app_url, app_tz, app_description, app_description_fre, app_bgurl1,
app_bgurl2, app_color1, app_color2, app_bgcolor1, app_bgcolor2, app_highlightcolor1,
app_header1, app_css, app_moderation_level, app_admin_level, app_min_level,
app_language_level, app_status, app_disable, app_order, app_module_title,
app_module_title_fre, app_protected, app_hidden, app_doc_title_eng,
app_doc_title_fre, app_start_page)
Insert into ape_permissions
Set an active user as an administrator for the application.

A MD5 string matching an account as found in the the ape_users table.

A string identifier matching the given value for APP_ID in ape_applications or the name
of the applications folder.

The level to assign as an integer. The typical value for an admin is 8. The highest
possible value is 9.

Insert into ape_levels
A set of descriptions must be provided for all the possible application levels one through
nine. (1-9)


A Reference Guide for APE 4.0



Level 1


This is the level 1 account.

7.0 Forms

There are several primary ways to handle the creation and management of form
controls within the APE framework. This section will outline examples of and the
recommended use of each of the following methods.

      •   Standard HTML forms
      •   Forms created with APE_form_validate
      •   Directly calling APE_form_element and APE_form_builder
      •   APE_form_element a Complete Listing
      •   APE_sql_display_record and related table related functions

7.1 HTML Forms

There is nothing to prevent the use of a standard <form> and it‟s input related elements.
The methods provided by APE are meant to speed development, provide consistency
and reduce code. It is possible and supported that the form and input processing can be
handled differently per application, page or option.

A Reference Guide for APE 4.0

7.2 Forms created with APE_form_validate

In previous sections of this document the use of APE_form_validate was utilized in the
output and control of a tabular dataset. It can also be utilized for other controlled
displays and control of information as required.

The settings array can process several attributes in setting up a form.
- "fieldtype" : What type of field (See the switch statement in APE_form_element);
- "defaultvalue" : Well, the default value;
- "elementparameter” : (mixed, array) Any special parameters you pass
- "label” : The text of the form element;
- "sameline" : (boolean) The NEXT element will be on the same line;
- "elementnote" : Small text at the right of the form element (side note);
 - "skipmemory" : (boolean) Doesn't read the memory value. Applies default value;

Custom fieldtype‟s add additional flexibility in how input fields are displayed and
accepted. See Section 7.4 for a complete listing of default elements.

A basic “hello world” example:
       $settings = array(
         'elements' => array('hello_world'
                  => array(
                  'fieldtype' => 'text',
                  'label' => „Hello World‟,
                            ‘elementparameter‟ => 15
       APE_form_validate('input_handler', null, $settings);

       function input_handler($APEform) {
         $MEM = $APEform['MEM'];

           //display the value submitted and saved in memory
           echo $MEM[„hello_world‟];

7.3 Directly calling APE_form_element and APE_form_builder

It is possible to call the internal functions of APE_form_validate directly when requiring
simpler access to the provided APE_form_element options.

//Will return a html formatted <select> with the current applications users listed and a label.
APE_form_element(„APE_app_users‟, „Application Users‟);

//Will return a html formatted <input type=”text”>.
APE_form_element(„text‟, „Name: ‟);

The full function description of APE_form_elements: TODO finish/check
 * Creates the form elements depending on the type given

A Reference Guide for APE 4.0

* @param string $element            The type of elements
* @param string $elementname        The HTML name attribute that will be given
* @param string $db_connection      Not used yet
* @param string $setvalue                   The default value
* @param string $default_value      The default value 2[?]
* @param string $parm
* @param string $type                        The type

APE_form_element($element, $elementname, $db_connection = null, $setvalue = null, $default_value = null,
$parameters = null)

When requiring a quick way to build and manage <select> and checkbox/radio button
choice arrays, the function APE_form_builder provides a quick solution to create a
<select> from the array generated from a record set. All of the APE_form_elements that
involve a <select>, checkboxes or radio buttons are created with APE_form builder as
this example for APE_pages demonstrates:

      case 'APE_pages':
        $cmd = 'SELECT stat_page FROM '.APE_TABLE_STATS.' GROUP BY stat_page';
        $res = APE_sql_query($cmd, APE_DB_CONNECTION);

        while ($row = APE_sql_fetch_array($res)) {
                 $select_array[$row['stat_page']] = $row['stat_page'];

        $ret .= APE_form_builder('select', $elementname, $select_array, null, $setvalue, array( 'enabledisableall' =>
true, 'columns' => 2 ));

7.4 APE_form_element a Complete Listing
The following represents all the included elements of APE_form_element. Each
application can create a custom list of elements by copying the format of
APE_form_element and creating a local application function called form_element with a
custom case select.

case 'start':
Creates a <form> tag and all the required parameters for a self submitting form.

case 'APE_applications':
Creates a checkbox list of installed applications that are not hidden or otherwise

case 'APE_pages':
Creates a listing of all possible page types as see by the stats table.

case 'APE_applications_select':
Creates a <select> list of installed applications that are not hidden or otherwise secured.

case "APE_createdby":

A Reference Guide for APE 4.0

Creates a <select> for users with permission relating to a item.

case 'APE_app_users':
Creates a <select> for users with permissions relating to the active application.

case 'APE_not_app_users':
Creates a <select> for users without permissions relating to the active application.

case 'APE_private':
Creates a Yes/No <select> for use in item privacy management.

case 'APE_category':
Creates a <select> list of all categories for an application.

case 'APE_folder':
Creates a <select> list of all folders for an application.

case 'APE_priority':
Creates a <select> list of APE defined priorities available to an item.

case 'APE_status':
Creates a <select> list of APE defined status options available to an item.
case 'APE_level':
Creates a <select> list of the levels associated to the active application.

case 'APE_since':
Created a data input field with a popup calendar for selecting the first value of a date

case 'APE_until':
Created a data input field with a popup calendar for selecting the second date of a

case 'APE_timezones':
Creates a full text listing of all available timezones.

case 'APE_srv_groups':
A listing of server groups.

case 'APE_services_types':
A listing of server types.

case 'APE_templates':
A listing of available templates associated to the application.

case 'APE_color':

A Reference Guide for APE 4.0

A text field with a color picker.

case 'boolean':
A simple True or False <select> element.

case "date":
Provides a text field with a popup calendar to select the current date. Can accept
several parameters to customize how the date is calculated and returned. TODO finish

case 'hour':
Creates a <select> list of all 24 hours in a day.

case 'minute':
Creates a <select> list 15 minute slices of minutes.

case "number":
Creates a <select> list of integers up to and including the $max value.

case "multiple":
Creates a multiple choice <select> from a list passed via parameters. TODO finish

case "timeint":
Creates a <select> of various incremental time slices.

case "timeint2":
Creates a <select> of various incremental time slices.

case "dayofweek":
Creates a <select> list of the days in a given week.

case "timeadjust":
Creates a <select> scale used to adjust timezones.

case 'saveas':
Creates a text field called saveas. This is a special case that will be used to create a
new saved tab for the submitted information.

case "textarea":
Creates a standard text area with 50 columns and 15 rows.

case 'text':
Creates a standard text field. Can be passed parameters to control size.

case "hidden":
Creates a standard hidden input field and accepts $setvalue as it‟s value.

A Reference Guide for APE 4.0

case "stop":
Creates a Submit button and a Reset link for the form.

7.5 APE_sql_display_record and related table related functions
8.0 Appendixes

8.1 APE Development

This appendix is intended to outline some of the features planned and in active
development. As well as those ideas discussed for TFNnet but not yet considered to be
in active development. Its purpose is to initiate discussion planning as to when each
item will be developed and in what manner as decided.

Current TFNnet Development

New Ticket Page
This item is complete other then a testing for small screen issues and a small problem with how the
assignee dropdown cannot be updated when switching apps as an admin using the development root.

Completely rewritten and updated the tracking of all user and application activities.

How users events are stored, shown and displayed has been updated on user profiles.

A basic framework is in place to show how reports can be extracted out of the event and activity data
collected above. Needs some discussion on what metrics would be most useful.

Ticket Track URL
Implemented in tfnharold, the last compete url accessed by the user is passed to the Create New Ticket

Application Status
Needs further design and development.

Reports are currently unable to completely utilize the printdata settings array.

Nic has implemented the current APE code base within his network. Several issues that were related to
linux compatibility and making the engine easier to move around different servers and development trees
was addressed.


    ·   Fplot - an alternative graphing library
    ·   Not yet evaluated

A Reference Guide for APE 4.0

    ·   IFrame - inline techniques to speed and smooth page loading.
    ·   Not yet officially implemented in development
    ·   Updated Layout Design and XAJAX
    ·   Not yet officially implemented in development

Furthering TFNnet Development

1. The development of an Application creation structure and other tools to facilitate hosting and
developer self-management.

Currently it is possible to create and manage a new application without looking at code, it would be
beneficial to extend this to incorporate a simple module editor (2) and other elements that would make
things easier to create, develop and manage new purpose built applications.

2. The development of tools to help with the creation and maintenance of end developer modules.

While the system currently uses a simple set-up for loading in application specific options (left panel)
there are several things that could be done to make the process easier and more robust. Adding a
module creation and editing tool, as well as providing a set of standard options eg. application specific
modules (TFR), Links (AS) or something like an application list and possibly the ability for the left pane to
provide status updates or free form text as needed. This enhancement would provide options for all
users/managers and/or a structure to code for tasked developers.

3. The development of full-featured tools to monitor and maintain servers associated to a given

Currently there is no feature complete way to add servers and services to monitor through the TFNnet
interface. There is a simple functional tool but for the most part we still add servers and services directly
through the phpMyAdmin interface. As of today a student has been tasked with coming up a tool.

4. The development of a Help feature primarily focused on video presentations of TFNnet

This feature has taken some turns as we develop how to accept and serve large to larger files. The vision
as it stands today is to create a file storage service related to the tickets. Depending on what type of files
are uploaded by a user they are served not only from the ticket screen but aggregated by file type. So
there would be a video's screen (eg. utube), a file browser (eg. Explorer) and/or an excel specific tool for
browsing/working with excel or other office documents. User profiles would also be updated (5) to
show/browse all of the users files and related tickets. All of this would be be restricted by permissions
and/or ownership rights.

5. An overhaul of the users profile/account page.

Several items have been purposed for incorporation into the users account page. Development would be
keyed on further integrating the users application(s) activity, ticket activity(s), history, files (4), status
changes and contacts. Further then just providing permissions based portal of a users account activity
profiles would offer some personalization eg. through subtle colour changes, photos and/or other
social/personal aspects. The idea would be to build up a detailed view of each user while giving more for
users to visit TFNnet beyond application tasks.

A Reference Guide for APE 4.0

6. RSS and XML integration

Several aspects of site could be enhanced though the integration of RSS/XML. Different views of tickets
(blog/tickets/ticket) could have a permissions restricted ability to generate an xml based RSS feed. User
account pages would have a feed detailing the users activity. RSS for each application to detail the
location and status of contacts. A feed for the monitor to show the status of one or all requested servers.
Finally an RSS/XML capable display module (3) should be developed.

7.0 Monitor 2.0

There are several aspects of the monitor that could be enhanced to be more useful and reliable. The
specifics of these changes would need some discussion but one key element would be to integrate more
beyond the simple management of servers. A major requirement would be the ability to monitor tickets
and take actions (email) based on parameters. eg. Emailing assignees about long open tickets,
escalating emails for tickets without response and possibly reporting (8) out on tickets. The monitor
should also be extendable with the ability to take custom cron like jobs from current and future

8. Reporting Everything

As TFNnet grows there is a need for granular information on usage. It would be beneficial if a core
reporting application was developed to monitor all application usage as well as a reporting tab for each
individual application. Things to track would be from the very basic, views/visits to the specific; ticket
counts by status, assignee/user action counts, average time to respond for tickets, server activity reports
and other measurable statistics (eg TFR module report usage) to be identified through discussions.

9. Future Ticketing and Scheduling

One element that would be interesting is the ability to create new tickets that would not actually be apart
of the system until a specified date and/or recurring on specific dates. This item would likely mean
another overhaul and upgrade of the ticket entry form as well as a look at how tickets are displayed. This
feature would tie back to the monitor (7) which would be responsible for activating tickets, reminders and
other scheduled items as they become current.

10. Other (partial list)
- Continue the further development of Ajax/JS features to provide better usability
- Building more features and functionality into the Inbox
- Ability to control thresholds per report (TFR)
- Constant publishing of Change Logs and Release Notes for users and developers
- Adding application short name to tickets table when view multiple apps via TFNnet
- Developing or removing Pinned items feature
- Further development and usage of the ticket Tags feature
- Rewrite of the Organize page to be more clear
- Fix bugs with the large calendar and how it links to tickets, possibly use for more
- Fix the Print ability
- Cleanup the Servers page to be more compact
- Indicate required items on Create Ticket form
- Polish fonts, spacing and other aesthetic visual elements throughout the application(s)
- Fix display errors when outputting who was mailed on a given ticket/response
- Discussions to go over the application in fine detail to get developer/management input


To top