# ATutor Developer Documentation

## Table of Contents

- 0. Version Considerations
- 1. Introduction
  - 1.1 API Documentation
- 2. Conventions Used in This Document
  - 2.1 Typographic Conventions
  - 2.2 Links
  - 2.3 Function Definitions (Prototypes)
- 3. Setup
  - 3.1 PHP Configuration
- 4. GitHub Repository
  - 4.1 Setting up a Git Development Environment
  - 4.2 Creating anfd Maintaining a Git Fork
  - 4.3 Installing from GitHub
- 5. Communication
- 6. Patches
- 7. Editor Tips
- 8. Proposed Features
- 9. Bug Tracking
- 10. Creating Bundles
- 11. Writing Portable Code
- 12. Coding Style
  - 12.1 Indentation
  - 12.2 Line Length
  - 12.3 Using Whitespace
  - 12.4 SQL Guidelines
  - 12.5 SQL/99 Joins
  - 12.6 Database Queries with queryDB() Function
  - 12.7 Control Flow Constructs
  - 12.8 Commenting
  - 12.9Naming Conventions
    - 12.9.1 Naming Variables
    - 12.9.2 Naming Functions
    - 12.9.3 Naming Files
- 13. Directory Structure
  - 13.1 Directories
  - 13.2 Files
- 14. Database Structure
- 15. Localisation
  - 15.1 Adding & Editing Language
- 16. Error and Feedback Messages
  - 16.1 Internals
  - 16.2 Adding Messages
  - 16.3 Printing Messages
  - 16.4 UTF-8 and Multibyte language
- 17. Useful Variables
  - 17.1 $db
  - 17.2 $addslashes
  - 17.3 $_base_href
  - 17.4 $_base_path
  - 17.5 $_user_location
  - 17.6 $_rel_url
  - 17.7 $_my_uri
  - 17.8 $contentManager
  - 17.9 $_section
- 18. Useful Functions
  - 18.1 authenticate()
  - 18.2 _AT()
  - 18.3 AT_print()
  - 18.4 AT_date()
  - 18.5 $addslashes()
  - 18.6 debug()
  - 18.7 get_login()
  - 18.8 urlencode_feedback()
  - 18.9 url_rewrite()
- 19. Useful Constants
  - 19.1 AT_INCLUDE_PATH
  - 19.2 SEP
  - 19.3 AT_DEVEL
  - 19.4 TABLE_PREFIX
  - 19.5 VERSION
- 20. Install & Upgrade Scripts
  - 20.1 Install Script
  - 20.2 Upgrade Script
- 21. Accessibility
- 22. Validation
- 23. Sample Script
- 24. Credits & Additional Sources

top

## 0. Version Considerations

This document is found in ATutor's `documentation/` directory and is maintained along with the rest of the code in the code repository. The latest version of this document will always be available in the repository. Versions bundled with ATutor releases are specific to that release. If you are modifying a previous version of ATutor then you should refer to the version of these guidlines as they are available with that specific version.

top

## 1. Introduction

ATutor, as an open source project, encourages PHP developers to develop their own custom features, and potentially contribute those features so they become a permanent part of ATutor. To ensure that code is easy to maintain, we urge developers to follow the guidelines outlined below. These rules and recommendations were created to standardize the distributed development process.

The latest version of this document can always be found at ATutor.ca.

### 1.1 API Documentation

Detailed API documentation is distributed throughout the ATutor source code, describing functions and classes, and how they are used in developing features. API documentation can be extracted into a relatively compact form for easy scanning and searching using the phpDocumentor module. Download the module from atutor.ca, and install it like any other module, then run the application to extract the API documentation from ATutor.

phpDocumentor Module

top

## 2. Conventions Used in This Document

This section covers the typographical conventions used in this document.

### 2.1 Typographic Conventions

`Constant width`

  Used for commands and code examples. Example: Use the `debug()` function to view a variable.

``Constant width surrounded by quotes``

  Constant-width font with surrounding quotes is used for filenames and path names. Example: The ``vitals.php`` file is important.

Square brackets (``[`` and ``]``)

  In syntax descriptions, square brackets (``[`` and ``]``) are used to indicate optional words or clauses. Not to be confused with the use of square brackets in `array` definitions. For example, in the following statement, `version` is optional: `./bundle.sh [version]`.

Pipe (``|``)

  When a syntax element consists of a number of alternatives, the alternatives are separated by pipes (``|``).

Example code is to be used as examples only and not as tested production code. In most cases its usefulness in the context of the example outweighs its correctness as workable code. In other cases the syntax and style used in the example itself are irrelevant and do not follow the coding guidelines outlined below. For example, `array`s may be documented using `string` keys without quoting their value, `$_SESSION[prefs]`, while in practice it is always best to escape the key with quotes: `$_SESSION['prefs']`.

### 2.2 Links

All the links in this document open in the current browser. Links that are not obviously to external sites are supplemented with title text. All other links are assumed to be anchors within this document.

### 2.3 Function Definitions (Prototypes)

The usage of the square brackets (``[`` and ``]``) around parameters imply that they are optional, in which case the function documentation will then state what the default value for that variable is. Please pay close attention to the return types of functions: If a function is described to return `boolean` then it will return either `TRUE` or `FALSE` and not an `integer` such as 0 or 1. Optional arguments to functions must always be listed as the last parameters in the list.

`returned_type function_name( param_type $param_name [, opt_param_type $opt_param_name])`

`returned_type`

  Type of value this function returns. See Types and PHP type comparison tables.

`function_name`

  The function name.

`param_type` and `opt_param_type`

  The type of the parameter that the function expects. See Types and PHP type comparison tables.

`$param_name` and `$opt_param_name`

  The names of the parameters as they are used in the function. The `$opt_param_name` is optional.

top

## 3. Setup

Please review the ATutor requirements and ensure that your development environment meets the minimum requirements.

- MySQL.com - Installation MySQL
- PHP.net - Installing PHP with Apache

Now-a-days the Web server and system software need to run ATutor come in easy to install package. Choose the package appropriate for your development platform and install it before installing ATutor.

- XAMP (all platforms)
- MAMP (Mac)
- WAMP (Windows)
- LAMP (Linux)

### 3.1 PHP Configuration

Setting below can be found in the `php.ini` on your system after installing the system software. Listed below are the essential configuration options and their recommended value:

    safe_mode            = Off
    error_reporting      = E_ALL
    display_errors       = On
    arg_separator.input  = ";&"
    register_globals     = Off
    magic_quotes_gpc     = Off
    magic_quotes_runtime = Off
    allow_url_fopen      = On
    register_argc_argv   = Off

top

## 4. GitHub

The ATutor source code is maintained in a GitHub repository, a public version control system that provides "Social Coding" capabilities, making it relatively easy for ATutor developers to have work added to ATutor's public source code. Developers will need to become familiar with Git and GitHub if they wish to participate in ATutor development. There is plenty of documentation on using Git and GitHub. You might read through the book at Git Pro, or review the GitHub Help documentaiton.

### 4.1 Setting up a Git Development Environment

Though there are a variety of Git client applications available, working from a command prompt issuing Git commands is relatively easy to learn. Knowing a small set of Git commands is all you required to get up and running, and contributing code through GitHub.

For Mac users there is GitHub for Mac, which can be installed to setup Git on your Mac. It provides a graphical client through which GitHub can be accessed.

Windows users have a variety of GitHub clients available. A quick search will turn up many. One popular client for Windows is SmartGit. Another is Cygwin

Linux users also have a variety of Github clients available, such as Git Cola or Giggle, among others. And, of course, if you prefer to just work from the command prompt, just install git itself. Most, probably all, Linux systems have a Git package available that can be installed through their package management system. On Ubuntu or Debian for instance, as the root user issue the command `apt-get install git` at the command prompt.

### 4.2 Creating and Maintaining a Git Fork

All developers outside the core development team will work in their own fork of the ATutor source code located on GitHub. Creating a fork is pretty straight forward. Once your GitHub account is setup, and you have logged in, search for the atutor/ATutor repository. At the top of the screen while viewing the repository, click on the `"Fork"` button to create a fork of the master source code. You will now have a copy of the source code linked to your account, something like `[username]/ATutor`, where [username] is your GitHub login.

Now you will want to clone the fork you created into your local development environment. Using your Git client you can then find its "clone" features to generate a local copy, or at the command prompt issue the following commands:

Create a clone
`git clone git@github.com/username/ATutor.git` (create a local copy, or clone, of the fork you created on GitHub)
`cd ATutor` (move into the cloned repository)
`git remote add upstream git://github.com/atutor/ATutor.git` ( for later fetching upstream changes from the main ATutor repository to keep your code current)

Create a branch to work in
`git checkout -b new_feature` (to create a working branch and switch to that branch. give the branch a descriptive name.)
`git branch` (to list the branches)

Edit, create, add copies of file as you would during development
`git status` (to list modified files)
`git add [filename]` (to stage modified file, or "git add *" to stage all modified files)
`git status` (to list staged files)
`git commit -m "describe the changes in a log message"` (to save the staged file to the new_feature branch you created above)
`git log` (to list changes that were committed)

Keep your branch up-to-date (perform these operations often)
`git checkout master` (switch to the local master branch)
`git pull upstream master` (update your local master branch with code from the main ATutor repository)
`git checkout new_feature` (switch to the local new_feature branch)
`git merge master` (merge updates in the local master to your working branch, then resolve any conflicts)

After pulling from the ATutor master repository, review the latest SQL upgrade file to ensure your database structure is up-to-date (in the install/db/ directory ). The file will contain schema changes of the current pre-released source. Example: If the current working source will be version 1.9, then the upgrade file to keep track of will be named `atutor_upgrade_x.y.z_to_1.9.sql`, where `x.y.z` is the version of the currently available stable release.

Submitting code for review and addition to ATutor
`git push origin new_feature` (push your new_feature branch to your own GitHub repository)
Go to https://github.com, login, then under "switch branches" select the `new_feature` branch you just pushed.
Click on the Pull Request button, to send your code for review.
Read through the pull request to ensure it is correct, for example "You're asking atutor to pull [1] commit into atutor:master from username:new_feature"
Press Send pull request to finish your code submission.

Clean up when you're done (after the code has been reviewed, accepted, and merged into the ATutor master branch)
`git branch master` (move into a branch other than the one to be deleted)
`git branch -D new_feature` (delete the branch from your local repository)
`git push origin :new_feature` (remove the branch from GitHub)

### 4.3 Installing from GitHub

Installing the development code cloned from GitHub requires one extra step in addition to the standard installation described in the Installation Instructions. Once the source code has been cloned, change to the ATutor/docs/include directory and create an empty configuration file by issuing the command `touch config.inc.php`, then run the installer as described in the instructions.

top

## 5. Communication

Much communication between developers occurs in the Development Forum. Please try to keep discussions public including any feature proposals. You may also communicate with ATutor development team directly through IRC. Using your IRC client, open `irc://irc.oftc.net/` then join the `#atutor` channel.

top

## 6. Patches

As of ATutor 1.6 the Patcher module is available for applying and developing patches to repair bugs, and to add or modify features in between ATutor releases. Details on creating and applying patches can be found in the ATutor Handbook for version 1.6.1+, or on the ATutor Wiki.

Patcher Documentation

top

## 7. Editor Tips

We use EditPlus, but you can use whichever editor and settings you feel comfortable with. The most important part when editing is to ensure that tabs meet the coding guidelines on indentation. Unix KDE users might use Kate as their text editor.

A few desirable features for a good text editor are listed below:

- Column and row numbering.
- Jump to line number.
- Word wrap toggle.
- Being able to specify soft or hard tabs.
- Syntax highlighting.
- Trim trailing whitespace.
- DOS to UNIX CR/LF conversions. Your editor must be able to save files with UNIX style line breaks. This means the `\n` character instead of the `\r` (Mac style) or `\r\n` (Windows style).

top

## 8. Proposed Features

New feature requests should be posted to the ATutor Feature Requests forum.

top

## 9. Bug Tracking

Please report bugs to the ATutor Bug Reports forum, or directly to the Mantis Bug Tracker. Be sure to indicate the code version being used, such as a release candidate, stable release, nightly build, or GitHub clone, etc. Also be sure to describe the details of the system that ATutor is being developed or tested on, such as the operating system, web server and version, PHP version, etc. Browse the Current Bug Summary for a list of active bug fixing.

top

## 10. Creating Bundles

The file ``bundle.sh`` is located in the root directory of the ATutor source code and is used for creating bundles from the development working directory. The Shell script must be run on UNIX, it will retrieve the latest version of the language from the language database, disable debugging, create an empty config.inc.php file, and lastly create a `.tar.gz` file. Note, by default this script will generate a bundle from the atutor/ATutor GitHub source code repository. You may change this path near the top of the file to point to a local version of the ATutor source code, if for instance you have your own customizations you'd like to build into an installable bundle. Or have it point to your own GitHub repository Usage:

`./bundle.sh [version_number]`
  Note that you will need execute permissions on the script to use it, and if it isn't in your `PATH` then you will have to prefix it with a `./`. The optional `version_number` argument will be used for suffixing onto the file name. For example, a version number of `1.8RC1` will generate a file named `ATutor-1.8RC1.tar.gz`.

top

## 11. Writing Portable Code

When writing your PHP code please try to use functions that exist since (the minimum requirement) PHP version 5.0.2. If you have to use a function that only exists in later versions of PHP, provide an alternative for older versions. To check if the function is available use either `version_compare(phpversion(), $min_version)` or `function_exists($function_name)`.

Code has to work on both Windows and UNIX. You should never use `exec()` or `system()`. In most cases we prefer to write code that works on both systems as is, without the need for if-statements that check for the operating system, since duplicating the functionality twice (once for each operating system) can be a source of bugs. Review the PHP Configuration section for details on how best to set-up your development environment.

top

## 12. Coding Style

This section should help those who would like to modify or add code. Anyone who wishes to contribute code must adhere to these guidelines or the code may not be accepted. Please try to write code that is easy to read and maintained with appropriate comments as needed. Correctness and efficiency are easier to certify if code is simple to read and understand.

### 12.1 Indentation

The importance of indentation for code organization cannot be overstated. Although indentation is not mandatory in PHP, it is a powerful visual organization tool that should consistently be applied to code.

- Indent using 4 spaces for each level.
- Think carefully about when too many nested levels has been reached. (Usually 4-5 is a good limit).
- Use Hard tabs, as described below.

Internally, we have shifted away from Hrad Tab, and now use soft tabs for indenting code. Hard tabs are regular tabs while soft tabs are not really tabs at all; each soft tab is actually represented by a certain number of regular spaces. The benefit of using soft tabs is that they always appear the same, regardless of the editor's tab-spacing. With soft tabs set and enforced, it is easy to maintain consistent indentation and whitespace treatment throughout the code. When hard tabs are used, especially if there are multiple developers using different editors, it is easy for mixed levels of indentation to be introduced, confusing the code's layout. See your editor's settings to have tabs coverted into 4 spaces. PLEASE AVOID USING HARD TABS

### 12.2 Line Length

Split the long lines into multiple lines:

    if (($month = 'jan') || ($month = 'feb') || ($month = 'mar') || ($month = 'apr')) {
        return 1;
    }

You can indent the second line to signify the association with the upper. For particularly long lines, you can indent and align every condition:

    if (($month = 'jan') ||
        ($month = 'feb') ||
        ($month = 'mar') ||
        ($month = 'apr')) {

        return 1;
    }

This methodology works equally well for function parameters:

    echo format_content($content_row['text'],
                        $content_row['formatting'],
                        $glossary,
                        $indent);

### 12.3 Using Whitespace

Whitespace can be used to provide and reinforce logical structure in the code. For example, it can be effectively used to group assignments and show associations. The following example is poorly formatted and difficult to read:

    $password = 'mypassword';
    $website_url = 'http://atutor.ca';
    $first_name = 'Joel';
    $last_name = 'Kronenberg';

But this code block can be improved by using whitespace to logically group related assignments together and align them on the equal sign (`=`):

    $pet_type    = 'mypassword';
    $website_url = 'http://atutor.ca';
    $first_name  = 'Joel';
    $last_name   = 'Kronenberg';

### 12.4 SQL Guidelines

Similar formatting and layout rules applied to PHP can be applied to SQL queries as well. SQL queries, especially in database systems that support complex subqueries, can become convoluted. As with PHP code, whitespace and line breaks should be used in SQL code as needed. Consider the following:

    select employees.first_name, employees.last_name from
                   employees where employees.vacation_time > 0 order by employees.last_name";

This is a simple query, but it is poorly organized. Its organization can be improved in a number of ways, including the following:

- Capitalize SQL keywords.
- Break lines on SQL keywords.
- Use table aliases to keep code clean.

    SELECT   S.first_name, S.last_name
    FROM     students S
    WHERE    S.email = ''
    ORDER BY S.last_name";

### 12.5 SQL/99 Joins

ANSI SQL/99 features ANSI compliant joins. There are several advantages in using this syntax, one of which is the separation of the `JOIN` condition from the `WHERE` clause.

    SELECT	M.email, M.login
    FROM	members M, forums_subscriptions S
    WHERE	S.member_id=M.member_id
    AND     M.email <> ''

SQL/99 makes a clear distinction between the fields in the `JOIN` condition and the `WHERE` clause:

    SELECT	M.email, M.login
    FROM	members M
    JOIN	forums_subscriptions S USING (member_id)
    WHERE	M.email <> ''

### 12.6 Database Queries with queryDB() Function

All database queries from ATutor 2.1.1 onward, should be made using the queryDB function.

- 12.6.1. Code

  The code for the queryDB() function is located in include/lib/mysql_connect.inc.php (to be moved in the future)

- 12.6.2. Function's signature
  - function queryDB($query, $params, $oneRow = false, $sanitize = true)
  - $query - is a vsprintf() formatted SQL string sent to the database
  - $params - is an array of values which would be sanitized by applying the $addslashes() function and then injected into $query. Any variables written directly into a query will not be santized, and should be avoided. Always pass them in through $params.
  - $oneRow - is an optional parameter used as an extra check for queries that are suppose to return only 0 or 1 row (default FALSE)
  - $sanitize - is an optional parameter which will tell the function to sanitize every string parameter by applying $addslashes to it if the parameter is set to true. (default TRUE)
  - return - this function always returns an array, either a single row where columns value make up the array when $oneRow = TRUE,

      Example Returned Arrays:

      //Single row as an array when $oneRow = TRUE
      Array(
          [user_id] => -1
          [help_id] => 1
          [enabled] => 1
          [dismissed] => 1
      )

      //A multi dimentional array of rows at the first level, and columns at the second.

      Array
      (
          [0] => Array
              (
                  [user_id] => -1
                  [help_id] => 1
                  [enabled] => 1
                  [dismissed] => 1
              )
          [1] => Array
              (
                  [user_id] => 5
                  [help_id] => 1
                  [enabled] => 1
                  [dismissed] => 0
              )
          ...
      )

  Queries -- The most common call is queryDB($query, $params);

  Since the queryDB() function is built around vsprintf() you can find how to write those 2 parameters in the following documentation:
  http://php.net/manual/en/function.vsprintf.php, or review the examples below.

  Error handling - in the case of a sql or vsprintf error, the error will be logged into the system's default php_error.log file, an error message will be displayed in ATutor and an empty array will be returned.

  Examples -> Go to Examples
- 12.6.3. Using dynamic queries with variables

  If you need to make a sql query `'select * from prefix_Table where id=some_number and cat_id=some_cat_id'` and you know that prefix_ and some_number might change then you can write the following statement.

      $result = queryDB('select * from %sTable where id=%d and cat_id=%d', array(TABLE_PREFIX, $some_number, $some_cat_id));

  NOTE: that the first parameter above is a string `%s` which will be replaced by the first value in the array the `TABLE_PREFIX` variable, sanitized with`$addslashes`, the second parameter is a decimal `%d` which will be replaced by the second value in the array `$some_number`, converted into integer, and the third parameter is a decimal `%d` which will be replaced by third value in the array `$some_cat_id`, converted into integer.

- 12.6.4. Iterating over results

      Examples:
      ---
      $results = queryDB($sql, $sqlParams);
      foreach ($results as $row) {
          // do something with each row of column values
      }
      ---
      $results = queryDB($sql, $sqlParams);
      foreach ($results as $i=>$row) {
          // do something and use $i as the row number
      }
      ---
      NOTE: oneRow was added "true" for extra checks and coding convenience

      $row = queryDB($sql, $sqlParams, true);
      foreach ($row as $column) {
          // do something with each column value in a single row
      }
      ---
      $row = queryDB($sql, $sqlParams, true);
      foreach ($row as $i=>$column) {
          // do something and use $i as the column number
      }

- 12.6.5. Special MySQL characters

  Since queryDB is built around vsprintf some characters (e.g. % ) are reserved characters and cannot be just passed into the query string. You must use vsprintf syntax to use them (e.g. `%%` )

      // Example:
      // If you want to execute 'select * from Table where Column like "%data%";' Note that
      // there are % signs in the query so queryDB will look like this

      queryDB('select * from Table where Column like "%%data%%"', array());

      OR

      // if you want to use a variable and not to hardcode the value then the function will look
      // like the following

      queryDB('select * from Table where Column like "%%%s%%"', array($data));

  If you look closely you will see `%% %s %%` where every `%%` will be replaced by `%` and `%s` will be replaced by a sanitized string `$data`.

- 12.6.6. Extra debugging

  queryDB has some code that can used to print each query sent to the database to the system's PHP error log by uncommenting the following line

      // The line below must be commented out on production instance of ATutor
      //error_log(print_r(mysql_error(), true), 0)    // NOTE ! Uncomment this line to start logging every single called query. Use for debugging purposes ONLY

- 12.6.7. GOOD practices
  - Use if(empty($result)) to find if returned array has any data.
  - Do not use "foreach ($result as $i=>$row) {" unless you know that you are going to use $i inside of your loop. Keep code as minimal as possible.
  - Make use of $oneRow parameter. It is there to prevent unexpected SQL results. Helps to catch errors, and helps to avoid multidimensional arrays where they are not needed.
  - Use extra debugging on your development environment to see the queries being performed, but be sure debugging is disabled on production systems and that SQL data is not stored in logs which will otherwise create extremely large log files.
  - Utilize queryDB parameters. The function is built in the way that it would sanitize every string and convert parameter to an integer if possible

        // Example:
        // Instead of
        queryDB('update Table set StringColumn="$mystring", IntColumn=$myint', array());

        // Use the following syntax instead
        queryDB('update Table set StringColumn="%s", IntColumn=%d', array($mystring, $myint));

    Note that in the second example $mystring will be sanitized and $myint will be convert into decimal before being injected into the query.

  - Try to utilize built in sanitization and avoid custom built conversions. Any extra conversions or checks added to the code potentially leads to the chance of a human mistake or errors. Code becomes bigger and less manageable. The prospect of copy-pasting the code increases. Instead try to use built in sanitization

        // Example:
        // Instead of doing this:
        global $addslashes;
        $myint = intVal($myint);
        $mystring = $addslashes($mystring);
        queryDB('update Table set StringColumn="$mystring", IntColumn=$myint', array());

        // Use the following line only:
        queryDB('update Table set StringColumn="%s", IntColumn=%d', array($mystring, $myint));

- 12.6.8. Building a complex query

  For the cases when a query permutates depending on variables, the code should be structured properly to accomodate this.

  Imagine you have a situation with the logic that looks as follows:

      if FOO
          if BAR
              query = select * from Table where Name = "some_name" order by some_column
          else
              if BLAH
                  query = select * from Table where Name = "some_name" sort by some_column
              else
                  query = select * from Table where Name = "some_name" and Age = some_age group by some_column
      else
          query = select * from Table where Age = some_age sort by Name

  The best approach would be the following:

      $sql = 'select * from Table';
      $sqlParams = array();
      if (FOO) {
          $sql .= ' where Name = "%s"';
          array_push($sqlParams, $some_name);
          if (BAR) {
              $sql .= ' order by %s';
              array_push($sqlParams, $some_column);
          } else {
              if (BLAH) {
                  $sql .= ' sort by %s';
                  array_push($sqlParams, $some_column);
              } else {
                  $sql .= ' and Age = %d group by %s';
                  array_push($sqlParams, $some_age, $some_column);
              }
          }
      } else {
          $sql .= ' where Age = %d sort by Name';
          array_push($sqlParams, $some_age);
      }
      $result = queryDB($sql, $sqlParams);

- 12.6.9. More Examples

  -     Table: AT_X
        ---------------------
        column A | column B
        ---------------------
        1     |    i
        2     |    ii
        3     |    ii
        4     |    iiii
        ---------------------

        queryDB('select * from %sX', array(TABLE_PREFIX));
        calls: 'select * from AT_X'
        returns: [
                [1, i],
                [2, ii],
                [3, ii],
                [4, iiii]
            ]

  -     $var = 5;
        queryDB('select * from %sX where A=%d', array(TABLE_PREFIX, $var));
        calls: 'select * from AT_X where A=5'
        returns: []

  -     $var = 'ii';
        queryDB('select * from %sX where B="%s"', array(TABLE_PREFIX, $var));
        calls: 'select * from AT_X where B="ii"'
        returns: [
                [2, ii],
                [3, ii]
        ]

  -     $var = 'ii';
        queryDB('select A from %sX where B="%s"', array(TABLE_PREFIX, $var));
        calls: 'select A from AT_X where B="ii"'
        returns: [
                [2],
                [3]
        ]

  -     $var = 'ii';
        queryDB('select * from %sX where B="%s"', array(TABLE_PREFIX, $var), true);
        calls: 'select * from AT_X where B="ii"'
        returns: [], stores and error and throws and error in ATutor

  -     $var = 2;
        queryDB('select * from %sX where A=%d', array(TABLE_PREFIX, $var), true);
        calls: 'select * from AT_X where A=2'
        returns: [2, ii]

  -     $var = 2;
        queryDB('select B from %sX where A=%d', array(TABLE_PREFIX, $var), true);
        calls: 'select B from AT_X where A=2'
        returns: [ii]

  -     $var = 2;
        queryDB('delete from %sX where A=%d', array(TABLE_PREFIX, $var));
        calls: 'delete from AT_X where A=2'
        returns: []

  -     $var = 2;
        queryDB('delete from %sX where A=%d', array(TABLE_PREFIX, $var), true);
        calls: 'delete from AT_X where A=2'
        returns: [], stores and error and throws and error in ATutor

  -     $var = '"Uh oh, this string has not double quotes"';
        queryDB('delete from %sX where B="%s"', array(TABLE_PREFIX, $var), false);
        calls: 'delete from AT_X where B="\"Uh oh, this string has not double quotes\""'
        returns: []

  -     $var = '"this string has not allowed characters"';
        queryDB('delete from %sX where B="%s"', array(TABLE_PREFIX, $var), false, false);
        calls: 'delete from AT_X where B=""Uh oh, this string has not double quotes""'
        returns: []

### 12.7 Control Flow Constructs

- Always use `<?php ?>` instead of the short form `<? ?>`. This implies that you must not use the `<?=$var;?>` short form either.
- Always include the optional semicolon in single line PHP blocks: `<?php echo $something; ?>`
- Use a single quote `'` instead of double quote `"` if there are no variables or special characters.
- Use spaces around string concatenating. `echo 'str' . $value . 'str2';`
- Parenthesis ``( )`` should come right after a function name. `function()` not `function ()`
- Parenthesis ``( )`` should have a space right after a language construct (`if`, `while`, `for`). Examples: `for (...)`, `while (condition)`
- Avoid using `continue` and `break` as it makes debugging more difficult.
- Braces formatting is illustrating below. We use K&R style where the initial brace is placed on the same line as the keyword and the trailing brace inline on its own line with the keyword:

      if (condition) {
          ...
      } else if (condition) {
          ...
      } else {
          ...
      }

- Arrays should be referenced with no spaces. `$arr['index']` not `$arr[ 'index' ]`
- Avoid using short if-statement construct (`$var = ($query ? $val1 : $val2)`) except in very rare cases. It is confusing and has a lot of bug potential.

### 12.8 Commenting

Avoid using Shell/Perl-style (`## this is a comment`) comments entirely. Use C-style comments (`/* ... */`) for large comment blocks and C++-style comments (`// ...`) for single-line comments only:

    /* This is a comment block
     * it is used for describing
     * the code below.
     */
    ...
    // this is a single line comment

Please, document while your code. See phpdoc, for details how to document functions, classes, methods, and variables. Coding is often hurried, but it will save a lot of time in the end to do this type of documenting! It looks like this:

       /**
       * what the function does in one line.
       * more detailed description on 0-n lines, if needed.
       * @access  [public|static|pseudostatic]
       * @param   [string|int|double|bool|array|object|mixed] $paramName1 desc
       * @param   [string|int|double|bool|array|object|mixed] $paramName2 desc
       *  ...
       * @param   [string|int|double|bool|array|object|mixed] $paramNameN desc
       * @return  datatype  description
       * @throws  not until PHP 5
       * @see     some_function()
       * @todo    description
       * @since   ATutor version, PHP version   (comma separated list)
       * @status  stable|experimental           (if not set then considered stable)
       * @pattern singleton|factory|mvc|observer|facade|...
       * @author  description                   (comma separated list)
       */
       function something() {
       }

Note that the description should be given as plain text not HTML. The `@pattern singleton` means that the constructor returns a reference to an already existing instance, if there is one.

### 12.9 Naming Conventions

- 12.9.1 Naming Variables:
  - Use capital letters for constants. E.g. `define('CONSTANT', 1)` and use the capital form of `TRUE`, `FALSE` and `NULL`
  - Otherwise, use all lower case
  - Use `_` to separate words. E.g. `$green_colour_value`
  - Loop variables can be of the usual variety: `$i`, `$j`, `$k`, etc.
  - Count variables should follow the format $*_count. E.g. `$bug_count`, and always initialised to 0
  - Temporary variables should be prefixed with `temp_`
  - `$sql`, `$result`, and `$row` should be used for SQL query, results, and rows respectively
- 12.9.2 Naming Functions:
  - Use all lower case
  - Use `_` to separate words. E.g. `setup_page_breaks()`
  - Keep functions to 5 words or less
  - Functions that print should be prefixed with `print_`.
  - Try to use prefixes to group functions (E.g., `email_`, `news_`, etc.)
- 12.9.3 Naming Files:
  - Use all lower case
  - Use `_` to separate words. E.g. `view_new_bugs_page.php`
  - Use `.php` file extensions (not `.html` or `.php3`)
  - Filenames must be less than 32 characters in length as this works with older file systems like MacOS
  - Included files should be suffixed by `.inc.php`
  - Files containing classes should be suffixed by `.class.php`
  - Exception: Files being included as part of an external library should not be renamed

top

## 13. Directory Structure

The following is a short explanation of the important components of the ATutor directory structure.

### 13.1 Directories

``admin/``
  This directory contains files used for the administration area (when a user logs in as an administrator). This includes files for system statistics, instructor requests, management of users, courses, categories and languages, and server configuration.
``include/``
  This directory contains files that are required or included into other files.
``include/classes/``
  This directory contains classes, essential to certain ATutor functions, such as the phpMailer, XML, Savant templating, and content management classes.
``include/lib/``
  This directory contains library files that hold functions and constants used throughout ATutor code.
``include/install/``
  This directory contains common files included during the installation process. Standalone and Subsite installers will both use these files.
``include/install/db/``
  This directory contains the SQL files necessary to set up or upgrade the ATutor database.
``install/include/``
  This directory contains files used during a standalone installation or upgrade, calling on the files in include/install.
``jscripts/``
  This directory contains all JavaScript files.
``themes/``
  This directory contains the different themes installed on an ATutor system, each with its own subdirectory.
``mods/``
  This directory contains core, standard, and extra modules installed in an ATutor system.

### 13.2 Files

The following is a description of some of the important files.

``include/config.inc.php``
  This file is created during installation and contains specific configuration information for an ATutor system.
``include/vitals.inc.php``
  This file is included by every directly accessible page. It connects to the database, initiates the user session, includes common libraries and constants, and defines frequently used functions.
``include/lib/vital_funcs.inc.php``
  This file includes functions used by vitals.inc.php.
``themes/themes_readme.txt``
  This file contains detailed information on how to create and install a theme.
``include/header.inc.php``
  This file outputs the page's header using the correct template and theme.
``include/html/footer.inc.php``
  This file outputs the page's footer using the correct template and theme.
``include/lib/output.inc.php``
  Most output formatting is done in this file, including things such as language, dates, a paginator, and content formatting, among other things .

top

## 14. Database Structure

A database model diagram (1.4MB PNG) created from the ATutor 2.1.1 database schema is available.

top

## 15. Localisation

All language terms and phrases are stored in the ATutor database. See the `_AT()` function in `include/lib/output.inc.php` for details on displaying text. There are three tables that are used for managing languages, their roles are as follows:

``language_pages``
  This table is used to cross reference language terms with pages. It allows selecting, via a `JOIN`, only the terms needed for a particular page. The `JOIN` may be slow at first but once the result is cached, subsequent calls are many times faster such that only the language needed for a particular page is restored from cache.
``language_text``
  This table holds all of the text for an ATutor installation.
``languages``
  This table holds the list of all available languages on the system and their attributes.

### 15.1 Adding & Editing Language

Please see the Translator Documentation for more details on translating a language within ATutor.

top

## 16. Error and Feedback Messages

All messages are handled using the `Message` class. The main purpose of the `Message` class is to encapsulate the functionality of tracking and managing various message types during a session by providing a nice layer of abstraction between you and the interface to `$_SESSION`, where the messages are stored.

At the moment six types of messages are supported:

`Error`
  Messages reflecting negative feedback to the user, indicating issues that need resolving or addressing.
`Feedback`
  Messages reflecting positive feedback, acknowledging a users action was successfull.
`Warning`
  Messages warning the user of a possible action with undesireable effects.
`Help`
  Messages with helpful information about the current page.
`Info`
  Messages with useful information.
`Confirmation`
  Messages requiring a confirmation in order to execute an action.

Messages can be passed between pages and can be accessed at any time, without any time restriction other than a session timeout.

### 16.1 Internals

Essentially the internals of the class are divided into two segments, a section responsible for printing graphics via Savant templates and another that manages the storage of Messages.

Tracking messages is accomplished by storing message codes and their optional arguments associatively in `$_SESSION`. Printing messages is accomplished via Savant and built in templates which can be found in ``themes/default/``. Message templates can copied into themes other than default/ and modified to change their appearance, though typically changes are made in a secondary theme's styles.css file.

The relational tracking structure is organized in the following manner inside `$_SESSION` in no particular order.

- `message`
  - `error`
    - `AT_ERROR_{*}`
      - `AT_ERROR_{*}`
      - `[argument_1]`
      - `[argument_2]`
  - `warning`
    - `AT_WARNING_{*}`
      - `AT_WARNING_{*}`
      - `[argument_1]`
  - `info`
    - `AT_INFOS_{*}`
      - `AT_INFOS_{*}`
      - `[argument_1]`
  - `help`
    - `AT_HELP_{*}`
      - `AT_HELP_{*}`
      - `[argument_1`
  - `feedback`
    - `AT_FEEDBACK_{*}`
      - `AT_FEEDBACK_{*}`
      - `[argument_1]`
  - `confirm`
    - `AT_CONFIRM_{*}`
      - `AT_CONFIRM_{*}`
      - `[argument_1]`

Messages are automaticaaly purged from `$_SESSION` following an appropriate print command.

### 16.2 Adding Messages

`$msg->add{Error|Warning|Info|Feedback|Help}($code);`

`$code` is a `String` of a language _msgs code or an array with element 0 being the language _msgs code followed by optional arguments. Refer to the language_text table in the database.

Important: One important thing to note is that `$code` must be stripped of the prefix for that type of message. By prefix it is meant `AT_[code_type]_`. For example:

- ``AT_ERROR_FORUM_NOT_FOUND`` should be specified as ``FORUM_NOT_FOUND``, by stripping off the ``AT_ERROR_`` prefix.
- ``AT_WARNING_DELETE_MESSAGE`` as ``DELETE_MESSAGE`` by stripping off ``AT_WARNING_``.
- ``AT_FEEDBACK_LOGOUT`` as ``LOGOUT`` by stripping off ``AT_FEEDBACK_``.
- ``AT_INFOS_MSG_SEND_LOGIN`` as ``MSG_SEND_LOGIN`` by stripping off ``AT_INFOS_``.
- ``AT_HELP_FILE_EXPORTABLE`` as ``FILE_EXPORTABLE`` by stripping off ``AT_HELP_``.

There are two ways of adding messages: a single code or a code with an array of arguments. You can mix-and-match, a combination of both is supported even for the same code. Below is description of the formats:

Adding single code
`$msg->addHelp('FILE_EXPORTABLE');`
OR
Adding array with arguments
`$f = array('FILE_EXPORTABLE', 'arg', 'arg2', ...);`
`$msg->addHelp($f);`

A nice feature implemented is that you do not have to provide all the arguments for a particular code at one time. Subsequent adding of the same code will just append the argument. This allows for greater manipulative flexibility in your source, without writing redundant code. Also note that encoding Feedback codes is no longer necessary for redirection.

Example 1:

`$feedback=array('FORUM_ADDED', 'ac_access_groups');`
`$msg->addFeedback($feedback);`
`// Before we print lets addr another one to the same code`
`$feedback2=array('FORUM_ADDED', 'about_atutor_help_text');`
`$msg->addFeedback($feedback2);`
`// No need to url_encode the code`
`$filename = 'archive.zip';`
`$f = array('FILE_UPLOADED_ZIP', $file_name);`
`$msg->addFeedback($f);`

Snapshot of a portion of `$_SESSION` as a result:

    [feedback] => Array
        (
            [AT_FEEDBACK_FORUM_ADDED] => Array
                (
                    [0] => AT_FEEDBACK_FORUM_ADDED
                    [1] => ac_access_groups
                    [2] => about_atutor_help_text
                )

            [AT_FEEDBACK_FILE_UPLOADED_ZIP] => Array
                (
                    [0] => AT_FEEDBACK_FILE_UPLOADED_ZIP
                    [1] => archive.zip
                )

        )
    	...

`header('Location: file_manager.php');`
`exit;`

### 16.3 Printing Messages

`$msg->print{Errors|Warnings|Infos|Feedbacks|Helps|All}($optional);`

Each will dump all the corresponding tracked messages of that type onto the page at that given line with appropriate graphics defined by its templates file.

`printAll()` allows all Messages of all types to be dumped immediately.

One thing to remember is that once a type of Message is printed all tracked data relating to that type are gone. There is no need to worry about purging messages from `$_SESSION`. The class manages this.

>Notice> `$optional` as the argument to this function. This allows you to shortcut the process of adding and printing Message's in one go. For example, suppose you want to add a Message and print it right away. Thus, you pass as an argument ANY argument that you would pass when adding a Message of that type. Essentially, two lines of code are accomplished in one.

Example:

    $msg->addError('MAX_ATTEMPTS');
    $msg->printErrors();

    can also be accomplished as:

    $msg->printErrors('MAX_ATTEMPTS');

#### Printing String inside Feedback style box

`printNoLookup($str);`

Print `$str` inside a Feedback Message type style box. Performs no dialog with `$_SESSION` or any language mappings in the language_text DB table. Strictly used in `/resources/links/index.php` for compatibility.

#### Checking for existance of specific Message type

`contains{Errors|Warnings|Feedbacks|Helps|Infos}();`

Returns true if the type of Message is being tracked and contains some kind of data. Useful for branching conditions in knowning when to print a Message or not. Otherwise returns false.

#### Manually Deleting a specific Message from storage

`delete{Error|Warning|Feedback|Help|Info}($codcuee);`

Will delete anything related to `$code` from `$_SESSION`

Example:

    	$msg->deleteFeedback('CANCELLED');

#### Example Code

    ...

    require_once(AT_INCLUDE_PATH . '/classes/Message/Message.class.php');

    global $savant;

    $msg = new Message($savant);

    $msg->addError('FORUM_NOT_FOUND');
    $msg->addWarning('SAVE_YOUR_WORK');
    $msg->addInfo('NO_SEARCH_RESULTS');
    $msg->addFeedback('FORUM_ADDED');

    /* State of relevant section of $_SESSION at this point
    [message] => Array
            (
                [error] => Array
                    (
                        [AT_ERROR_FORUM_NOT_FOUND] => AT_ERROR_FORUM_NOT_FOUND
                    )

                [warning] => Array
                    (
                        [AT_WARNING_SAVE_YOUR_WORK] => AT_WARNING_SAVE_YOUR_WORK
                    )

                [info] => Array
                    (
                        [AT_INFOS_NO_SEARCH_RESULTS] => AT_INFOS_NO_SEARCH_RESULTS
                    )

                [feedback] => Array
                    (
                        [AT_FEEDBACK_FORUM_ADDED] => AT_FEEDBACK_FORUM_ADDED
                    )

            )
    */

    // Now print them
    $msg->printErrors();
    $msg->printWarnings();
    $msg->printInfos();
    $msg->printFeedbacks();

    /* State of relevant section of $_SESSION at this point
     [message] => Array
            (
            )
     */

    // Let's add an array of arguments
    $feedback=array('FORUM_ADDED', 'ac_access_groups');
    $msg->addFeedback($feedback);

    // Before we print lets another another one to the same code
    $feedback2=array('FORUM_ADDED', 'about_atutor_help_text');
    $msg->addFeedback($feedback2);

    $msg->addHelp('DEMO_HELP2');

    $help=array('DEMO_HELP2', $_my_uri);
    $msg->addHelp($help);

    $help2=array('ADD_TEST', $_my_uri);
    $msg->addHelp($help2);

    // No need to url_encode the code
    $filename = 'archive.zip';
    $f = array('FILE_UPLOADED_ZIP', $file_name);
    $msg->addFeedback($f);

    /* State of relevant section of $_SESSION at this point. Notice the second addFeddback call above
     * had its arguments appended

     [message] => Array
            (
                [feedback] => Array
                    (
                        [AT_FEEDBACK_FORUM_ADDED] => Array
                            (
                                [0] => AT_FEEDBACK_FORUM_ADDED
                                [1] => ac_access_groups
                                [2] => about_atutor_help_text
                            )

                        [AT_FEEDBACK_FILE_UPLOADED_ZIP] => Array
                            (
                                [0] => AT_FEEDBACK_FILE_UPLOADED_ZIP
                                [1] => archive.zip
                            )

                    )

                [help] => Array
                    (
                        [AT_HELP_DEMO_HELP2] => Array
                            (
                                [0] => AT_HELP_DEMO_HELP2
                                [1] => /~Jay/docs/index.php?
                            )

                        [AT_HELP_ADD_TEST] => Array
                            (
                                [0] => AT_HELP_ADD_TEST
                                [1] => /~Jay/docs/index.php?
                            )

                    )

            }
    */

    $msg->printAll();

    /* State of relevant section of $_SESSION at this point
     [message] => Array
            (
            )
     */

     ...

top

## 16.4 UTF-8 and Multibyte language

As of ATutor 1.6, string parsing is done with multibtyle string functions, either the `mbstring` function in PHP itself, or the multibyte string functions in the UTF-8 library included with ATutor. By default ATutor will attempt to use the PHP `mbstring` functions, and will fall back on the ATutor library if this fails. In order to support both methods of string processing, a set of custom string parsing functions have been created. The only time the ATutor functions will be used is when the mbstring check during the installation or upgrade process has been disabled. The functions mirror the standard string parsing function in PHP, but with the `$` prepended. So, where ever you would normally use a PHP function like `substr()` , instead use `$substr()`. These functions are located in the vitals.inc.php file.

     if (extension_loaded('mbstring')){
    	 $strtolower = 'mb_strtolower';
    	 $strtoupper = 'mb_strtoupper';
    	 $substr = 'mb_substr';
    	 $strpos = 'mb_strpos';
    	 $strrpos = 'mb_strrpos';
    	 $strlen = 'mb_strlen';
     } else {
     	 $strtolower = 'utf8_stringtolower';
    	 $strtoupper = 'utf8_stringtoupper';
    	 $substr = 'utf8_substr';
    	 $strpos = 'utf8_strpos';
    	 $strrpos = 'utf8_strrpos';
    	 $strlen = 'utf8_strlen';
     }

### String functions

- `string $strtolower(string $str)` -- UTF-8 aware strtolower function. Make a string lowercase
- `string $strtoupper(string $str)` -- UTF-8 aware strtolower function. Make a string uppercase
- `int $strpos(string $haystack , string $needle )` -- UTF-8 aware strpos function. Find position of first occurrence of string in a string
- `int $strrpos(string $haystack , string $needle )` -- UTF-8 aware strrpos function. Find position of last occurrence of a string in a string
- `int $strlen(string $str)` -- UTF-8 aware strlen function. Get string length
- `string validate_length(string $input, int $len, int $forDisplay)` -- Checks if the input data has exceeded the database perferred length, if so, the input will be truncated and returned.

#### Description

Starting from 1.6, the above string functions will replace the original string functions when dealing with strings in order to adapt the utf-8 environment.

#### Location

``include/vitals.inc.php``

#### Example 1

To alter a text to lowercase:

    		$str = 'Αρχαίο Πνεύμα';
    		echo $strtolower($str);

#### Example 2

To alter a text to uppercase:

    		$str = 'Αρχαίο Πνεύμα';
    		echo $strtoupper($str);

#### Example 3

To find the middle character of a string:

    		$str = 'Αρχαίο Πνεύμα';
    		$mid = $strlen;
    		echo $strpos($mid, $str);

#### Example 4

To check if the string has the appropriate length:

    		$str = 'Αρχαίο Πνεύμα';
    		$title = validate_length($str, 40);
    		//now the title is safe to insert into the db

top

## 17. Useful Variables

Most of the variables documented here are required for most pages to function correctly. `constant` variables, although not explicitly declared as constants, should be considered as such, and not altered.

### 17.1 $db

#### Description

`constant resource $db`

`$db` is the main database handler. Use it to connect to the ATutor database.

#### Location

``include/vitals.inc.php``

#### NOTE:

The `$db` variable should not be use in versions of ATutor 2.1.1 and beyond, with database queries now being handles by the queryDB() function.

### 17.2 $addslashes

See `$addslashes()`.

### 17.3 $_base_href

#### Description

`constant string $_base_href`

The full URL to the base href of the current page, an equivalence of the "href" attribute value in the page html <base> tag. Supports both regular and SSL protocols. Example: `http://myserver.org/files/ATutor/`.

#### Location

``include/lib/constants.inc.php``

### 17.4 $_base_path

#### Description

`constant string $_base_path`

Extracted from $_base_href, the full absolute base path of the current page. Example: `/files/ATutor/`.

#### Location

``include/lib/constants.inc.php``

### 17.5 $_user_location

#### Description

`constant $_user_location`

`$_user_location` can be one of five values: ``public``, ``admin``, ``users``, ``prog`` or empty. This variable must be set before requiring ``vitals.inc.php``, and specifies what kind of general user authentication the page declaring it needs.

``public`` pages can be viewed by any user, signed-in as a member or not. ``admin`` pages (those in the ``admin/`` directory) can only be viewed by the administrator. ``users`` pages (those in the ``users/`` directory) can only be viewed by logged in members. If `$_user_location` is empty, it is assumed the page can only be accessed when a user is signed-in and viewing a course. ``prog`` is reserved for the pop-up window displaying the progress bar.

This variable was added as a way of specifying which template to use (public, admin, or member). Its role as a way of authenticating is not thoroughly established.

#### Location

Declared on every page that is directly accessible.

### 17.6 $_rel_url

#### Description

`constant string $_rel_url`

The absolute path and file name relative to ATutor's base installation. If ATutor was installed in `http://myserver.org/files/ATutor/`, the `$_rel_url` of the Site-Map page, for example, would evaluate to `/tools/sitemap/index.php`.

This URL will always be the same for a given page, regardless of the location or path of an installation. This variable was added as a way of standardising the ``page`` value in the ``lang_base_pages`` table.

#### Location

``include/lib/constants.inc.php``

### 17.7 $_my_uri

#### Description

`constant string $_my_uri`

The full path and file name to the current page in a format that is ready to accept additional URL arguments. The argument separator will be defined as `SEP`. For example, if the current URL is `http://myserver.org/index.php?cid=806;disable=PREF_MENU;menu_jump=2`, then `$_my_uri` would be `/index.php?cid=806;`.

So, `$_my_uri` is the URL to the current page without the temporary switch arguments. The following URL arguments are removed: `enable`, `disable`, `expand`, `menu_jump`, `g`, `collapse`, `f`, `e`, `save`, and `lang`.

#### Location

``include/lib/vitals.inc.php``

### 17.8 $contentManager

#### Description

`constant ContentManager $contentManager`

The `$contentManager` object provides access to methods for operating on content. All access to the ``content`` table should be done through this object.

#### Locations

``include/vitals.inc.php``
``include/classes/ContentManager.class.php``

### 17.9 $_section

Deprecated in ATutor 1.5

#### Description

`array $_section`

This variable is a two-dimensional `array` used to display a page's breadcrumbs. The first index identifies the page starting from `0` such that `$_section[0]` defines the first page in the hierarchy, `$_section[1]` the second, and so on. The second index is used to assign that page's properties, defined as follows: index `0` is the page title, and index `1` is the URL. This variable must be defined before the ``header.inc.php` file is required.

The URL for the last page (i.e.. the current page) is optional.

#### Example 1

To assign the path to the site-map:

    // the Site-Map is a sub-page of the Tools page, hence we define the path:

    $_section[0][0] = _AT('tools');              // the Tools' page title
    $_section[0][1] = 'tools/';                  // the Tools' page URL
    $_section[1][0] = _AT('sitemap');            // the Site-Map's page title
    $_section[1][1] = 'tools/sitemap/index.php'; // the Site-Map's page URL

#### Location

Declared on every page that is directly accessible.

top

## 18. Useful Functions

The functions listed below provide vital functionality for ATutor pages. Developers will most likely end up using most, if not all, of the functions below. Please review the Function Definitions (Prototypes) section for an explanation of the syntax being used. Additional javadoc comments can be found with each function's definition.

### 18.1 authenticate()

`authenticate()` -- Authenticates the current user against a specified privilege.

#### Description

`mixed authenticate( integer $privilege [, boolean $check] )`

Authenticates the current user against `$privilege`. If `$check` is `AT_PRIV_RETURN` then the function will return the status of the authentication with `TRUE` meaning the user has been successfully authenticated or `FALSE` otherwise. With `$check` set to `FALSE` (default), the function will call `exit` to abort the script if the user cannot be authenticated and return `TRUE` otherwise.

The instructor user will always return `TRUE`.

`$privilege` is set to one of the constants defined in ``include/lib/constants.inc.php``.

Please use only `AT_PRIV_RETURN` or `FALSE` as possible values for `$check` as additional options may be added and the value of the constant changed.

#### Location

``include/vitals.inc.php``

#### Example 1

To authenticate an entire page using the announcements management privilege:

    define('AT_INCLUDE_PATH', '../include/');
    require (AT_INCLUDE_PATH . 'vitals.inc.php');
    /**
    /* exit if the user cannot be authenticated
     * otherwise continue loading the page.
     */
    authenticate(AT_PRIV_ANNOUNCEMENTS);

#### Example 2

To authenticate a block of code using the forums management privilege:

    if (authenticate(AT_PRIV_FORUMS, AT_PRIV_RETURN)) {
        // ... this user has been authenticated
    }

### 18.2 _AT()

`_AT()` -- Returns translated terms.

#### Description

`string _AT( string $term [, string $argument1 [, string $argument2 ...]] )`

This function returns a translated version of `$term` based on the user's current language preference as defined in `$_SESSION[lang]`. If `$term` cannot be found in the language database, it will return ``[ $term ]`` to signify that it was not found.

Terms may require supplements in the form of additional arguments (see example 2). A term may require zero or more arguments. If a `term` requires arguments, then they must all be provided; no argument can be left out.

#### Location

``include/lib/output.inc.php``

#### Example 1

Printing a single term:

    /* echo a translated version of the 'tools' string.
     * i.e. 'Tools' in English, 'Outils' in French, etc..
     */
     $_SESSION['lang'] = 'en';
    echo '<h2>' . _AT('tools') . '</h2>';

     $_SESSION['lang'] = 'fr';
    echo '<h2>' . _AT('tools') . '</h2>';

Result:

    <h2>Tools</h2>
    <h2>Outils</h2>

#### Example 2

Printing a phrase with arguments:

    $username = 'Jon';
    echo _AT('welcome_message', $username);

Result:

    Hello, Jon. Welcome back.

### 18.3 AT_print()

`AT_print()` -- Transforms and formats user data for printing.

#### Description

`string AT_print( string $input, string $field_name [, boolean $runtime_html] )`

This function returns a transformed version of `$input` based on the rules specified by `$field_name`. `$input` is assumed to originate from the database, but it may be generalised in the future.

`$field_name` is the unique name of the `$input` field in the form of `table_name.field_name`. The formatting options for the given field are defined in ``include/lib/constants.inc.php``. If `$field_name` is not a valid option as defined in the constants file then the function will return `$input` unchanged.

The boolean `$runtime_html` is used by fields which have an optional HTML formatting field. `$runtime_html` should be the associated HTML formatting field for that data. If set to `FALSE` then HTML elements will be escaped from `$input` and new line characters converted to `<br />`s.

No data from the database should be printed without passing it through this function first.

#### Location

``include/lib/output.inc.php``

#### Example 1

Printing a field where HTML is not allowed:

    $username = 'my_name<b>_is';
    $value    = AT_print($username, 'members.login'); // escape the '<b>' tag
    echo $value

Result:

    my_name<b>_is

### 18.4 AT_date()

`AT_date()` -- Returns a localised version of a date.

#### Description

`string AT_date( [string $format [, integer $timestamp [, integer $format_type]]] )`

This function returns the `string` representation of the given `$timestamp` as transformed by `$format`. Uses the same options as PHP's `date()` function, but requires a `%` in front of each argument. If `$timestamp` is not specified, then the current time will be used.

`$format_type` specifies the type of time stamp being provided. Available types are defined in ``include/lib/constants.inc.php``. Possible options are:

`AT_DATE_MYSQL_DATETIME`
  The default. Format `YYYY-MM-DD HH:MM:SS`.
`AT_DATE_MYSQL_TIMESTAMP_14`
  Format `YYYYMMDDHHMMSS`.
`AT_DATE_UNIX_TIMESTAMP`
  A regular UNIX time stamp; seconds since epoch.
`AT_DATE_INDEX_VALUE`
  A special case specifying that only the single value of `$format` should be returned. The index into a specified date `array`. Only available for the following date options: `%D`, `%l`, `%F`, `%M`.

The following arguments are language dependent:

`%D`
  A three-letter textual representation of a day, Mon through Sun
`%F`
  A full textual representation of a month, January through December
`%l` (lowercase 'L')
  A full textual representation of the day of the week, Monday through Sunday
`%M`
  A three-letter textual representation of a month, Jan through Dec

The following arguments are not yet supported to be language dependent, but may be in the future:

`%S`
  English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with `%j`
`%a`
  Lowercase Ante meridiem and Post meridiem am or pm
`%A`
  Uppercase Ante meridiem and Post meridiem AM or PM

In most (soon to be all) cases, `$format` will be specified using a call to `_AT()` to retrieve the correct date format for that language. See Example 2 below.

#### Location

``include/lib/output.inc.php``

#### Example 1

Returning a specified date using a UNIX time stamp:

    $time = mktime(0, 0, 0, 7, 14, 2004);
    echo AT_Date('%l %F %j, %Y', $time, AT_DATE_UNIX_TIMESTAMP);

Result:

    Wednesday July 14, 2004

#### Example 2

Returning a specified date using a UNIX time stamp that is also language dependent:

    $time = mktime(0, 0, 0, 7, 14, 2004);

    $_SESSION['lang'] = 'en';
    echo AT_Date(_AT('announcement_date_format'), $time, AT_DATE_UNIX_TIMESTAMP);

    echo '<br />';
    $_SESSION['lang'] = 'fr';
    echo AT_Date(_AT('announcement_date_format'), $time, AT_DATE_UNIX_TIMESTAMP);

Result:

    Wednesday July 14, 2004
    mercredi, 14 juillet 2004

#### Example 3

Returning a single month name:

    $_SESSION['lang'] = 'fr';
    The second month in French is: <?php echo AT_date('%F', 2, AT_DATE_INDEX_VALUE) ?>

Result:

    The second month in French is: f憝rier

### 18.5 $addslashes()

`$addslashes()` -- Quotes a string with slashes.

#### Description

`string $addslashes( string $str )`

If `get_magic_quotes_gpc` is disabled, then this variable function maps onto `addslashes()`, otherwise it maps onto `my_add_null_slashes()` which simply returns the input `$str` unchanged.

#### Location

``include/vitals.inc.php``

#### Example 1

With `magic_quotes_gpc` enabled:

    $str = "What's going on?";

    // prints magic_quotes_gpc: 1
    echo 'magic_quotes_gpc: ' . get_magic_quotes_gpc();

    // maps to my_add_null_slashes(). prints What\'s going on? [correct]
    echo $addslashes($str);

    // prints What\\\'s going on? [wrong]
    echo addslashes($str);

#### Example 2

With `magic_quotes_gpc` disabled:

    $str = "What's going on?";

    // prints magic_quotes_gpc: 0
    echo 'magic_quotes_gpc: ' . get_magic_quotes_gpc();

    // maps to addslashes(). prints What\'s going on? [correct]
    echo $addslashes($str);

    // prints What\'s going on? [correct]
    echo addslashes($str);

### 18.6 debug()

`debug()` -- Outputs a variable.

#### Description

`void debug( mixed $var [, string $title] )`

This function is used for printing variables for debugging. `$var` can be of any type. The output is nicely formatted and easy to read. `debug()` will not output anything if the constant `AT_DEVEL` evaluates to `FALSE`.

`$title` is available to label the debugging box for distinguishing it from other debugging boxes on the same page.

#### Location

``include/vitals.inc.php``

#### Example 1

Viewing the contents of an `array`:

    $my_array = array('apple' => 'green', 4 => 'something');
    debug($my_array, 'my_array');

Result:

        >my_array>>
    Array
    (
        [apple] => green
        [4] => something
    )

### 18.7 get_login()

`get_login()` -- Returns the login name of a member.

#### Description

`string get_login( integer $id )`

Returns the login name of the member whose ID is `$id`. There is no error handling.

#### Location

``include/vitals.inc.php``

### 18.8 urlencode_feedback()

`urlencode_feedback()` -- Encodes a feedback code.

#### Description

`mixed urlencode_feedback( mixed $f )`

This function returns a URL safe encoding of a feedback code. Its purpose is to encode the feedback into the URL so that the page being redirected to will then output the feedback. `$f` may be an `array` of feedback codes, where additionally, each feedback code may be an array consisting of supplementary arguments. If `$f` is an `array` then the return value will be its `string` representation, otherwise the function will return `$f` unchanged.

The way feedback is implemented may change in the future, so it is best to use this function even if the feedback code is not an `array`.

#### Location

``include/vitals.inc.php``

#### Example 1

To encode a feedback array:

    $f[] = array(AT_FEEDBACK_FILE_UPLOADED_ZIP, $file_name);

    header('Location: file_manager.php?f='.urlencode_feedback($f));
    exit;

### 18.9 url_rewrite()

`url_rewrite()` -- Change an url to a pretty url.

#### Description

`string url_rewrite( string $url, boolean $is_rewriting_header, boolean $force)`

`$url`

  the Url should be a relative link to the file.

`$is_rewriting_header`

  Determine if url_rewrite is rewriting a header (location: ..) path or not. Available values are AT_PRETTY_URL_IS_HEADER, AT_PRETTY_URL_NOT_HEADER(default). Use AT_PRETTY_URL_IS_HEADER if url_rewrite is being called inside header(Location:...)

`$force`

  Apply url_rewrite forcefully if it is true, default value is false.

This function returns a pretty URL from the given parameter. Its purpose is to change the URLs to a "prettier" format in order to extend user friendliness in the system, and to create indexes for Google search. This function will authenticate itself towards the current pages. In our definition, admins, login, registration pages should not have pretty url applied. However, if one want to use url_rewrite on these pages, please set `$force` to TRUE, this will force it to change the urls to pretty urls. Please note that the admin's system preference will still overwrite the force effect. `$url` may be an `string` of URL, '?' and the seprators in the URL query will be replaced by slashes. Please note that the PHP_SELF variable might break some of the form action/header redirect because the Pretty URI is a virtual path. To address this problem, set $is_rewriting_header to AT_PRETTY_URL_IS_HEADER, as demonstrated in example 3.

#### Location

``include/vitals.inc.php``

#### Example 1

To change an URL:

    $url = 'forum/view.php?fid=3&pid=4';
    echo url_rewrite($url);		//output go.php/1/forum/view.php/fid/3/pid/4

#### Example 2

To change an URL for mods:

    $url = 'mods/hello_world/index.php';
    echo url_rewrite($url, true);		//output go.php/1/mods/hello_world/index.php

#### Example 3

To change an URL for header redirection:

    header('Location: '. url_rewrite('forum/index.php', AT_PRETTY_URL_IS_HEADER));

top

## 19. Useful Constants

These constants are part of the vital functionality of ATutor.

### 19.1 AT_INCLUDE_PATH

#### Description

The `AT_INCLUDE_PATH` must be defined before you `require` or `include` any files. The constant defines the relative path to the ``include/`` directory. For security reasons no file should ever be called-in without using this constant!

#### Example 1

Requiring the vitals file from the tools page:

    define('AT_INCLUDE_PATH', '../include/');
    require (AT_INCLUDE_PATH . 'vitals.inc.php');

#### Location

Declared on every page that is directly accessible.

### 19.2 SEP

#### Description

For XHTML compliance, we have created this constant to use when applying variables to URL arguments. The constant is one of the values defined by PHP's `arg_separator.input`, with a preference for the semi-colon (``;``), if available, over the ampersand (``&``).

#### Example 1

Printing a dynamic link:

    $arg1 = 'one';
    $arg2 = 'two';

    echo "SEP is ".SEP."\n";
    echo '<a href="index.php?arg1=' . $arg1 . SEP . 'arg2=' . $arg2 . '">link</a>';

Result:

    SEP is ;
    <a href="index.php?arg1=one;arg2=two">link</a>

#### Location

``include/lib/constants.inc.php``

### 19.3 AT_DEVEL

#### Description

Enables or disables usage of the debug() function.

#### Location

``include/vitals.inc.php``

### 19.4 TABLE_PREFIX

#### Description

The `TABLE_PREFIX` constant holds the prefix to the ATutor database tables. It is needed when creating SQL queries.

#### Location

``include/config.inc.php``

### 19.5 VERSION

#### Description

The version number of this ATutor installation.

#### Location

``include/lib/constants.inc.php``

top

## 20. Install & Upgrade Scripts

Installing or upgrading ATutor is done with the scripts found in the ``install/`` directory. Two files in particular control the installation or upgrading flow and are appropriately named ``install.php`` and ``upgrade.php``. For actual documentation on installing or upgrading please see ATutor's official documentation.

The ``install/`` directory contains two other subdirectories that are used during the installation or upgrade process. The ``install/db/`` directory contains database schema files and are clearly labeled. The ``install/include/`` directory contains scripts that are common to both processes and labeled according to their order in either process.

### 20.1 Install Script

The ``install.php`` script requires each step as it's needed as the `$step` counter variable is incremented. To add or edit a step, edit the ``install.php`` file.

### 20.2 Upgrade Script

The ``upgrade.php`` script works exactly the same as the install script does, but requires different files (step prefixed with a 'u'). To upgrade the database schema an SQL file named ``atutor_upgrade_from_to_to.sql`` must be created, where `from` is the exact version of the previous ATutor version, and `to` is the next stable version.

top

## 21. Accessibility

Part of ATutor's philosophy is to be "designed with accessibility and adaptability in mind", we advise you to consider carefully the practices outlined on the following sites:

- WAI Quick Tips
- Web-Savvy & Standards Compliance
- ATutor's specific accessibility features

top

## 22. Validation

Please use the W3C Markup Validation Service, a free service, to check your pages for XHTML conformance, W3C Recommendations and other standards.

top

## 23. Sample Script

The following is sample code that shows the general flow of an ATutor script. The example shows how you may use some of the variables and functions available to you. Some scripts may not need all the variables and functions used below.

    <?php
    // 0. insert the SVN keywords
    // $Id: guidelines.html 1275 2004-07-28 16:02:49Z joel $

    // 1. define relative path to `include` directory:
    define('AT_INCLUDE_PATH', '../include/');

    // 2. require the `vitals` file before any others:
    require (AT_INCLUDE_PATH . 'vitals.inc.php');

    // 3. authenticate this user:
    authenticate(AT_PRIV_SPECIAL_PRIV);

    // 4. define the breadcrumbs path:
    $_section[0][0] =  _AT('tools');
    $_section[0][1] = 'tools/';
    $_section[1][0] =  _AT('my_page');
    $_section[1][1] =  'tools/page.php;

    // 5. handle any post request:
    if (isset($_POST['submit'])) {
      // 5.1 check for errors:
      if ($_POST['some_field'] == '') {
          $msg->addError('SOME_ERROR_CODE');
      }

      if (!$msg->containsErrors()) {
          //5.2 complete the desired action here. (example: insert into DB)

          //5.3 set the feedback message and add it to the URL:
          $msg->addFeedback('MESSAGE');
          $url = $_base_href . 'tools/index.php?arg1=yes';

          //5.4 redirect after successful operation:
          header('Location: ' . $url);
          exit;
      }
    }

    // 6. start the page display by calling the header
    require (AT_INCLUDE_PATH . 'header.inc.php');

    // 7. display any feedback or error messages that my occur:
    require (AT_INCLUDE_PATH . 'html/feedback.inc.php');

    /*
     * 8. display the page contents here.
     */

    // 9. finish the page by calling the footer
    require (AT_INCLUDE_PATH . 'footer.inc.php');
    ?>

top

## 24. Credits & Additional Sources

- ATutor.ca
- ATutor Developer Support Forum
- Documentation
  - ATutor Translator Documentation
  - PHP Manual
  - The Git Book
  - MySQL Documentation
  - Blueshoes.org - Coding Guidelines for BlueShoes Developers by Andrej Arn
  - Blueshoes.org - PHP Syntax Exam
  - Blueshoes.org - PHP Cheat Sheet
  - HTMLhelp.com - Cascading Style Sheets by John Pozadzides and Liam Quinn
  - Apache HTTP Server Documentation
  - W3C's Web Content Accessibility Guidelines
- Tools
  - phpMyAdmin
  - EditPlus
  - Git Clients