Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.


This classes within the 'core\command' namespace are intended to be used when Totara code needs to interact with external programs. Typically, a developer might use built-in PHP functions such as exec(), shell_exec() or a number of others which execute commands on the shell (command line). By having these classes, we can provide additional security on top of functions such as those. If future issues arise in this domain, we should only have to fix them in one place rather than everywhere that could trigger an external command.

Risks that we can protect against by centralising this code could include, among other things, harmful commands appearing on the command line due to differences between operating systems for characters used for escaping, preventing a problem program from being run by excluding it from the white list or being able to easily identify where we can restrict the types of arguments provided to a program.

Using the API in new code

To run a program in new code:


On a Unix command line, the above code would execute a shell command that would look like so:  '/path/to/exe' switch1 key1 '123'

White listing

If the new code is going into core. The path to the program will need to be added to the get_whitelist() method inside the \core\command\executable class. In order for this to work across operating systems, this would be a setting, so see how other code gets this path. Likely from a $CFG setting or using get_config().


If code is added that does not include the program in the white list at all, running it via the command line will also not work. This obviously only applies when this API is used and doesn't prevent an external program being run by the built-in functions such as exec().


Validation is performed on values only (either when added on their own via add_value() or added as the value in a key/value pair via add_argument()).


If validation is failed. An exception is thrown, typically this would be \core\command\exception, however a \moodle_exception may be thrown in some cases if it arose from clean_param().


When adding values, an $escape_ifnopcntl argument is available. If the PCNTL library is being used, values will not need to be escaped, and so they won't be. Otherwise, on the command line, values will be escaped.

If you are sure that the values do not need to be escaped, i.e. it's not user input, and it is required that these values are not escaped, even on the command line, set this value to false to allow this.


The PCNTL library is typically only available when PHP is executed on the command line and on Unix. It is an extension that will need to be installed and enabled. The command execution API described here will allow it to be run even with requests sent to the web server rather than just via the CLI. However, it is not available on Windows.