Advanced Website Creator


1. Description of the web interface
1.1. Administrative interface
1.1.1. Login
1.1.2. Registered users
1.1.3. Add a new user
1.1.4. Edit a user
1.1.5. System settings
1.2. User interface
1.2.1. Login
1.2.2. List of projects
1.2.3. Add a new project
1.2.4. Load a project
1.2.5. Project management area
1.2.5.1. Project info
1.2.5.2. Project settings
1.2.5.3. Actions
1.2.5.4. Action add
1.2.5.5. Action properties
1.2.5.6. Action handler
1.2.5.7. Action fields
1.2.5.8. Add an action field
1.2.5.9. Edit an action field
1.2.5.10. Action forwards
1.2.5.11. Add a forward definition
1.2.5.12. Edit a forward definition
1.2.5.13. Forward arguments
1.2.5.14. Action templates
1.2.5.15. Action template edit
1.2.5.16. Project constants
1.2.5.17. Project database definition
1.2.5.18. Project field definitions
1.2.5.19. Add a new field definition
1.2.5.20. Edit a field definition
1.2.5.21. Field checks
1.2.5.22. Add a new field check
1.2.5.23. Edit a field check
1.2.5.24. Project include files
1.2.5.25. Edit a project include file
1.2.5.26. Project lists
1.2.5.27. Add a new list definition
1.2.5.28. Edit a list definition
1.2.5.29. List elements
1.2.5.30. Project URLs
1.2.5.31. Add a new URL
1.2.5.32. Import a package
1.2.5.33. Edit a URL
1.2.5.34. Wizard: Form
1.2.5.35. Wizard: VADE (a.k.a CRUD)
2. Structure of the project database definition
2.1. General description
2.2. Comments
2.3. Expressions
2.4. Database types
2.5. Database sequences
2.6. Database tables
2.7. Database views
2.8. Database PL/SQL functions
2.9. Database named queries
2.10. Database definition functions
2.10.1. User-defined functions
2.10.2. Built-in function definitions
2.11. Including other definition files
3. PHP Library classes
3.1. lib_db - Database library class
3.2. lib_event - Event library class
3.3. lib_file - File library class
3.4. lib_json - JSON library class
3.5. lib_list - Lists library class
3.6. lib_mail - Multipart email library class
3.7. lib_misc - Miscellaneous library class
3.8. lib_nested_set - Tree library class
3.9. lib_sorted_list - Sorted list library class
3.10. lib_shutdown_callbacks - A library for registering/unregistering shutdown callbacks
4. Miscellaneous
4.1. Implementation details of the Model-View-Controller (MVC) runtime framework

Chapter 1. Description of the web interface

1.1. Administrative interface

The administrative interface can be accessed at http://your-website-url/admin where your-website-url is the domain or IP address where Advanced Website Creator (AWC) has been installed. The administrative interface is used rarely - usually you need to use it immediately after AWC installation in order to adjust the global settings of AWC and to create initial AWC users. After that initial setup you will only need to use the administrative interface in order to add or remove AWC users. Below is a detailed description of different administrative pages.

1.1.1. Login

This is the page where you will be prompted for an admin username and password, so enter the admin username and passwords which you have chosen during AWC installation. Upon a successful login you will be taken to the Registered users page.

1.1.2. Registered users

This is the page you are taken to immediately after an administrative login. You can also reach this page by clicking on the Users link on the left sidebar. From here you can go to the Add a new user page by clicking on the Add a new user link. Below that link is the list of already existing users (initially this list is empty). You can edit an existing user by clicking on his username or delete him by clicking on the DELETE button.

Warning

When you delete a user all his projects are deleted as well and cannot be undeleted later, so use the delete command carefully.

1.1.3. Add a new user

From this page you can add a new user. In order to do that enter his username and password and then click on the ADD button.

1.1.4. Edit a user

From this page you can edit the username or password for some user. Enter the new data and click the UPDATE button to change the user data.

1.1.5. System settings

You can reach this page by clicking the Settings link on the left sidebar. From here you can adjust the global settings which must be configured for AWC to work correctly. Below is a detailed list of different fields and their meaning:

  • Temporary files directory: While working AWC creates temporary files and directories. This setting specifies the directory where such temporary files and directories are created. On most Linux servers /tmp/ is a value that will work fine, but if you want you can specify a separate directory that will be used only by AWC. Just make sure that AWC has write permissions for the specified directory. It is recommended that you specify an absolute pathname. This field is mandatory, i.e. it cannot be left empty.

  • Zend Encoder pathname: This setting is used by AWC when you require encoding of a compiled project with Zend Encoder. In this case AWC will try to encode the compiled code, using the encoder pathname specified in this field. It is recommended that you specify an absolute pathname. This field is optional. If you leave it empty, then Zend encoding of compiled projects will be disabled.

  • IonCube Encoder pathname: This setting is used by AWC when you require encoding of a compiled project with IonCube Encoder. In this case AWC will try to encode the compiled code, using the encoder pathname specified in this field. It is recommended that you specify an absolute pathname. This field is optional. If you leave it empty, then IonCube encoding of compiled projects will be disabled.

  • Site run directory: When you choose to run a project from within AWC, the project will be compiled into the specified directory and a new browser will be opened and navigated to the site run url. Since there can be multiple user accounts, AWC needs to use different run directories for different users. In order to achieve this, it recognizes special expansion strings inside the field value, then these strings are replaced with so called expansion values. The table below lists special strings and their expansion values:

    Expansion stringExpansion value
    %%The % character
    %iThe user ID. This is a unique numeric value assigned to the user by AWC.
    %nThe username as assigned by the administrator when the user is created.

    For example if the site run directory field contains the value /var/www/vhosts/%n/htdocs/ then the site run directory for a user with username john will be /var/www/vhosts/%n/htdocs/. This field is mandatory, i.e. it cannot be left empty.

  • Site run url: When a project is run from within AWC, it outputs the compiled project into the user site run directory, and after that a browser window is opened and navigated to the compiled project website. Since AWC does not know beforehand how to find the URL for the site run directory, it needs the site run url value from which the website URL is calculated. The same expansion strings are supported as for the site run directory. For example is the site run url field contains the value http://%n.your-site.com/ then the site run url for user thomas will be http://thomas.your-site.com/. This field is mandatory, i.e. it cannot be left empty.

  • Layout quick select: This box allows you to quickly select values for the other file layout fields. Following profiles are supported:

    • Generic: A generic layout that places the system directory inside the website document root. This layout will work on any server, but it has a couple of drawbacks:

      • You have to watch out when naming directory URLs so that they do not clash with the system directory.

      • If your webserver does not support .htaccess files, then contents of the system directory will be accessible from the client browser.

    • AWC: An AWC-specific layout, that places the system files in a directory outside of the website document root.

    • Plesk: A layout designed for websites using the Plesk control panel. The system files are placed in a Plesk specific directory called private/.

  • Layout htdocs directory: This field contains the pathname of the website document root. The pathname is relative to the website run directory. The value must be a relative pathname which cannot point outside of the run directory. If you leave this field empty then the document root is assumed to be the same directory as the website run directory.

  • Layout system directory: This field contains the pathname of the website system directory. The system directory contains directories and files that are used by the server-side code, but should not be directly accessible from the client web browser. The pathname in this field is relative to the website run directory, so it must be a relative pathname which cannot point outside of the run directory. If you leave this field empty then the system directory is assumed to be the same directory as the website run directory.

  • Layout protect system directory: Check this box if you want to deny web clients access to the system directory. You need this protection only when the system directory is located inside the website document root. If the system directory is located outside of the document root, it is not accessible from the web, and there is no need to explicitly protect it. Protection of system directory is achieved by using a .htaccess file, so your website must allow usage of .htaccess files in order for this protection mechanism to work correctly.

  • MySQL test server: If you plan to run from within AWC websites that use the MySQL database engine, then you should enable this option.

  • MySQL connect mechanism: If you plan to run projects that use a MySQL backend, then you need to specify connection settings to use when connecting to the server. For the connection mechanism you can use either UNIX-domain socket or TCP . This field is mandatory, i.e. it cannot be left in a [not selected] state.

  • MySQL socket file: If you plan to run projects that use a MySQL backend connecting to a UNIX-domain socket, then you can specify the pathname of the socket file. This field is optional. If you leave it empty then a default value (usually /tmp/mysql.sock) will be used.

  • MySQL host: If you plan to run projects that use a MySQL backend and connect to the MySQL server via a TCP socket, then you should specify the hostname or IP address of the MySQL server. This field is mandatory, i.e. it cannot be left empty.

  • MySQL port: If you plan to run projects that use a MySQL backend and connect to the MySQL server via a TCP socket, then you can specify the socket port number. This field is optional. If you leave it empty then a default value (usually 3306) will be used.

  • MySQL admin username: When running projects that use a MySQL database backend, AWC needs to create and drop databases and users. In order to do that it needs to know the username and password of a MySQL user that has sufficient privileges. Usually the MySQL user that has such privileges is called root. This field is optional. If you leave it empty then the default MySQL username will be used when creating and dropping databases and users.

  • MySQL admin password: When running projects that use a MySQL database backend, AWC needs to create and drop databases and users. In order to do that it needs to know the username and password of a MySQL user that has sufficient privileges. This field is optional. If you leave it empty then the default MySQL password will be used when creating and dropping databases and users.

  • PostgreSQL test server: If you plan to run from within AWC websites that use the PostgreSQL database engine, then you should enable this option.

  • PostgreSQL connect mechanism: If you plan to run projects that use a PostgreSQL backend, then you need to specify connection settings to use when connecting to the server. For the connection mechanism you can use either UNIX-domain socket or TCP . This field is mandatory, i.e. it cannot be left in a [not selected] state.

  • PostgreSQL socket directory: If you plan to run projects that use a PostgreSQL backend connecting to a UNIX-domain socket, then you can specify the directory where the socket file is located. This field is optional. If you leave it empty then a default value (usually /tmp/) will be used.

  • PostgreSQL socket extension: If you plan to run projects that use a PostgreSQL backend connecting to a UNIX-domain socket, then you can specify the socket file extension. This field is optional. If you leave it empty then a default value (usually .5432) will be used.

  • PostgreSQL host: If you plan to run projects that use a PostgreSQL backend and connect to the PostgreSQL server via a TCP socket, then you should specify the hostname or IP address of the PostgreSQL server. This field is mandatory, i.e. it cannot be left empty.

  • PostgreSQL port: If you plan to run projects that use a PostgreSQL backend and connect to the PostgreSQL server via a TCP socket, then you can specify the socket port number. This field is optional. If you leave it empty then a default value (usually 5432) will be used.

  • PostgreSQL admin username: When running projects that use a PostgreSQL database backend, AWC needs to create and drop databases and users. In order to do that it needs to know the username and password of a PostgreSQL user that has sufficient privileges. Usually the PostgreSQL user that has such privileges is called postgres. This field is optional. If you leave it empty then the default PostgreSQL username will be used when creating and dropping databases and users.

  • PostgreSQL admin password: When running projects that use a PostgreSQL database backend, AWC needs to create and drop databases and users. In order to do that it needs to know the username and password of a PostgreSQL user that has sufficient privileges. This field is optional. If you leave it empty then the default PostgreSQL password will be used when creating and dropping databases and users.

1.2. User interface

The user interface can be accessed at http://your-website-url/ where your-website-url is the domain or IP address where AWC has been installed. The user interface is where you create, edit and run projects. Below is a detailed description of different user pages.

1.2.1. Login

This is the page where you will be prompted for a username and password in order to login as a user. You can manage existing users or create new ones from the administrative Registered users page. Upon a successful login you will be taken to the List of projects page.

1.2.2. List of projects

This is the page you are taken to immediately after a user login. You can also reach this page by clicking on the Projects link on the left sidebar. From this page you can add a new project by clicking on the Add a new project link, add a project from a savefile by clicking on the Load a project link or manage one of the existing projects listed in the table. For each listed project you can save it in a file by clicking on the SAVE button, delete it by clicking on the DELETE button or start editing it by clicking on the on project name.

1.2.3. Add a new project

From this page you can add a new project. Below is a detailed list of different fields and their meaning:

  • Project name: The project name. This field is mandatory, i.e. it cannot be left empty.

  • Base URL path: In order to adjust the URLs in the compiled project, AWC needs to know the pathname part of the URL where your compiled project will run. For example if your project will be installed to http://www.your-server.com/project/path/ then the base URL path will be /project/path/. If the website will run on it own domain e.g. http://my.own-domain.com then the base URL path will be /. The value must always be an absolute path so it must always start with a / and one additional requirement is that it always ends with a /. This setting only affects the Build command, because the Run command uses a base URL path computed from the site run URL admin setting. This field is mandatory, i.e. it cannot be left empty.

  • Enable debug log: Check this box if you want to enable generation of a debug log in logs/debug.log in the project run directory.

  • Prefer action aliases: If you check this box, then AWC will use replace action URLs with URL aliases wherever possible. Please note that enabling this option does not automatically create URL aliases for actions and you still have to manually add URL aliases for different actions. This option just means that whenever you add an alias for some action, AWC will use the added action alias instead of the action URL. If you want to have search-friendly URLs you should enable this option.

  • Relocatable website: This setting specifies whether the compiled website will be able to work correctly after you move it to a URL pathname different from the base URL path. Below is a table summarizing the information about this setting:

    Setting valueURLs inside compiled text URLsURLs inside compiled templatesCan run from any base URL pathHTML code of the websute can be saved and viewed statically.Website execution speedAdditional limitations
    NoAbsoluteAbsoluteNoNo, unless the links inside text URLs and action templates are adjusted.FastNo
    PartialRelativeAbsolute but recomputed every time the template is displayedYesNo, unless the links inside action templates are adjusted.AverageYes
    FullRelativeRelativeYesYesSlowYes

    As you can see there is tradeoff between flexibility and execution speed - the Full setting allows greatest flexibility but slowest website execution speed. However the Partial and Full settings have one additional limitation which does not exist for the No setting - not all text URLs can be compiled when the relocatable setting is Partial or Full. E.g. if there is a text URL in dir_1/file.html and an alias in dir_2/dir_3/alias pointing to the text URL, then trying to reference any actions or URLs from that text URL will result a compile error. The generic rule is that if a text URL references any actions or URLs then all aliases pointing to that text URL must contain the same number of path segments as the text URL.

    Generally it is recommended to leave this setting at No, unless you really need a relocatable website.

  • Encoder: The PHP encoder that you want to use. This field is mandatory, i.e. it cannot be left in a [not selected] state.

  • Encode expire: Choose expire type of the encoded project. Following expire types are supported:

    • Expire in a period: The compiled project will expire in a specified number of seconds, minutes, hours or days after the moment when it has been compiled. Please note that for the Zend encoder expiry in a period is emulated via expiry on a date, so the actual expiry moment is always midnight of the calculated expire day. E.g. if you have a project that is configured to expire 48 hours after compile and you compile it at 15:30:10 on Feb/24/2007, then it will actually expire on Feb/26/2007 at 00:00:00 instead of on Feb/26/2007 at 15:30:10. This limitation does not exist if you are using the IonCube encoder.

    • Expire on a date: The compiled project will expire at 00:00:00 on the specified date, regardless of the moment when it has been compiled.

  • Expire period: The number of seconds, minutes, hours or days after which the compiled project will expire. The actual expire units are chosen from the Expire units select box.

  • Expire units: Choose the actual time units in which is measured the expire period.

  • Expire date: Put in this field the date on which the compiled project will expire. The value must be in the following format YYYY-MM-DD, where YYYY is the four-digit year (must be 1970 or greater), MM is the one or two-digit month number and DD is the one or two-digit day of month. E.g. if you put in this field 2010-02-10 then the compiled project will expire of Feb/10/2010 at 00:00:00.

  • Layout quick select: This select box allows you to configure quickly the values in the other layout fields. It has the same meaning as the layout quick select box field on the administrative pages, but it applies only to project builds created from the Build menu item. For project runs from within AWC, the system uses the layout configured from the administrative pages.

  • Layout htdocs directory: This field contains the pathname of the website document root. It has the same meaning as the layout htdocs directory field on the administrative pages, but it applies only to project builds created from the Build menu item. For project runs from within AWC, the system uses the system directory configured from the administrative pages.

  • Layout system directory: This field contains the pathname of the website system directory. It has the same meaning as the layout system directory field on the administrative pages, but it applies only to project builds created from the Build menu item. For project runs from within AWC, the system uses the system directory configured from the administrative pages.

  • Layout protect system directory: Check this box if you want to deny web clients access to the system directory. This checkbox has the same meaning as the layout protect system directory checkbox on the administrative pages, but it applies only to project builds created from the Build menu item. For project runs from within AWC, the system uses the protection setting configured from the administrative pages.

  • Database engine: The database engine that you want to use. At the moment MySQL and PostgreSQL are the two supported database engines. This field is mandatory, i.e. it cannot be left in a [not selected] state.

  • Database connect mechanism: You can optionally choose a database connection mechanism. At the moment two connection mechanisms are supported - UNIX-domain sockets and TCP. The setting of this field does not affect the Run command since that command is using the database settings from the administrative settings page. However it affects the connection data in include/generated/config.inc for sites created via the Build command. This field is optional, if you do not choose a database connection mechanism you will have to edit include/generated/config.inc and adjust the connection mechanism just before you install the website on a webserver.

  • Database socket directory: If you are using a PostgreSQL database backend and are connecting to it via a UNIX-domain socket, then you can optionally specify the directory where the UNIX-domain socket is located. The setting of this field does not affect the Run command since that command is using the database settings from the administrative settings page. However it affects the connection data in include/generated/config.inc for sites created via the Build command. This field is optional, if you do not choose a socket directory you can optionally edit include/generated/config.inc and adjust the socket directory just before you install the website on a webserver.

  • Database socket extension: If you are using a PostgreSQL database backend and are connecting to it via a UNIX-domain socket, then you can optionally specify the extension of the UNIX-domain socket. The setting of this field does not affect the Run command since that command is using the database settings from the administrative settings page. However it affects the connection data in include/generated/config.inc for sites created via the Build command. This field is optional, if you do not choose a socket extension you can optionally edit include/generated/config.inc and adjust the socket extension just before you install the website on a webserver.

  • Database socket file: If you are using a MySQL database backend and are connecting to it via a UNIX-domain socket, then you can optionally specify the pathname of the UNIX-domain socket file. The setting of this field does not affect the Run command since that command is using the database settings from the administrative settings page. However it affects the connection data in include/generated/config.inc for sites created via the Build command. This field is optional, if you do not choose a socket pathname you can optionally edit include/generated/config.inc and adjust the connection mechanism value for the website just before you install the website on a webserver.

  • Database host: If you are connecting to the database server via a TCP socket, you can optionally specify the hostname or IP address of the database server. The setting of this field does not affect the Run command since that command is using the database settings from the administrative settings page. However it affects the connection data in include/generated/config.inc for sites created via the Build command. This field is optional, if you do not choose a server hostname or IP address you will have to edit include/generated/config.inc and adjust the connection mechanism value for the website just before you install the website on a webserver.

  • Database port: If you are connecting to the database server via a TCP socket, you can optionally specify the port number of the database server. The setting of this field does not affect the Run command since that command is using the database settings from the administrative settings page. However it affects the connection data in include/generated/config.inc for sites created via the Build command. This field is optional, if you do not choose a port number you can optionally edit include/generated/config.inc and adjust the port number value for the website just before you install the website on a webserver.

  • Database username: In this field you can specify the username to be used when connecting to the database server. The setting of this field does not affect the Run command since that command is using the database settings from the administrative settings page. However it affects the connection data in include/generated/config.inc for sites created via the Build command. This field is optional, if you do not choose a username you will have to edit include/generated/config.inc and adjust the username value for the website just before you install the website on a webserver.

  • Database password: In this field you can specify the password to be used when connecting to the database server. The setting of this field does not affect the Run command since that command is using the database settings from the administrative settings page. However it affects the connection data in include/generated/config.inc for sites created via the Build command. This field is optional, if you do not choose a password you will have to edit include/generated/config.inc and adjust the password value for the website just before you install the website on a webserver.

  • Database name: In this field you can specify the database to be used when connecting to the database server. The setting of this field does not affect the Run command since that command is using the database settings from the administrative settings page. However it affects the connection data in include/generated/config.inc for sites created via the Build command. This field is optional, if you do not choose a database name you will have to edit include/generated/config.inc and adjust the database name for the website just before you install the website on a webserver.

1.2.4. Load a project

From this page you can load a project from a savefile (usually savefiles have the extension .awc). Choose a name under which the project will be imported and a project savefile from your local filesystem then click on the ADD button.

1.2.5. Project management area

Project management area is where actual project development takes place. Initially after selecting a project for editing you taken to the project info page. Clicking on the links on the left sidebar will take you to pages where you can view and edit different parts of your project. Below is a detailed list of different pages in the project management area.

1.2.5.1. Project info

This is the first page you are taken to after entering the project management area. You can also reach it by clicking on the Info link on the left sidebar. On this page you can see info about your project - project name, database engine type, PHP encoder used, etc.

1.2.5.2. Project settings

From this page you can view and alter project settings which you have selected during project creation. Also there are several settings that are not explicitly set when a new project is added, but you can view and change these settings from the settings page. Below is a detailed list of different fields and their meaning:

1.2.5.3. Actions

You can reach this page by clicking on the Actions link on the left sidebar. It lists all the project actions which are organized in a tree. Empty actions are the actions that have empty action handlers. Such empty actions do not have URLs corresponding to them, so they cannot be used in {ACTION:...} tags or as redirect or alias targets. Empty actions have their names displayed in black color on the actions page. Non-empty actions can be used in {ACTION:...} tags or as redirect or alias targets. Non-empty actions have their names displayed in blue color.

On the action tree there are clickable links for different operations that can be applied to each action. These links are located on the right side of each action name. Below is a description of these links:

  • add: Allows you to add a new action. The newly added action will be a child of the specified action. For details on this see the action add page.

  • del: Deletes the specified action node and all of its descendant action nodes.

  • props: Takes you to the action properties page.

  • handler: Opens the action handler page in a new window.

  • fields: Takes you to the action fields page.

  • fwd m/n: Takes you to the action forwards page. m is the number of forwards defined by the action itself and n is the number of forwards accessible from the action handler. An action handler can access all the forwards defined by the action or by one of its direct or indirect parents.

  • tpl m/n: Takes you to the action templates page. m is the number of templates defined by the action itself and n is the total number of templates accessible from the action forwards or included via the {INCLUDE:...} tag. An action can access all the forwards defined by the action or by one of its direct or indirect parents.

1.2.5.4. Action add

From this page you can add a new action. Below is a detailed list of different fields and their meaning:

  • Name: This field contains the action name.

  • Session access: This setting describes the access type which is allowed for the $session variable which is passed as a parameter to each action handler.

    Table 1.1. Session access types

    Access typeType of $session variableArray reads resultArray writes result
    NonenullAll reads return null.A fatal error is issued after termination of the action handler.
    ReadArrayThe corresponding session array property is returned.If content of the session variable have been changed a fatal error is issued after termination of the action handler.
    Read/WriteArrayThe corresponding session array property is returned.After termination of the action handler, the new contents of the session variable are saved.

    Please remember that for Read and Read/Write access types there are respectively read and write locks placed on the session object. This means that in order to improve the performance you should try to use session access None wherever possible, and prefer session access Read to session access Read/Write.

  • Enable HTTP cache: When this box is not checked, the runtime framework will send several HTTP headers which prevent caching of the returned web page by the browser or by any HTTP proxies. Check this box if you want to avoid sending these headers.

1.2.5.5. Action properties

From this page you can edit action properties for existing actions. Page fields are same as the ones on the action add page.

1.2.5.6. Action handler

From this page you can edit the contents of the handler for the chosen action. The action handler consists of PHP code which instructs the runtime framework what to do next after the action handler terminates. Upon project build AWC wraps the action handler in a function which looks like:

function action_handler (&$session, &$fields)
{
    your custom code for the action handler
}

The action_handler function is called by the runtime framework each time when someone requests a website URL that corresponds to an action. The runtime framework also passes two parameters to the action handler. Below is a detailed description of these parameters:

  • session: This argument is an array that allows the action handler to keep some data persistent between HTTP requests. Data stored in the session array is private to each session, i.e. you can have multiple simultaneous sessions and each session will have access only to its own session data. Behavior of this array depends on the session access type setting for the action. See the corresponding action property for more info.

  • fields: The HTML fields array is passed as an argument to the user-defined action handler. It allows the action handler to:

    • Read the values and error codes of action input fields.

    • Modify the values and error codes of input fields.

    The fields array is indexed by field names. Each entry in the fields array is an array that contains the following elements:

    • value: The field value. The type of this array element depends on the field type. For a list of value types for different field types see this table.

    • error: The error message for that field. A null error means that there is no error for that field.

    The value and error code of each input field is set by the framework. Upon an HTTP request the framework iterates through the fields specified in the action definition, tries to fetch each field value and if the value has been fetched successfully, runs the specified field checks. After that the value and error of each field are set accordingly. The data type of each field value is dependent on the field type. The error is either a string or a null, where a string value is the actual error message and a null value means that there is no error. You can call field_manager::is_ok($fields) in order to check if there is an error in some field. This function returns true if and only if all fields have their error messages set to null.

An action handler should return a forward array. The forward array is a PHP array with numeric indexes, where the first element contains the forward name and the other elements contain the forward arguments, if any. The forward array instructs the PHP runtime about the final action to take before sending an HTTP reply to the user. For more info about action forwards see the section on forward types. Here are some examples of user-defined handlers returning forward arrays:

return (array ("login"));

The above example returns a forward array using the forward login and no forward arguments.

return (array ("show", 123, "Hello", "World"));

The above example returns a forward array using the forward show and three forward arguments: 123, "Hello" and "World".

if ($fields ["username"]["error"] === null) {
    if (lib_db::read_by_filter (
        "users",
        array ("username" => $fields ["username"]["value"])
    ) !== null) {
        $fields ["username"]["error"] = "This username is already taken.";
    }
}
if (field_manager::is_ok ($fields) == false) {
    return (array ("show"));
}
lib_db::create ("users", array (
    "user_id" => lib_db::next_id ("user_id"),
    "username" => $fields ["username"]["value"],
    "password" => $fields ["password"]["value"]
));
return (array ("list"));

The above sample action handler is a bit more complex than the previous two ones. First it checks if the username field has been entered correctly and if so checks if a user with the desired username already exists, i.e. if the username is already taken. After that the action handler checks the overall status of all fields and if there is some field that has an error, a forward called show is invoked. If there are no field errors, a new user is created using the username and passwords from the action input fields. After that a forward called list is invoked.

1.2.5.7. Action fields

Each action has a list of input fields that are optionally fetched from the $_GET, $_POST and $_FILES arrays and then placed in the $fields parameter of the action handler. The action fields page shows you the list of form fields accessible from the specified action. You can reach the action field page by clicking on a fields link on the action list page.

From the action fields page you can reach the add a new action field page, edit an existing action field or delete an existing action field.

1.2.5.8. Add an action field

From this page you can add a new action input field. Below is a detailed list of input field settings:

  • Field name: Choose the name of the input field. This is the name under which the field will be imported into the $fields array.

  • Field definition: Choose a field definition that will be imported. You can view and edit field definitions from the field definitions page.

  • Fetch: When an action is being executed, the runtime framework creates an array index inside the $fields pseudo-array, for each imported field definition. The Fetch checkbox determines whether the runtime framework will actually try to populate the field value from the $_GET, $_POST or $_FILES array or will leave the field initialized with its default(empty) value.

1.2.5.9. Edit an action field

From this page you can edit an existing action field. Page fields are same as the ones on the add an action field page.

1.2.5.10. Action forwards

This page list the forwards defined by this action. From this page you can do the following:

  • Go to the add a forward definition page by clicking on the Add a new forward definition link.

  • Go to the edit a forward definition page by clicking on the name of the chosen forward.

  • Go to the forward arguments page by clicking on the ARGS button for the chosen forward. Please note that the ARSG button is displayed only for forward types that support user-defined arguments.

  • Delete an existing forward definition by clicking on the corresponding DELETE button.

1.2.5.11. Add a forward definition

From this page you can add a new forward definition for the chosen action. Below is a detailed list of different input fields and their meaning:

  • Forward name: The name of the forward.

  • Forward type: The type of the forward. Here is a description of supported forward types:

    Table 1.2. Forward types

    Forward typeForward argumentsForward description
    NoneNoneThis forward assumes that user-defined handler has already taken care of the forward action, so the framework does not need to do anything.
    TemplateZero or more. Argument names are specified explicitly in forward definition. Argument values are specified explicitly in forward array. These arguments are turned into template variables upon template invocation.Displays the specified template as HTML code.
    Redirect (temporary)Zero or more. Argument names are specified explicitly in forward definition. Argument values are specified explicitly in forward array. These arguments are turned into url GET variables when making the HTTP redirect.Sends a temporary HTTP redirect to the URL specified in argument definition.
    Redirect (Permanent)Zero or more. Argument names are specified explicitly in forward definition. Argument values are specified explicitly in forward array. These arguments are turned into url GET variables when making the HTTP redirect.Sends a permanent HTTP redirect to the URL specified in argument definition.
    DownloadThree arguments: filename, mime_type, data. Argument names are not specified explicitly in forward definition. Argument values are specified explicitly in forward array.Sends data to the client browser using the specified filename and mime type. Can be used for implementing file downloads restricted only to authorized users.


  • Target template: Specifies the displayed template. This field is only available for forwards of type Template.

  • Target action: Specifies the action to redirect the browser to. This field is only available for redirect forwards.

1.2.5.12. Edit a forward definition

From this page you can edit an existing forward definition. Page fields are same as the ones on the Add a forward definition page.

1.2.5.13. Forward arguments

This page lists the arguments for the chosen forward. From that page you can add, rename, reorder and delete action argument names.

1.2.5.14. Action templates

This page lists all forward templates defined by the chosen action. From this page you can:

  • Upload a new template, by choosing a file to upload, entering a template name and clicking on the ADD button.

  • Create a new empty template, by leaving the upload field empty, entering a template name and clicking on the ADD button.

  • Open the template edit page by clicking on the name of the selected template.

  • Rename an existing template by clicking on the corresponding RENAME button.

  • Download an existing template by clicking on the corresponding D/L button.

  • Delete an existing template by clicking on the corresponding DELETE button.

All templates are text files that usually contain HTML code with the page layout. Templates support following tags:

Table 1.3. Template tags

Template tagTag description
{INCLUDE:name}Processes current template as if contents of template name had appeared in the current template in place of the INCLUDE tag.
{URL:path}The tag is replaced with the URL with pathname path.
{VAR:name}The tag is replaced with the value of template variable name.
{ACTION:path}The tag is replaced with the URL of the action with pathname path.
{FIELD:name:attributes}The tags is replaced with the HTML code for input field name. If attributes is a non-empty string, it is treated as HTML attributes which are added to the generated HTML input tag.
{ERROR:name}The tag is replaced with the error message for the input field name.


1.2.5.15. Action template edit

From this popup page you can edit the text contents of the chosen template.

1.2.5.16. Project constants

You can reach this page by clicking on the Constants link on the left sidebar. From this page you can add, edit, delete project constants. They are regular PHP case-sensitive constants that will be visible inside all action handlers and include files.

1.2.5.17. Project database definition

You can reach this page by clicking on the Database link on the left sidebar. For more information about the database definition structure see this chapter of the manual.

1.2.5.18. Project field definitions

You can reach this page by clicking on the Fields link on the left sidebar. Here you can see a list of field definitions. Each field definition instructs the runtime framework how to fetch the value of one input field and what checks to apply to the fetched value. After you create a field definition, you can use this definition to create action fields. From the project fields page you can:

1.2.5.19. Add a new field definition

From this page you can add a new field definition. Below is a detailed list of different input fields and their meaning:

  • Field name: Place here the name of the field definition.

  • Field type: Following field types are supported:

    Table 1.4. Field definition types

    TypeCorresponding HTML tag
    Area<textarea>...</textarea>
    Checkbox<input type="checkbox">
    File<input type="file">
    Hidden<input type="hidden">
    Image<input type="image">
    MultiboxAn array of <input type="checkbox"> elements
    Password<input type="password">
    Select<select>...</select>
    Text<input type="text">
    Submit<input type="submit">

  • Field source: The source from which field data is fetched. At the moment two possible sources are supported - GET and POST. Field definitions of type File do not need an explicit specification of source, since they always use the PHP array $_FILES.

  • List values: Choose a project list that will be used to populate the values of the select list or the multibox. You can manage project lists from the project lists page.

  • Initial list value: This field is used when the field type is Select. If you enter a non-empty string in this field, the runtime framework will generate a default <option> value for the created <select> HTML tag. The default option will have a value of -1 and will contain the string value that you specify as an initial list value. If you leave this field empty, then no default <option> element will be created.

1.2.5.20. Edit a field definition

From this page you can edit an existing field definition. Page fields are same as the ones on the Add a new field definition page.

1.2.5.21. Field checks

This page lists all checks which the runtime framework applies to the fetched field value. From this page you can:

1.2.5.22. Add a new field check

From this page you can add a new check that the runtime framework will apply to the fetched field value. Below is a detailed list of different input fields and their meaning:

  • Check type: Following check types are supported:

    Table 1.5. Check types

    Check typeDescription
    IntegerCheck if the field value is a valid integer and if it falls within a specified range. Each of the minimum/maximum limits is optional.
    LengthCheck if the length of the string value falls within a specified range. Each of the minimum/maximum limits is optional.
    ListCheck if the field value belongs to the field's list. This check is supported only for Select and Multibox field types, since they are the only kinds of fields that have lists attached to them.
    PCRECheck if the field value matches a Perl-Compatible Regular Expression.
    UploadCheck if the field contains a valid uploaded file. This check is supported only for File field types.

  • Error message: You can put here an error message that will be set for the corresponding field if this check fails. The message must be at least 1 character long and can contain any characters. If you leave this value empty, then a default error message will be used if the check fails.

  • Minimum value: The checked string must represent a valid integer and this integer must be equal to or greater than this value. The value can range from -PHP_INT_MAX - 1 (which equals to -2147483648 on 32-bit systems) to PHP_INT_MAX (which equals to 2147483647 on 32-bit systems). If you leave this field empty, then no minimum value restriction will be imposed.

  • Maximum value: The checked string must represent a valid integer and this integer must be equal to or less than this value. The value can range from -PHP_INT_MAX - 1 (which equals to -2147483648 on 32-bit systems) to PHP_INT_MAX (which equals to 2147483647 on 32-bit systems). If you leave this field empty, then no maximum value restriction will be imposed.

  • Minimum length: The length of the checked string must be equal to or greater than this value. The value can range from -PHP_INT_MAX - 1 (which equals to -2147483648 on 32-bit systems) to PHP_INT_MAX (which equals to 2147483647 on 32-bit systems). If you leave this field empty, then no minimum length restriction will be imposed.

  • Maximum length: The length of the checked string must be equal to or less than this value. The value can range from -PHP_INT_MAX - 1 (which equals to -2147483648 on 32-bit systems) to PHP_INT_MAX (which equals to 2147483647 on 32-bit systems). If you leave this field empty, then no maximum length restriction will be imposed.

  • Perl Regexp: The checked string must match the given Perl-Compatible regular expression, e.g. /^[A-Za-z_][A-Za-z0-9_]{0,63}$/.

1.2.5.23. Edit a field check

From this page you can edit an existing field definition. Page fields are same as the ones on the Add a new field check page.

1.2.5.24. Project include files

You can reach this page by clicking on the Includes link on the left sidebar. This page lists all PHP includes for this project. From here you can:

  • Upload a new include file, by choosing a file to upload, entering an include name and clicking on the ADD button.

  • Create a new empty include file, by leaving the upload field empty, entering an include name and clicking on the ADD button.

  • Open the include edit page by clicking on the name of the selected template.

  • Rename an existing include by clicking on the corresponding RENAME button.

  • Download an existing include file by clicking on the corresponding D/L button.

  • Delete an existing include file by clicking on the corresponding DELETE button.

1.2.5.25. Edit a project include file

From this page you can edit contents of a PHP include file. PHP include files are regular PHP files, started with the <?php tag and terminated with the ?> tag.

1.2.5.26. Project lists

You can reach this page by clicking on the Lists link on the left sidebar. From this page you manage lists of key/value pairs which can be used to define Select and Multibox fields. You can do the following operations:

  • Define a new list by clicking on the Add a new list definition link.

  • Edit an existing list by clicking on its name.

  • Manage list elements by clicking on the corresponding ELEMENTS button. This button is available only for persistent lists.

  • Delete an existing list by clicking on the corresponding DELETE button.

1.2.5.27. Add a new list definition

From this page you can add a new list definition. Below is a detailed list of different input fields and their meaning:

  • List name: Put in this field the list name

  • Persistent: Persistent lists have key/value pairs that are statically configured and fetched from the database. Non-persistent lists do not have fixed elements and before being used they must be initialized with a call to lib_list::set().

1.2.5.28. Edit a list definition

From this page you can edit an existing list definition. Page fields are same as the ones on the Add a new list definition page.

1.2.5.29. List elements

From this page you can add edit and delete list elements.

1.2.5.30. Project URLs

You can reach this page by clicking on the URLs link on the left sidebar. It lists all the project URLs that can be accessed from the client browser. The listed URLs are organized in a tree and there are clickable links for different operations that can be applied to each URL. These links are located on the right side of each URL name. Below is a description of these links:

  • add: Allows you to add a URL. The newly added action will be a descendant of the selected URL. This link is available only for directory URLs. For details on this see the add URL page.

  • text: Edit the text contents of the selected URL. This link is available only for text URLs.

  • imp: Import package files as children of the specified URL. This link is available only for directory URLs. For details on this see the import package page.

  • del: Delete the selected URL as well as all of its descendants.

  • edit: Edit properties of the selected URL. For details on this see the edit URL page.

  • d/l: Download the contents of the specified URL. This link is available only for data and text URLs.

1.2.5.31. Add a new URL

From this page you can create a new URL by adding a new URL segment to an already existing URL. Below is a detailed list of different input fields and their meaning:

  • URL name: This field contains the URL segment name.

  • URL type: Following URL types are supported:

    Table 1.6. URL types

    URL typeDescription
    DirectoryA directory that can contain other URLs segments.
    DataA generic data file. Its contents are not altered in any way.
    TextA text file that can contain tags
    Permanent redirectThis URL sends a permanent HTTP redirect (301) to the specified action or URL
    Temporary redirectThis URL sends a temporary HTTP redirect (302) to the specified action or URL
    AliasThis URL is internally replaced with the contents of a specified action or URL

  • Data file: When creating a URL of type Data, you must upload a file that contains the data.

  • Text file: When creating a URL of type Text, you can optionally upload a file that contains the text data. Any special tags in the text are processed during project compile.

  • Target type: The target type of your redirect/alias. It can be either an action or an URL.

  • Target action: The target action to which this URL is redirected/aliased.

  • Target URL: The target URL to which this URL is redirected/aliased.

As mentioned above text URLs can contain special tags which are processed during project compile. Below is a description of these tags:

Table 1.7. Text URL tags

Text URL tagTag description
{URL:path}The tag is replaced with the URL with pathname path.

1.2.5.32. Import a package

From this page you can add at the same time multiple data files to a directory URL. Such groups are called packages. Below is a detailed list of different input fields and their meaning:

  • Name: Name of a newly created URL that will contain the imported package files.

  • Package: Package that you want to import.

Below is a list of packages that come bundled with AWC:

Table 1.8. Packages bundled with AWC

Package namePackage description
jsA library of javascript functions and classes.

1.2.5.33. Edit a URL

From this page you can edit an existing URL. Page fields are same as the ones on the Add a new URL page, but there are a few differences from the URL add page:

  • If you want to do convert a directory URL with child nodes to some other URL type, you will have to delete all the children before making the change. Conversion of non-empty directory URLs is not supported.

  • When you convert a text URL to a data URL, the uploaded data file is optional. When there is no data file, the text contents of the URL are used as data for the data URL.

  • When you convert a data URL to a text URL and do not specify a text file to upload, the data from the data URL is treated as a text string for the text URL.

1.2.5.34. Wizard: Form

This wizard allows you to create quickly a form by automatically generating the form elements (actions, fields, forwards and the HTML template). You can either use default names for the inserted objects or specify these names explicitly. Below is a detailed list or the wizard input fields and their meaning:

  • Parent action This is the action under which all form objects (actions, fields, forwards and templates) will be inserted.

  • Action name (main): This is the name of the main form action. You can change the pre-filled name in case it conflicts with another action name.

  • Action name (prompt): This is the name of the action that is used to display the form initially. If the prompt action name conflicts with another action you can change the pre-filled name to something else.

  • Action name (submit): This is the name of the action that is called when the user submits the form. If the submit action name conflicts with another action you can change the pre-filled name to something else.

  • Template name: This is the name of the page template that contains the form view. If the template name conflicts with another template you can change the pre-filled name to something else.

  • Forward name (show): This is the name of the action forward that shows the page template. If the forward name conflicts with another forward you can change the pre-filled name to something else.

  • Forward name (success): This is the name of the action forward that is invoked after the form has been submitted and your custom code has finished processing. Please note that by default the success forward is of type NONE, so it just displays an empty page after form has been processed. You probably will want to change it to some other forward type (usually a template or redirect forward).

There are also three input values that are specified for each form fields. Below is a detailed list of these input values:

  • Field name: This is the input field name. It must be at least 1 character long. It can contain letters (uppercase or lowercase), digits or underscores and must start with a letter (uppercase or lowercase) or an underscore.

  • Field type: This value specifies a field definition that will be used by this field.

  • Field text: This is the text description of the input field. This text will be displayed on the form page on the left side of the input field.

1.2.5.35. Wizard: VADE (a.k.a CRUD)

This wizard allows you to create quickly a database table and a set of pages to list, add, edit and delete records from that table. Below is a detailed list or the wizard input fields and their meaning:

  • Record table: The name of the database table that will hold the inserted records.

  • Record id field: The name of the database column that will contain the record ID values. It will be created in the database as an integer field.

  • Record ID field type: The field definition that will be used by the record ID system field. In most cases you should choose a definition of an integer field type.

  • Record list query: The name of the database query that will be used to get a full list of the records in the database.

  • Parent action: This is the action under which all objects (actions, fields, forwards and templates) will be inserted.

  • Main action name: This is the name of the main action. You can change the pre-filled name in case it conflicts with another action name.

  • Main fields template: This is the name of the template file that will hold the add and edit form fields. You can change the pre-filled name in case it conflicts with another template name.

  • Enable listing of records: Check this box if you want to allow listing of records.

  • List action name: This is the name of the main action that handles record listing. If the action name conflicts with another action you can change the pre-filled name to something else.

  • List template name: This is the name of the template used by the list page. If the template name conflicts with another template you can change the pre-filled name to something else.

  • List show forward name: This is the name of the forward used to display the list page. If the forward name conflicts with another forward you can change the pre-filled name to something else.

  • List redirect forward name: This is the name of the main forward that will redirect the user to the list action.

  • Enable addition of records: Check this box if you want to allow addition of new records.

  • Add main action name: This is the name of the main record add action. If the action name conflicts with another action you can change the pre-filled name to something else.

  • Add prompt action name: This is the name of the action that is used to display the record add form initially. If the prompt action name conflicts with another action you can change the pre-filled name to something else.

  • Add submit action name: This is the name of the action that is called when the user submits the record add form. If the submit action name conflicts with another action you can change the pre-filled name to something else.

  • Add template name: This is the name of the page template that contains the view for the record add page. If the template name conflicts with another template you can change the pre-filled name to something else.

  • Add show forward name: This is the name of the action forward that shows the record add page template. If the forward name conflicts with another forward you can change the pre-filled name to something else.

  • Add success forward name: This forward is valid only when record listing is not allowed. In this case the success forward will be invoked by the submit action after a record has been added successfully. When record listing is allowed, the main list forward will be invoked instead.

  • Enable editing of records: Check this box if you want to allow editing of existing records.

  • Edit main action name: This is the name of the main record edit action. If the action name conflicts with another action you can change the pre-filled name to something else.

  • Edit prompt action name: This is the name of the action that is used to display the record edit form initially. If the submit action name conflicts with another action you can change the pre-filled name to something else.

  • Edit submit action name: This is the name of the action that is called when the user submits the record edit form. If the submit action name conflicts with another action you can change the pre-filled name to something else.

  • Edit template page name: This is the name of the page template that contains the view for the record edit page. If the template name conflicts with another template you can change the pre-filled name to something else.

  • Edit show forward name: This is the name of the action forward that shows the record edit page template. If the forward name conflicts with another forward you can change the pre-filled name to something else.

  • Enable deletion of records: Check this box if you want to allow deletion of existing records.

  • Delete action name: This is the name of the record delete action. If the action name conflicts with another action you can change the pre-filled name to something else.

There are also four input values that are specified for each form fields. Below is a detailed list of these input values:

  • Field name: This is the input field name. It must be at least 1 character long. It can contain letters (uppercase or lowercase), digits or underscores and must start with a letter (uppercase or lowercase) or an underscore.

  • Field type: This value specifies a field definition that will be used by this field.

  • Field text: This is the text description of the input field. This text will be displayed on the list page in the corresponding header column and on the add and edit pages on the left side of the input field.

  • List: If you check this box then this field will appear on the listing, add and edit pages. Otherwise if you leave the box unchecked the field will appear on the add and edit pages only.

Chapter 2. Structure of the project database definition

2.1. General description

On the one hand the database definition is used to initialize the structure of the SQL database inside the SQL server. Tables, views, sequences are created inside the database according to the database definition. On the other hand the database definition is used by the PHP runtime to handle user database requests. When handling user requests runtime code uses the database definition in order to perform error checking of parameters passed by the user. When the database definition requires some feature not supported natively by the selected SQL engine, the definition processor will either throw an error message, or will request from the runtime to emulate this feature, depending of the feature in question. Below is a detailed description of the database definition structure. Please note that order of database definition elements is not important, i.e. you can use a data type before you define it. The definition processor is clever enough to process definition elements in the correct order. The following sections describe different elements of the database definition.

2.2. Comments

Comments are delimited by /* and */ and can span multiple lines. Here is are a few sample comments:

/* This is a comment */

/*
     This is another comment
     spanning multiple lines
*/

2.3. Expressions

There are many places in the database definition where expressions are used. An expression is one of the following:

  • A string constant. String constants are enclosed in double quotes and use the backslash \ as an escape character. The following character escapes are allowed:

    Table 2.1. Character escapes

    Escape combinationMeaning
    \nLine Feed (LF) character
    \rCarriage Return (CR) character
    \tHorizontal Tab (HT) character
    \vVertical Tab (VT) character
    \fForm Feed (FF) character
    \\Backslash character
    \"Double Quote (DQ) character


    Here are some examples of string constants:

    "red"
    "gre\"en"
    "test\n123"
  • An integer constant. Integer constants. Integer constants may contain the digits 0-9. Here are some examples of integer constants:

    22
    1
    17
  • A null constant. The token null is the only token that is evaluated as a null.

  • A variable name. Variable names are identifiers prefixed by the $ character. Here are some examples of variable names:

    $var
    $even
    $precision

    Please note that at the moment the only places where variable names can be defined are function definitions where function parameter names serve implicitly as variable names.

  • A function call. Function calls have the form:

    function_name (expression_1, expression_2, ...)

    where expression_1, expression_2, ... serve as arguments. Here are some examples of function calls:

    locate ("red")
    locate (find ("green"))

    The examples assume that locate() and find() are functions and that locate() returns a string expression.

  • An operator expression. For the moment the only supported operator is the dot which serves as a string concatenation operator. Here are some examples of string concatenation:

    "red" . "green"
    "blue" . locate ("yellow")

2.4. Database types

Many of the definition constructs require the specification of a database type. Since not all SQL servers have a complete support for SQL domains that could be used to implement data types, the database definitions have internal support for user-specified data types which are later expanded to user-specified strings. Type definitions have the following format:

type type_name = string_expression;

Here is a sample type definition:

type dbstring = "varchar(30)";

This type definition will not generate immediately SQL code. Instead the compiler will remember it and when this type is used in some declaration, the compiler will expand the dbstring type to varchar(30).

2.5. Database sequences

If the database engine has native support for sequences, then a sequence definition expands to the native SQL command CREATE SEQUENCE. Otherwise the framework runtime emulates sequences via values stored in a system table. The exact format of a sequence definition is:

sequence sequence_name = integer_expression;

Here is a sample sequence definition:

sequence admin_id = 15;

It will create a sequence named admin_id and assign 15 to it as an initial value.

2.6. Database tables

Table definitions have the following general format:

volatile table table_name {
        primary|index field_type* field_name [links];
        ...
} = initializer;
  • The optional volatile modifier means that reference counting applies to rows in this table. Each incoming link pointing to a given row increases its reference count by 1. If the reference count for a given row goes to 0, then the framework runtime deletes that row.

    Warning

    The volatile modifier is currently recognized by the definition parser but the PHP runtime ignores the volatile flag, i.e. rows with refcount 0 currently are not deleted.

  • The primary or index keyword is optional and instructs the database engine to optimize access to this field by marking it as a primary index or just as a regular index. A table must have exactly one primary index.

  • The field_type field is the name of a database type defined by the user. The field type may be followed by an optional asterisk (*). When the asterisk is present the field is defined as nullable, otherwise the field is not nullable and NOT NULL is added to the field SQL definition.

  • This field_name field contains the name of the table field.

  • The optional [links] field defines a list of field links. This list is comma separated and each item in this list is of the form direction : another_table_name. Direction is either incoming or outgoing, and another_table_name is the name of some database table. Specifying a link in such a fashion means that there is a link between the rows in current table and rows in another_table such that (current_table.field_name == another_table.primary), where current_table.field_name denotes the table field that contains the link construct and another_table.primary denotes the primary field of table another_table. If direction is specified as incoming, then the link is incoming for the table containing the link construct and outgoing for table another_table, otherwise if direction is specified as outgoing, then the link is incoming for table another_table and outgoing for the table containing the link construct. The reference count of each table row is the number of incoming links pointing to that row. Here is an example of tables, using incoming/outgoing links:

    table workers {
             primary    int       worker_id;
                        string*   first_name;
                        string*   last_name;
    };
    
    volatile table tools {
             primary    int       tool_id;
                        int       worker_id   [incoming : workers];
                        string    type;
    };

    For each tool there is a worker that is the owner of that tool. The tools table is volatile, meaning that a tool is deleted as soon as the corresponding worker (its owner) is deleted.

    Warning

    The links construct is currently recognized by the parser but the PHP runtime ignores the field links, i.e. rows with recount 0 currently are not deleted.

  • The optional = initializer construct specifies an inline array initializer, or points to an external file containing the initializer values. Each row of the initializer is inserted verbatim into the database table. When a C-like array initializer is used the table definition looks like:

    table table_name {
            ...
    } = {
            {expression, expression, ...},
            {expression, expression, ...},
            ...
    };

    The expression must evaluate either to a string value or to a null value. In the case expression evaluates to null, the field must be nullable or an error will occur. Here is an actual example of using an inline table initializer:

    table my_table {
            primary    int           user_id;
            index      dbstring      name;
                       dbstring*     address;
    } = {
            {"1", "John" . " Smith", null},
            {"2", "Tom Browne", "Driver " . "street 25A"}
    };

    If an external initializer was used the definition would look like:

    table my_table {
            primary    int           user_id;
            index      dbstring      name;
                       dbstring*     address;
    } = "external_file.txt";

    The external file can contain string constants or null constants (no expressions are allowed in external initializer files). String constants are comma separated, enclosed in double quotes and the usual character escaping rules apply just as with usual string literals. As usual the null token is used to represent null constants. Just as with inline initializers if an attempts is made to initialize a non-nullable field with a null value, an error occurs. Here are contents of an external initializer file that would initialize the my_table table with the same contents as the inline initializer from the example above.

    "1", "John Smith", null
    "2", "Tom Browne", "Driver street 25A"

    Warning

    Do not use external initializers with the Advanced Website Creator. They are intended to be used when the database parser is run as a standalone application.

2.7. Database views

View definitions expand to the "CREATE VIEW" command. View definitions have the following format:

view view_name = string_expression;

Here is a sample view definition:

view my_view = "SELECT * FROM users";

2.8. Database PL/SQL functions

PL/SQL function definitions have the following format:

plsql return_type plsql_name (type_1 arg_1, type_2 arg_2, ...)
(
        type_1 local_1;
        type_2 local_2;
        ...
) = string_expression;
  • return_type denotes the return type of the PL/SQL function. If the return type is surrounded by square brackets, then the function is defined to return a set of that type, e.g. if string is defined as varchar, then [string] is translated to SETOF varchar.

  • plsql_name denotes the name of the defined function.

  • type_N denotes the type of the Nth function argument or local variable.

  • arg_N denotes the name of the Nth function argument.

  • local_N denotes the name of the Nth local variable.

  • string_expression is a string expression evaluating to the contents of the function body (between the "BEGIN" and "END" keywords").

2.9. Database named queries

Named query definitions have the following format:

query query_name = string_expression;

The string expression must evaluate to a string that is an SQL query. The query is not translated to an SQL object, but is handled internally by the PHP runtime code. When calling lib_db::query_named() you can pass additional parameters which are recognized by the runtime and inserted into the named query. You can specify where to insert these arguments by embedding the following special strings into the named query:

  • {ESC:number} is replaced by the SQL escaped value of the argument with index number (arguments are indexed starting from zero).

  • {RAW:number} is replaced by the value of the argument with index number (arguments are indexed starting from zero). The argument value is inserted verbatim without any escaping or any other modification.

After the result rows are received from the SQL server, the values in these rows are converted to PHP data types. In order for the PHP runtime to perform this conversion correctly you have to specify the data types of the resulting fields. You can do that by embedding the following special string into the named query:

  • {FIELD:type} tells the PHP runtime that there is a result field of type type. The type value must be an SQL type defined via the type keyword.

When the PHP runtime builds a named query, the {FIELD:...} strings are removed from the resulting SQL statement. However the field hints are used when the SQL result data is converted back to PHP data types. The exact location of {FIELD:...} tags is unimportant, but for each result field of the query there must be exactly one {FIELD:...} tag and the tags must be in the same order as the result fields. For an detailed description of data conversion rules take a look at these tables. Below is a sample named query:

type int = "int4";
type name = "varchar(64)";

table users {
        int     user_id;
        int     location;
        name    first_name;
        name    last_name;
};

query user_list = "
        SELECT
                user_id {FIELD:int},
                first_name {FIELD:name},
                last_name {FIELD:name}
        FROM users
        WHERE location='{ESC:0}'
";

2.10. Database definition functions

The database definition parser supports function definitions. Such a function definition does not immediately generate SQL code. Instead you can call such functions from inside expressions. This means that such functions are particularly useful when you need to define several named queries which have lots of similar parts. In this case you can move the similar code to user-defined functions and then use these user defined functions to implement the bodies of your named queries, thus greatly reducing the duplicated SQL code you need to write.

2.10.1. User-defined functions

When writing database definitions you can define your own functions. Such function definitions have the following format:

function function_name ($arg_1, $arg_2, ...) = expression;
  • function_name is the name of your function.

  • $arg_1, $arg_2, ... are the format argument names. These arguments are accessible from within expression.

  • expression is the expression forming the function body. When the function is called the formal arguments are replaced by the parameter values, expression is evaluated and its value is used as function return value.

Here is an example of a user-function definition:

function join_strings ($first, $second) = $first . $second;

If you call the function in the following way: join_strings ("Single", "Word"), then the function invocation code will evaluate to the "SingleWord" string.

2.10.2. Built-in function definitions

The database definition parser supports several builtin functions. They are mainly used implicitly to implement other language constructs like table, view, plsql, etc. However these functions can also be called explicitly although this is not recommended under normal circumstances. However in some cases it is necessary to call explicitly one or more of these functions, e.g. when you need to define a table with a name matching a reserved keyword. Here is a list of these built-in functions:

Table 2.2. Built-in functions

Function prototypeFunction description
array array (mixed ...)Builds an array out of its parameters.
void dump_plsql (string name, array returns, array args, array locals, string body)Dumps a PL/SQL function.
void dump_query (string name, string body)Dumps a named query.
void dump_sequence (string name, integer initial)Dumps a sequence.
void dump_table (string name, integer volatile, array fields, array init)Dumps a table.
string prefix_pathname (string prefix, string pathname)If pathname is not absolute adds the specified prefix (which must be an absolute dirname) to it and return the resulting value, otherwise (pathname is absolute), return the pathname itself.
array read_table_initializer (string pathname)Reads a table initializer file into an array.
void dump_type (string name, string definition)Adds a new SQL type with specified name and replacement text.
void dump_view (string name, string definition)Dumps a view.


FIXME: Must describe the built-in functions in more detail.

2.11. Including other definition files

You can include additional definition files into the currently processed definition file. Each include statement has the form :

include string_literal;

Where string_literal is a literal containing the pathname (either absolute or relative) of the included definition file. When the definition parser meets an include statement, it processes the included file as if it has been inserted in the including file instead of the include keyword. After the included file has been processed, the parser continues processing the including definition file, right after the include keyword.

Warning

Do not include external database definition files when using the Advanced Website Creator. The include keyword is intended to be used when the database parser is run as a standalone application.

Chapter 3. PHP Library classes

3.1. lib_db - Database library class

This library class contains static methods used to access the database through the selected SQL engine.

  • Some of the database functions accept as a parameter of return table rows in the form of PHP arrays. Such arrays use field names as array keys and field values as their corresponding array values. When you create such an array as a parameter you not have to specify values for all fields, some fields may be omitted. It is up to the database function if it will accept a table row with some missing fields.

  • Some database functions require a filter which specifies the table rows affected by the function. Such a filter is a PHP array with array keys containing field names and array values containing field values. The filter requires that all field values are equal to the corresponding values specified in the filter. E.g. the filter array ("username" => "john", "password" => "12345") will be translated to the SQL clause WHERE username='john' AND password='12345'.

  • The framework runtime takes care of escaping the SQL names and values which you pass to different functions as parameters, inside row arrays or inside filters. This means that you should not escape names and values before passing them to database functions. The only exceptions are query_raw() function which sends the query verbatim to the database engine and query_named() when you use the %{RAW:number} expansion. In these two cases you must take care to manually escape the possibility of SQL injection into your SQL queries.

  • If the project database engine supports transactions, then the database library will automatically wrap processing of action handlers inside transactions. A transaction is started during action processing when the first SQL query is sent. Upon completion of action processing the transaction is committed automatically. If an error occurs during action processing, then the transaction is automatically rolled back.

Table 3.1. Database library methods

Method prototypeMethod description
array get_capabilities (void)Returns a capabilities array with description of database engine features.
int next_id (string sequence)Returns the current value for the specified sequence and increases the sequence by 1. When issuing the database call, the sequence parameter is escaped in order to avoid SQL injection attacks. No other database conversions are performed.
string escape (string string)Escapes a string for insertion into the database. Use it to avoid SQL injection attacks.
array query_raw (string query)Sends a raw SQL query. The query argument is passed verbatim to the SQL engine. Returns an array of resulting rows. The rows are indexed starting from 0. No database conversions are performed.
array query_named (string name, ...)Sends a named SQL query. A query with that must be present in the database definition. The name argument can be followed by additional arguments which are inserted into the query (see database definition, database queries for more info). Returns an array of resulting rows. Row indexes start from 0. Function parameters are embedded into the query string and optionally escaped based on the {ESC:...} and {RAW:...} tags inside the query string. Resulting rows are converted to PHP values based on the {FIELD:...} tags in the query string.
int affected_rows (void)Returns the number of affected rows by the previous SQL query.
void create (string table, array row)Inserts a new row in the specified table. The row argument is an array where element keys are treated as field names and element values are treated as field values. Row values are converted from PHP to SQL data types based on the table field types.
void destroy (string table, string primary)Looks for a table row with a matching value of primary key. If such a row is present, removes it from the table. When looking for a matching row to destroy the primary field value is converted from a PHP to an SQL data type, based on the primary field type.
void destroy_by_filter (string table, array filter)Looks for all table rows matching the specified filter, then removes all found rows from the table. When looking for matching rows to destroy the filter values are converted from PHP to SQL data types, based on the field types of the filter.
array read (string table, string primary)Looks for a table row with a matching primary key value. If such a row is present returns an array where field names serve as array keys and field values serve as array values. If such a row does not exist the function returns null. When looking for a matching row to read the primary field value is converted from a PHP to an SQL data type, based on the primary field type.
array read_by_filter (string table, array filter)Looks for a table row that matches the specified filter. If such a row is present returns an array where field names serve as array keys and field values serve as array values. If such a row does not exist returns null. If there are multiple rows matching the filter, a fatal error occurs. When looking for a matching row to read the filter values are converted from PHP to SQL data types, based on the field types of the filter.
void write (string table, array row, string primary)Looks for a table row with a matching primary key value. If such a row is present, updates it by using array keys as field names and array values as field values. When looking for a matching row to update, the primary field value is converted from a PHP to an SQL data type, based on the primary field type.
void write_by_filter (string table, array row, array filter)Looks for all table rows matching the specified filter. Updates them by using array keys as field names and array values as field values. Update of multiple rows is allowed. When looking for matching rows to update, the filter values are converted from PHP to SQL data types, based on the field types of the filter.
int savepoint_create (void)Creates a new savepoint. If there is no active transaction, it tries to start one. If the database engine does not support transactions or savepoints a fatal error occurs. Returns an integer index value that can be used later to rollback or erase the created savepoint.
void savepoint_rollback (int index)Given the savepoint index tries to rollback the specified savepoint. If the specified savepoint does not exist a fatal error occurs.
void savepoint_release (int index)Given the savepoint index tries to erase the specified savepoint. If the specified savepoint does not exist a fatal error occurs.

The get_capabilities() function returns an info array that contains information about the capabilities of the database engine. Below is a description of the capabilities array elements:

Table 3.2. Capabilities info array

ElementDescription
oidsA boolean indicating if the database has OIDS support.
plsqlA boolean indicating if the database has PL/pgSQL support.
schemasA boolean indicating if the database has support for schemas.
sequencesA boolean indicating if the database has support for sequences.
transactionsAn integer value indicating the level of transactions support. It can take one of the sql transaction constants.
for_shareA string containing the clause that must be applied to the SQL SELECT statement in order to place a read-only lock on the selected rows. E.g. for PostgreSQL it is FOR SHARE. If SELECT does not support read-only row locks, then the value is null.
for_updateA string containing the clause that must be applied to the SQL SELECT statement in order to place a read-write lock on the selected rows. E.g. for PostgreSQL it is FOR UPDATE. If SELECT does not support read-write row locks, then the value is null.

There are several integer SQL transaction constants that are used to indicate inside the capabilities info array the level of transaction support:

Table 3.3. SQL transaction constants

Constant symbolic valueConstant integer valueValue meaning
sql_transaction::NONE0The database engine does not support transactions
sql_transaction::BASIC1The database engine supports transactions, but does not support savepoints.
sql_transaction::SAVEPOINTS2The database engine supports transactions with savepoints.

Table 3.4. Data conversion applied when reading from and writing to a MySQL database

Database field typeMySQL data valuePHP data value
Any typeNULL (regardless of the actual column type)null
BOOL, BOOLEAN'1', '0'true, false
Any other type'text string' 1"text string"

  1. The text string is escaped via mysql_real_escape_string() when creating the MySQL string. The database value is not unescaped explicitly when creating the PHP string, since the MySQL database performs the unescaping implicitly when reading from the database.

Table 3.5. Data conversion applied when reading from and writing to a PostgreSQL database

Database field typePostgreSQL data valuePHP data value
Any typeNULL (regardless of the actual column type)null
BOOL, BOOLEAN't', 'f', '1', '0' 1true, false
BYTEA'binary string' 2"binary string"
Any other type'text string' 3"text string"

  1. When converting from a PHP boolean to a PostgreSQL BOOL or BOOLEAN type, the resulting boolean constant is always 't' or 'f'.

  2. The binary string is escaped via pg_escape_bytea() when creating the PostgreSQL string and then unescaped via pg_unescape_bytea() when creating the PHP string.

  3. The text string is escaped via pg_escape_string() when creating the PostgreSQL string. The database value is not unescaped explicitly when creating the PHP string, since the PostgreSQL database performs the unescaping implicitly when reading from the database.

3.2. lib_event - Event library class

The event library class contains static methods used to send messages to the site logfile and to the browser window.

  • The integer constants lib_event::L_DEBUG, lib_event::L_INFO and lib_event::L_ERROR can be used to specify message priority level.

  • Some functions accept a format string followed by a variable number of arguments. The format string together with the following variable arguments are used to build the message. For details on the conversion see the PHP documentation on the sprintf() function.

  • When a message is logged, all messages characters after the first 4096 characters are ignored.

  • If the project is built with debugging enabled all log messages are written to logs/debug.log. Otherwise (debugging is disabled) no messages are written to the logfile. In both cases fatal messages are displayed on the screen, just before the program is terminated.

Table 3.6. Event library methods

Method prototypeMethod description
void log (int level, string format, ...)Sends a new message to the event library.
void fatal (string format, ...)Sends a new message to the event library with L_ERROR priority, then displays this message in the browser window and terminates the current script. Please note that although only the first 4096 characters are sent to the logging framework, the unabridged version of the message is displayed in the browser window.

3.3. lib_file - File library class

The file library class contains static methods used to perform different filesystem operations not supported natively by PHP.

Table 3.7. File library methods

Method prototypeMethod description
array path_split (string $path)Returns an info array that contains the path description. Both the / (slash) and \ (backslash) characters are recognized as segment separators.
string path_join (array $info, string $separator)Builds a pathname string from an info array and segment separator character.
bool path_is_absolute (string path)Returns true if the given path is absolute. Otherwise returns false. The check for absolute pathname is performed as follows:
  • If the OS is Windows and the path starts with a drive letter and semicolon, these two characters are removed from the path.

  • If the resulting path starts with slash or backslash the path is absolute otherwise it is not absolute.

string path_dirname (string path)Returns the directory component for the specified path. If the specified pathname does not have a directory component, this function will return false.

Notes:

  • The directory component for a given pathname is not always the parent directory, e.g. the directory component of "/home/user1/../" is "/home/user1".

  • This function differs from the POSIX-compliant dirname functions, because when there is no dirname component it returns false, while POSIX compliant functions return "/" or ".".

string path_normalize (string path)Returns the normalized form of the given path. Normalization is performed by:
  • Conversion of all slashes and backslashes to the directory separator native to the currently active OS.

  • Conversion of multiple consecutive directory separators to a single directory separator.

  • Resolving the . and .. directory elements. For absolute pathnames if there is a .. which cannot be resolved, i.e. there is a .. element for which its parent is not stored in the path, an error occurs. For relative pathnames an unsuccessful resolving of a .. element is not considered an error.

  • Removal of trailing slashes.

Returns the normalized path on success, or false on error.

string path_unixize (string path)Unixizes the specified path. The following changes are performed:
  • Conversion of all backslashes to forward slashes.

  • Conversion of multiple consecutive slashes to a single slash.

  • Removal of trailing slashes.

Returns the unixized path.

string path_relative (string source, string dest)Calculates the relative path under which the pathname dest is reachable from within the source directory. Returns the relative path on success or false on error.
bool tree_copy (string source, string dest, array params)Copies recursively the pathname source to destination dest. params is an array holding the file copying flags. It contains the following elements:
  • keep_ownership is a boolean specifying whether to keep file ownership.

  • keep_permissions is a boolean specifying whether to keep file permissions.

Returns true on success or false on error.

bool tree_delete (string pathname)Deletes the directory tree pathname recursively. Returns true on success or false on error.
bool tree_move (string source, string dest)Moves the pathname source to destination dest. Moving between different filesystem partitions is supported. Returns true on success or false on error.
array tree_walk (string pathname, array params)Walks the directory tree pathname recursively and gathers information on files matching specified criteria. params is an array holding the file matching criteria. It contains the following elements:
  • dir_follow is boolean flag specifying whether to follow symlinks.

  • dir_mark is a boolean specifying whether to add trailing directory separator to each directory.

  • path_partial is a boolean indicating whether to store partial pathnames instead of full pathnames. Partial pathnames do not have the pathname prefix (which is the starting point of the tree walk).

  • path_detailed is a boolean indicating whether to add detailed info arrays to the list instead of string pathnames.

  • depth_min is an integer specifying the minimum directory depth of pathnames added to the resulting list. A null value means that there is no minimum directory depth.

  • depth_max is an integer specifying the maximum directory depth of pathnames added to the resulting list. A null value means that there is no maximum directory depth.

On success this method returns an array of matching pathnames. The array has numeric indexes starting from zero. Each element in this array is an array with the following elements:

  • pathname When the path_detailed parameter is false, pathname is a string containing the pathname of the file, otherwise (path_detailed is true), pathname is an array with the following elements:

    • drive If the script is running on a Windows platform and the file pathname has a drive letter, drive contains the drive letter. Otherwise (non-Windows platform or the pathname does not contain a drive letter), drive contains null.

    • absolute is a boolean indicating if the file has absolute pathname.

    • parts Different parts of the pathname are separated by directory separators. parts contains these pieces of the pathname.

  • is_dir is a boolean indicating if it is a directory.

  • is_executable is a boolean indicating if it is an executable file . A file is considered executable if the filesystem permissions allow execution of that file.

  • is_file is a boolean flag indicating if it is a regular file.

  • is_link is a boolean indicating if the file is a symlink.

  • is_readable is a boolean indicating if the filesystem permissions allow reading from the file.

  • is_writable is a boolean indicating if the filesystem permissions allow writing to the file.

  • uid is the UID of the file owner.

  • gid is the GID of the main file group.

  • permissions is an integer containing file permission flags (file "mode").

On failure this function returns false.

string create_temp_file (string dir)Creates a temporary file inside the specified directory. On success returns the pathname of the created file or false on failure.
string create_temp_dir (string dir)Creates a temporary directory inside the specified directory. On success returns the pathname of the created file or false on failure.

The pathname split and join functions use an info array that contains pathname information. Below is a description of the info array elements:

Table 3.8. Pathname info array

ElementDescription
driveContains the drive letter. This element contains a non-null value only when the framework runs on Windows and the split pathname has a drive letter. In all other cases the value of this property is null.
absoluteA boolean element showing if the split pathname is absolute.
partsAn array with zero-based numeric indexes. Its elements are the pathname segments.

3.4. lib_json - JSON library class

This class contains static methods used to convert a PHP array into a string which can be used to initialize a JavaScript variable.

Table 3.9. JavaScript library methods

Method prototypeMethod description
string build (mixed value)Auto detects the item type and returns a string suitable for a JavaScript variable initialization.

3.5. lib_list - Lists library class

This class contains static methods used to manage generic lists of key/value pairs.

  • Methods in this library take as parameters or return as a result value, data structures called lists. Such lists are PHP arrays, where list keys are represented by array keys and list values are represented by the array values. Elements in lists have a sort order. Such sort order is represented in PHP arrays using the built-in ordering of elements in PHP arrays.

  • At the beginning of the HTTP request list values are kept in the database. Each time a list is fetched from the database, it is cached in memory. Contents of this memory cache can be modified by the library methods, however such modifications are transient and are lost once the HTTP request terminates.

Table 3.10. List library methods

Method prototypeMethod description
array get (string name)Returns a list called name. An attempt to fetch a non-existent list is considered a fatal error.
void set (string name, array list)Adds a list called name with data in list to the in-memory list cache. Lists added via this function can be fetched by the get method if they were added during the current HTTP request. After the current HTTP request terminates, cache contents are purged.

3.6. lib_mail - Multipart email library class

This class contains static methods used to create and send multipart emails. The created emails have two parts - one with a MIME type text/plain and another with a MIME type text/html. Such emails can be read HTML email clients which can take advantage of the HTML markup elements like hypertext links. The non-HTML enabled clients will read the text part of the email.

Table 3.11. Email library methods

Method prototypeMethod description
void clear (void)Start building a new email message. All previously added email parts are removed.
void add_text (string text)Add plaintext to the message. The text is treated literally in both the text and the html email parts. This means that for example adding the string <br> will not add a line break in the HTML part.
void add_new_line (void)Add a newline. The text counterpart treats this as a LF character and the HTML counterpart treats this as the HTML tag <br>.
void add_link (string url, string text)Add a hypertext link. The text part inserts the url parameter as a text string. The HTML part inserts a <a href="url">text</a> hypertext link.
void send (string from, string to, string subject)Sends an HTML message. The From, To and Subject headers are taken from the corresponding function parameters and the body of the message is built from the previously added message pieces. The from parameter as passed as an extra email header to the mail() function. This means that depending on the configuration of your PHP installation, it is possible that the from parameter will take no effect.

3.7. lib_misc - Miscellaneous library class

This class contains static methods used to perform tasks which could not be attributed to any other library, so they were gathered in this miscellaneous library.

Table 3.12. Miscellaneous library methods

Method prototypeMethod description
bool is_windows (void)Returns a boolean indicating if the script is running on a Windows OS.
string escape_php_string (string string)Returns string after performing character escaping. The resulting string is suitable for inclusion into PHP source as a PHP string. The escaping is performed with the assumption that the PHP string is double quoted, i.e. the escaped character set includes double quotes.
string escape_pcre_string (string string)Returns string after performing character escaping. The resulting string is suitable for inclusion into a Perl-Compatible regular expression as a literal match.
string generate_hash (string length)Returns a hash string, which is length characters long. The character set of the hash string consists of the 0-9 and A-Z character sets.
bool is_valid_eregi (string expr)Returns a boolean indicating if the expr parameter is a valid case-insensitive regular expression.

3.8. lib_nested_set - Tree library class

The nested set model is a way of representing tree structures inside SQL tables. This model is much more efficient than the adjacent list model which is often used to represent trees in SQL. For a description of the nested set model you can read Breaking the Relational Taboo.

Table 3.13. Nested set library functions

Method prototypeMethod description
void create (array tree, array data)Given the tree description in tree and the data row in data, this function will insert a new node into the tree. Type of inserted node (root or child) depends on the parent id in data. If the parent is null, then a root node is inserted, otherwise (a non-null parent) a child of the specified parent is inserted. The left node and right node fields can be omitted or they can have arbitrary values since the create() function calculates and writes the node values into the database on its own.
bool move_left (array tree, string item_id)Given the tree description in tree and the item id in item_id, this function will try to exchange the specified node with its left sibling. This function can fail only if the node is already the leftmost sibling. On success this function returns true, and on failure false.
bool move_right (array tree, string item_id)Given the tree description in tree and the item id in item_id, this function will try to exchange the specified node with its right sibling. This function can fail only if the node is already the rightmost sibling. On success this function returns true, and on failure false.

Notes:

  • Tables which contain nested sets must have at least four system fields: node id, parent id, node left value, node right value. No specific names are forced on these fields since nested set functions receive names of these fields in the tree parameter. The node id values are not required to be unique within the whole table, but they have to be unique within the respective tree.

  • All nested set methods receive tree description as a parameter. This description is an array containing following elements:

    • table: Name of an SQL table holding the tree structure.

    • filter: An array where array keys hold SQL field names and the array values hold the corresponding SQL field values. Only rows with matching values are considered part of the tree. This means that a single SQL table can hold several trees as long as their filters specify non-intersecting sets of rows. Structure of these filters is identical to the structure of filters used by lib_db. If you do not want to apply any filter, i.e. the table will hold only a single tree, then pass an empty array as a filter.

    • field_id: Name of the node id field. Usually this is the field serving as table primary key.

    • field_parent: Name of the parent id field.

    • field_left: Name of field containing left node value. This field must be of an integer type.

    • field_right: Name of field containing right node value. This field must be of an integer type.

  • The create() function receives a data row as a parameter. This data row is an array where array keys hold SQL field names and the array values hold the corresponding SQL field values. Structure of this data row is identical to the data rows used by lib_db.

3.9. lib_sorted_list - Sorted list library class

The sorted list class contains functions that are used to add ordering to table rows.

Table 3.14. Sorted list library functions

Method prototypeMethod description
void create (array list, array data)Given the list description in list and the data row in data, this function will insert a new item into the list. The sort key field can be omitted or it can have an arbitrary value since the create() function calculates and writes the sort key value into the database on its own.
bool move_forward (array list, string item_id)Given the list description in list and the item id in item_id, this function will try to exchange the specified item with the preceding one in the list. This function can fail only if the item is already the first one in the list. On success this function returns true, and on failure false.
bool move_backward (array list, string item_id)Given the list description in list and the item id in item_id, this function will try to exchange the specified item with the next one in the list. This function can fail only if the item is already the last one in the list. On success this function returns true, and on failure false.

Notes:

  • Tables which contain sorted lists must have at least two system fields: item id and sort key. No specific names are forced on these fields since sorted list functions receive names of these fields in the list parameter. The item id values are not required to be unique within the whole table, but they have to be unique within the respective list.

  • All sorted list methods receive list description as a parameter. This description is an array containing following elements:

    • table: Name of an SQL table holding the list structure.

    • filter: An array where array keys hold SQL field names and the array values hold the corresponding SQL field values. Only rows with matching values are considered part of the list. This means that a single SQL table can hold several lists as long as their filters specify non-intersecting sets of rows. Structure of these filters is identical to the structure of filters used by lib_db. If you do not want to apply any filter, i.e. the table will hold only a single list, then pass an empty array as a filter.

    • field_id: Name of the item id field. Usually this is the field serving as table primary key.

    • field_sort: Name of field containing the item sort key.

  • The create() function receives a data row as a parameter. This data row is an array where array keys hold SQL field names and the array values hold the corresponding SQL field values. Structure of this data row is identical to the data rows used by lib_db.

3.10. lib_shutdown_callbacks - A library for registering/unregistering shutdown callbacks

This library contains functions that allow you to register/unregister callbacks that are called upon program shutdown, after the HTTP request has been processed.

Table 3.15. Shutdown library functions

Method prototypeMethod description
int add (callback callback)Adds the specified callback to the list of shutdown callbacks that will be called immediately before program termination. The function returns a cookie that can be used in a call to remove() in order to remove the callback from the list of shutdown callbacks.
void remove (int cookie)Given a cookie for a registered shutdown callback, removes the specified callback from the list of shutdown callbacks.

Chapter 4. Miscellaneous

4.1. Implementation details of the Model-View-Controller (MVC) runtime framework

The typical processing of an HTTP request by our runtime framework looks like:

  1. The browser sends an HTTP request for some URL that is handled by our website.

  2. The HTTP is initially handled by the webserver. If the webserver has support for Apache-compatible URL rewriting (mod_rewrite) and our website is using search engine friendly URLs like /some_friendly_url.html, then this is the step when the pretty-looking URL is being translated into a real URL recognizable by our runtime framework. The real URL will look like: /index.php?action=37. The correspondence between search-engine friendly URLs and real action URLs is configured inside the URLs menu in Advanced Website Creator.

  3. The PHP code in index.php initializes the runtime framework, then calls the generic action processing code inside our runtime framework.

  4. The generic action processing code gets the action ID from the HTTP GET parameter action and then uses the found action ID in order to build the $fields array that will be passed later to our action handler. In order to populate the fields array the action processing code uses the fields that we have defined for that action on the Actions page for our website project. Some of the $fields elements are fetched from the HTTP GET/POST/FILES parameters, while others are initialized to their empty values - this again is configured from the Actions page. For fields that are populated from the HTTP GET/POST/FILES data, the field values are being checked against the user-defined checks. These user-defined checks can be specified on the Fields page for our website project. For fields that fail some check an error message is saved inside the $fields array. The error message can be defined by the user. If there is no user-defined error message, a default one is used.

  5. If we have configured the action to participate in a session, then generic action processing code uses HTTP cookies in order to get the session ID and then read the saved session variables for that session from the database backend. The read session variables are used to populate the $session array.

  6. The $fields and $session arrays (which represent the Model in MVC terms) are passed to our used-defined action handler.

  7. The user-defined action handler (which is the Controller in MVC terms) has to instruct the runtime framework what to do after the action has been processed. When handling HTML forms the action handler typically should do the following:

    • If the action should only be called within a valid session, the action handler checks if there is a valid session. If there is no valid session the processing is stopped and the handler usually returns a forward which redirects the user browser to a login page.

    • The optionally handler runs extra checks against the values in $fields ["field_name"]["value"]. If there are errors for some fields, the handler can save them as text messages in the corresponding $fields ["field_name"]["error"] fields.

    • The handler calls field_manager::is_ok() to check if there is an error for some field. This error can be either caused by a failed builtin check or by our extra checks in the previous step. If there is an error for some field, then the action handler usually returns a forward that instructs the framework to re-display the page template. The errors for fields "field_name" will be displayed on the page in place of embedded {ERROR:field_name} tags.

    • If there are no errors for any fields, then the user-defined action handler performs the actual action for which it has been invoked, e.g. sends an email (if this is the submit action for a contact form) or creates a new database record (if this is the submit action for a page that adds new website users).

    • After all processing is over, the action handler returns a forward that instructs the runtime framework to send a redirect to some other action, e.g. one that display the current users for our website.

  8. On return our action handler passes the action forward name to the generic action processing code inside the runtime framework. The runtime framework executes the specified action forward, which can do various things, e.g. display a specified template, redirect the browser to some URL, etc.

Below is a table describing mapping between MVC components and their counterparts in Advanced Website Creator:

Table 4.1. Mapping between MVC components and their counterparts in AWC

MVC componentAWC component
Model$fields and $session arrays automatically populated by the AWC runtime framework and then passed to the corresponding action handler (the controller).
ViewThe displayed HTML code is defined by the chosen action forward and by the HTML template displayed by that forward.
ControllerThe action handlers for the defined actions.