# Moodle Coding Guidelines

Any collaborative project needs consistency and stability to stay strong.

These guidelines are to provide a goal for all Moodle code to strive to. It's true that some of the older existing code falls short in a few areas, but it will all be fixed eventually. All new code definitely must adhere to these standards as closely as possible.

## General Rules

1. All code files should use the .php extension.
2. All template files should use the .html extension.
3. All text files should use Unix-style text format (most text editors have this as an option).
4. All php tags must be 'full' tags like <?php ?> ... not 'short' tags like <? ?>.
5. All existing copyright notices must be retained. You can add your own if necessary.
6. Each file should include the main config.php file.
7. Each file should check that the user is authenticated correctly, using require_login() and isadmin(), isteacher(), iscreator() or isstudent().
8. All access to databases should use the functions in lib/datalib.php whenever possible - this allows compatibility across a wide range of databases. You should find that almost anything is possible using these functions. If you must write SQL code then make sure it is: cross-platform; restricted to specific functions within your code (usually a lib.php file); and clearly marked.
9. Don't create or use global variables except for the standard $CFG, $SESSION, $THEME and $USER.
10. All variables should be initialised or at least tested for existence using isset() or empty() before they are used.
11. All strings should be translatable - create new texts in the "lang/en" files with concise English lowercase names and retrieve them from your code using get_string() or print_string().
12. All help files should be translatable - create new texts in the "en/help" directory and call them using helpbutton().

    If you need to update a help file:

    - with a minor change, where an old translation of the file would still make sense, then it's OK to make the change but you should notify translation@moodle.org
    - for a major change you should create a new file by adding an incrementing number (eg filename2.html) so that translators can easily see it's a new version of the file. Obviously the new code and the help index files should also be modified to point to the newest versions.
13. Incoming data from the browser (sent via GET or POST) automatically has magic_quotes applied (regardless of the PHP settings) so that you can safely insert it straight into the database. All other raw data (from files, or from databases) must be escaped with addslashes() before inserting it into the database.
14. IMPORTANT: All texts within Moodle, especially those that have come from users, should be printed using the format_text() function. This ensures that text is filtered and cleaned correctly.

## Coding Style

I know it can be a little annoying to change your style if you're used to something else, but balance that annoyance against the annoyance of all the people trying later on to make sense of Moodle code with mixed styles. There are obviously many good points for and against any style that people use, but the current style just is, so please stick to it.

1. Indenting should be consistently 4 spaces. Don't use tabs AT ALL.
2. Variable names should always be easy-to-read, meaningful lowercase English words. If you really need more than one word then run them together, but keep them short as possible. Use plural names for arrays of objects.

   GOOD: $quiz
   GOOD: $errorstring
   GOOD: $assignments (for an array of objects)
   GOOD: $i (but only in little loops)
   BAD: $Quiz
   BAD: $aReallyLongVariableNameWithoutAGoodReason
   BAD: $error_string

3. Constants should always be in upper case, and always start with the name of the module. They should have words separated by underscores.

   define("FORUM_MODE_FLATOLDEST", 1);

4. Function names should be simple English lowercase words, and start with the name of the module to avoid conflicts between modules. Words should be separated by underscores. Parameters should always have sensible defaults if possible. Note there is no space between the function name and the following (brackets).

   function forum_set_display_mode($mode=0) {
   global $USER, $CFG;
   if ($mode) {
   $USER->mode = $mode;
   } else if (empty($USER->mode)) {
   $USER->mode = $CFG->forum_displaymode;
   }
   }

5. Blocks must always be enclosed in curly braces (even if there is only one line). Moodle uses this style:

   if ($quiz->attempts) {
   if ($numattempts > $quiz->attempts) {
   error($strtoomanyattempts, "view.php?id=$cm->id");
   }
   }

6. Strings should be defined using single quotes where possible, for increased speed.

   $var = 'some text without any variables';
   $var = "with special characters like a new line \n";
   $var = 'a very, very long string with a '.$single.' variable in it';
   $var = "some $text with $many variables $within it";

7. Comments should be added as much as is practical, to explain the code flow and the purpose of functions and variables.
   - Every function (and class) should use the popular phpDoc format. This allows code documentation to be generated automatically.
   - Inline comments should use the // style, laid out neatly so that it fits among the code and lines up with it.

   /**
   * The description should be first, with asterisks laid out exactly
   * like this example. If you want to refer to a another function,
   * do it like this: {@link clean_param()}. Then, add descriptions
   * for each parameter as follows.
   *
   * @param int $postid The PHP type is followed by the variable name
   * @param array $scale The PHP type is followed by the variable name
   * @param array $ratings The PHP type is followed by the variable name
   * @return mixed
   */
   function forum_get_ratings_mean($postid, $scale, $ratings=NULL) {
   if (!$ratings) {
   $ratings = array(); // Initialize the empty array
   if ($rates = get_records("forum_ratings", "post", $postid)) {
   // Process each rating in turn
   foreach ($rates as $rate) {
   ....etc

8. Space should be used liberally - don't be afraid to spread things out a little to gain some clarity. Generally, there should be one space between brackets and normal statements, but no space between brackets and variables or functions:

   foreach ($objects as $key => $thing) {
   process($thing);
   }
   if ($x == $y) {
   $a = $b;
   } else if ($x == $z) {
   $a = $c;
   } else {
   $a = $d;
   }

## Database structures

1. Every table must have an auto-incrementing id field (INT10) as primary index.
2. The main table containing instances of each module must have the same name as the module (eg widget) and contain the following minimum fields:
   - id - as described above
   - course - the id of the course that each instance belongs to
   - name - the full name of each instance of the module
3. Other tables associated with a module that contain information about 'things' should be named widget_things (note the plural).
4. Column names should be simple and short, following the same rules as for variable names.
5. Where possible, columns that contain a reference to the id field of another table (eg widget) should be called widgetid. (Note that this convention is newish and not followed in some older tables)
6. Boolean fields should be implemented as small integer fields (eg INT4) containing 0 or 1, to allow for later expansion of values if necessary.
7. Most tables should have a timemodified field (INT10) which is updated with a current timestamp obtained with the PHP time() function.

## Security Issues (and handling form and URL data)

1. Do not rely on 'register_globals'. Every variable must be properly initialised in every code file. It must be obvious where the variable came from
2. Initialise all arrays and objects, even if empty. `$a = array()` or `$obj = new stdClass();`.
3. Do not use the `optional_variable()` function. Use the `optional_param()` function instead. Pick the correct PARAM_XXXX value for the data type you expect. To check and set an optional value for a variable, use the `set_default()` function.
4. Do not use the `require_variable()` function. Use the `required_param()` function instead. Pick the correct PARAM_XXXX value for the data type you expect.
5. Use `data_submitted()`, with care. Data must still be cleaned before use.
6. Do not use `$_GET`, `$_POST` or `$_REQUEST`. Use the appropriate `required_param()` or `optional_param()` appropriate to your need.
7. Do not check for an action using something like `if (isset($_GET['something']))`. Use, e.g., `$something = optional_param( 'something',-1,PARAM_INT )` and then perform proper test for it being in its expected range of values e.g., `if ($something>=0) {...`.
8. Wherever possible group all your `required_param()`, `optional_param()` and other variables initialisation at the beginning of each file to make them easy to find.
9. Use 'sesskey' mechanism to protect form handling routines from attack. Basic example of use: when form is generated, include `<input type="hidden" name="sesskey" value="<?php echo sesskey(); ?>" />`. When you process the form check with `if (!confirm_sesskey()) {error('Bad Session Key');}`.
10. All filenames must be 'cleaned' using the `clean_filename()` function, if this has not been done already by appropriate use of `required_param()` or `optional_param()`
11. Any data read from the database must have `addslashes()` applied to it before it can be written back. A whole object of data can be hit at once with `addslashes_object()`.
12. Wherever possible, data to be stored in the database must come from `POST` data (from a form with `method="POST"`) as opposed to `GET` data (ie, data from the URL line).
13. Do not use data from `$_SERVER` if you can avoid it. This has portability issues.
14. If it hasn't been done somewhere else, make sure all data written to the database has been through the `clean_param()` function using the appropriate PARAM_XXXX for the datatype.
15. If you write custom SQL code, make very sure it is correct. In particular watch out for missing quotes around values. Possible SQL 'injection' exploit.
16. Check all data (particularly that written to the database) in every file it is used. Do not expect or rely on it being done somewhere else.
17. Blocks of code to be included should contain a definite PHP structure (e.g, a class declaration, function definition(s) etc.) - straight blocks of code promote uninitialised variable usage.

Moodle Documentation

Version: $Id: coding.html,v 1.1 2006/02/06 09:28:54 moodler Exp $