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.
topATutor, 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.
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.
topThis section covers the typographical conventions used in this document.
Used for commands and code examples. Example: Use the debug() function to view a variable.
Constant-width font with surrounding quotes is used for filenames and path names. Example: The `vitals.php` file is important.
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].
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, arrays 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'].
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.
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])
Type of value this function returns. See Types and PHP type comparison tables.
The function name.
The type of the parameter that the function expects. See Types and PHP type comparison tables.
The names of the parameters as they are used in the function. The $opt_param_name is optional.
Please review the ATutor requirements and ensure that your development environment meets the minimum requirements.
If you have a dedicated development environment that doesn't share a web server with other production code, then it is best to use the bundled php.ini-dist configuration file as the default--simply rename it to php.ini. 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 = Offtop
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.
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.
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
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)
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.
topMuch communication between developers occurs in the Development Forum. Please try to keep discussions public including any feature proposals. You may also communicate with directly through IRC. Using your IRC client, open irc://irc.oftc.net/ then join the #atutor channel.
topAs of ATutor 1.6 the Patcher module is available for applying and developing patches to repair bugs, and to add or modify features. Details on creating and applying patches can be found in the ATutor Handbook for version 1.6.1+, or on the ATutor Wiki.
topWe 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:
The Proposed Features page lists features which have been requested by the ATutor community. ATutor.ca members can vote on features to establish a priority, while potential developers may then assign themselves to tasks. New feature requests should be posted to the ATutor Feature Requests forum.
topPlease 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 SVN checkout, 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.
topThe file `bundle.sh` is located in a directory above `docs` and is used for creating bundles from the working `docs` directory. The Shell script must be run on UNIX and will retrieve the latest version of the language from the database, disables debugging, creates an empty config.inc.php filr, and lastly create a .tar.gz file. Note, by default this script will generate a bundle from the atutor svn 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. Usage:
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.
When writing your PHP code please try to use functions that exist since (the minimum requirement) PHP version 4.3.0. 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.
topThis 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 maintain with appropriate comments as needed. Correctness and efficiency are easier to certify if code is simple to read and understand.
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.
Internally, we have used hard tabs as we all use the same editor, but we may decide to move to soft tabs in the future. 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 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.
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);
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';
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:
SELECT S.first_name, S.last_name FROM students S WHERE S.email = '' ORDER BY S.last_name";
ANSI SQL/99 features ANSI compliant joins. There are several advantages in using this new 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 <> ''
if (condition) { ... } else if (condition) { ... } else { ... }
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, like javadoc, 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.
The following is a short explanation of the important components of the ATutor directory structure.
The following is a description of some of the important files.
A database model diagram (153 KB GIF) created from the ATutor 1.4.1 database schema is available. (somewhat outdated)
topAll language terms and phrases are stored in the ATutor database. See the _AT() function for details on displaying text. There are three tables that are used for managing languages, their roles are as follows:
Please see the Translator Documentation for more details on translating a language within ATutor.
topAll 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:
Please note that using the old method of passing messages is not supported anymore.
Messages can be passed between pages and can be accessed at any time, without any time restriction other than a session timeout.
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 `templates/`.
The relational tracking structure is organized in the following manner inside $_SESSION in no particular order.
Messages are automaticaaly purged from $_SESSION following an appropriate print command.
$code is a
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:
There are two ways of adding messages: a single code or a code with an array fo arguments. You can mix-and-match, a combination of both is supported even for the same code. Below is description of the formats:
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:
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 ) ) ...
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.
$msg->addError('MAX_ATTEMPTS'); $msg->printErrors(); can also be accomplished as: $msg->printErrors('MAX_ATTEMPTS');
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.
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.
Will delete anything related to $code from $_SESSION
$msg->deleteFeedback('CANCELLED');
... 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
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 vital.inc.php
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'; }
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.
`include/vitals.inc.php`
To alter a text to lowercase:
$str = 'Αρχαίο Πνεύμα'; echo $strtolower($str);
To alter a text to uppercase:
$str = 'Αρχαίο Πνεύμα'; echo $strtoupper($str);
To find the middle character of a string:
$str = 'Αρχαίο Πνεύμα'; $mid = $strlen; echo $strpos($mid, $str);
To check if the string has the appropriate length:
$str = 'Αρχαίο Πνεύμα'; $title = validate_length($str, 40); //now the title is safe to insert into the dbtop
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.
constant resource $db
$db is the main database handler. Use it to connect to the ATutor database.
`include/vitals.inc.php`
See $addslashes().
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/.
`include/lib/constants.inc.php`
constant string $_base_path
Extracted from $_base_href, the full absolute base path of the current page. Example: /files/ATutor/.
`include/lib/constants.inc.php`
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.
Declared on every page that is directly accessible.
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.
`include/lib/constants.inc.php`
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.
`include/lib/vitals.inc.php`
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.
`include/vitals.inc.php`
`include/classes/ContentManager.class.php`
Deprecated in ATutor 1.5
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.
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
Declared on every page that is directly accessible.
topThe 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.
authenticate() -- Authenticates the current user against a specified privilege.
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.
`include/vitals.inc.php`
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);
To authenticate a block of code using the forums management privilege:
if (authenticate(AT_PRIV_FORUMS, AT_PRIV_RETURN)) { // ... this user has been authenticated }
_AT() -- Returns translated terms.
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.
`include/lib/output.inc.php`
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>
Printing a phrase with arguments:
$username = 'Jon'; echo _AT('welcome_message', $username);
Result:
Hello, Jon. Welcome back.
AT_print() -- Transforms and formats user data for printing.
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.
`include/lib/output.inc.php`
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
AT_date() -- Returns a localised version of a date.
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:
The following arguments are language dependent:
The following arguments are not yet supported to be language dependent, but may be in the future:
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.
`include/lib/output.inc.php`
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
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
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
$addslashes() -- Quotes a string with slashes.
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.
`include/vitals.inc.php`
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);
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);
debug() -- Outputs a variable.
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.
`include/vitals.inc.php`
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 )
get_login() -- Returns the login name of a member.
string get_login( integer $id )
Returns the login name of the member whose ID is $id. There is no error handling.
`include/vitals.inc.php`
urlencode_feedback() -- Encodes a feedback code.
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.
`include/vitals.inc.php`
To encode a feedback array:
$f[] = array(AT_FEEDBACK_FILE_UPLOADED_ZIP, $file_name); header('Location: file_manager.php?f='.urlencode_feedback($f)); exit;
url_rewrite() -- Change an url to a pretty url.
string url_rewrite( string $url, boolean $is_rewriting_header, boolean $force)
the Url should be a relative link to the file.
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:...)
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.
`include/vitals.inc.php`
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
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
To change an URL for header redirection:
header('Location: '. url_rewrite('forum/index.php', AT_PRETTY_URL_IS_HEADER));top
These constants are part of the vital functionality of ATutor.
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!
Requiring the vitals file from the tools page:
define('AT_INCLUDE_PATH', '../include/'); require (AT_INCLUDE_PATH . 'vitals.inc.php');
Declared on every page that is directly accessible.
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 (`&`).
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>
`include/lib/constants.inc.php`
Enables or disables usage of the debug() function.
`include/vitals.inc.php`
The TABLE_PREFIX constant holds the prefix to the ATutor database tables. It is needed when creating SQL queries.
`include/config.inc.php`
The version number of this ATutor installation.
`include/lib/constants.inc.php`
topInstalling 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.
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.
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.
topPart 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:
topPlease use the W3C Markup Validation Service, a free service, to check your pages for XHTML conformance, W3C Recommendations and other standards.
topThe 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