Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.
/lib/ -> setuplib.php (source)

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 and 403]

These functions are required very early in the Moodle setup process, before any of the main libraries are loaded.

Copyright: 1999 onwards Martin Dougiamas {@link http://moodle.com}
License: http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
File Size: 2185 lines (81 kb)
Included or required:0 times
Referenced: 0 times
Includes or requires: 0 files

Defines 12 classes

moodle_exception:: (1 method):
  __construct()

require_login_exception:: (1 method):
  __construct()

require_login_session_timeout_exception:: (1 method):
  __construct()

webservice_parameter_exception:: (1 method):
  __construct()

required_capability_exception:: (1 method):
  __construct()

coding_exception:: (1 method):
  __construct()

invalid_parameter_exception:: (1 method):
  __construct()

invalid_response_exception:: (1 method):
  __construct()

invalid_state_exception:: (1 method):
  __construct()

invalid_dataroot_permissions:: (1 method):
  __construct()

file_serving_exception:: (41 methods):
  __construct()
  default_exception_handler()
  default_error_handler()
  abort_all_db_transactions()
  is_early_init()
  get_exception_info()
  generate_uuid()
  get_docs_url()
  format_backtrace()
  ini_get_bool()
  setup_validate_php_configuration()
  initialise_cfg()
  initialise_local_config_cache()
  hash_local_config_cache()
  initialise_fullme()
  initialise_fullme_cli()
  setup_get_remote_url()
  workaround_max_input_vars()
  merge_query_params()
  init_performance_info()
  during_initial_install()
  raise_memory_limit()
  reduce_memory_limit()
  get_real_size()
  disable_output_buffering()
  is_major_upgrade_required()
  redirect_if_major_upgrade_required()
  upgrade_ensure_not_running()
  check_dir_exists()
  make_unique_writable_directory()
  make_writable_directory()
  protect_directory()
  make_upload_directory()
  get_request_storage_directory()
  make_request_directory()
  get_backup_temp_directory()
  make_backup_temp_directory()
  make_temp_directory()
  make_cache_directory()
  make_localcache_directory()
  set_access_log_user()

bootstrap_renderer:: (9 methods):
  has_started()
  __call()
  early_error_content()
  early_error()
  early_notification()
  plain_redirect_message()
  early_redirect_message()
  plain_page()
  proxy_log_callback()


Class: moodle_exception  - X-Ref

Base Moodle Exception class

Although this class is defined here, you cannot throw a moodle_exception until
after moodlelib.php has been included (which will happen very soon).

__construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null)   X-Ref
Constructor

param: string $errorcode The name of the string from error.php to print
param: string $module name of module
param: string $link The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
param: mixed $a Extra words and phrases that might be required in the error string
param: string $debuginfo optional debugging information

Class: require_login_exception  - X-Ref

Course/activity access exception.

This exception is thrown from require_login()

__construct($debuginfo)   X-Ref
Constructor

param: string $debuginfo Information to aid the debugging process

Class: require_login_session_timeout_exception  - X-Ref

Session timeout exception.

This exception is thrown from require_login()

__construct()   X-Ref
Constructor


Class: webservice_parameter_exception  - X-Ref

Web service parameter exception class

__construct($errorcode=null, $a = '', $debuginfo = null)   X-Ref
Constructor

param: string $errorcode The name of the string from webservice.php to print
param: string $a The name of the parameter
param: string $debuginfo Optional information to aid debugging

Class: required_capability_exception  - X-Ref

Exceptions indicating user does not have permissions to do something
and the execution can not continue.

__construct($context, $capability, $errormessage, $stringfile)   X-Ref
Constructor

param: context $context The context used for the capability check
param: string $capability The required capability
param: string $errormessage The error message to show the user
param: string $stringfile

Class: coding_exception  - X-Ref

Exception indicating programming error, must be fixed by a programer. For example
a core API might throw this type of exception if a plugin calls it incorrectly.

__construct($hint, $debuginfo=null)   X-Ref
Constructor

param: string $hint short description of problem
param: string $debuginfo detailed information how to fix problem

Class: invalid_parameter_exception  - X-Ref

Exception indicating malformed parameter problem.
This exception is not supposed to be thrown when processing
user submitted data in forms. It is more suitable
for WS and other low level stuff.

__construct($debuginfo=null)   X-Ref
Constructor

param: string $debuginfo some detailed information

Class: invalid_response_exception  - X-Ref

Exception indicating malformed response problem.
This exception is not supposed to be thrown when processing
user submitted data in forms. It is more suitable
for WS and other low level stuff.

__construct($debuginfo=null)   X-Ref
Constructor

param: string $debuginfo some detailed information

Class: invalid_state_exception  - X-Ref

An exception that indicates something really weird happened. For example,
if you do switch ($context->contextlevel), and have one case for each
CONTEXT_... constant. You might throw an invalid_state_exception in the
default case, to just in case something really weird is going on, and
$context->contextlevel is invalid - rather than ignoring this possibility.

__construct($hint, $debuginfo=null)   X-Ref
Constructor

param: string $hint short description of problem
param: string $debuginfo optional more detailed information

Class: invalid_dataroot_permissions  - X-Ref

An exception that indicates incorrect permissions in $CFG->dataroot

__construct($debuginfo = NULL)   X-Ref
Constructor

param: string $debuginfo optional more detailed information

Class: file_serving_exception  - X-Ref

An exception that indicates that file can not be served

__construct($debuginfo = NULL)   X-Ref
Constructor

param: string $debuginfo optional more detailed information

default_exception_handler($ex)   X-Ref
Default exception handler.

param: Exception $ex
return: void -does not return. Terminates execution!

default_error_handler($errno, $errstr, $errfile, $errline)   X-Ref
Default error handler, prevents some white screens.

param: int $errno
param: string $errstr
param: string $errfile
param: int $errline
return: bool false means use default error handler

abort_all_db_transactions()   X-Ref
Unconditionally abort all database transactions, this function
should be called from exception handlers only.

return: void

is_early_init($backtrace)   X-Ref
This function encapsulates the tests for whether an exception was thrown in
early init -- either during setup.php or during init of $OUTPUT.

If another exception is thrown then, and if we do not take special measures,
we would just get a very cryptic message "Exception thrown without a stack
frame in Unknown on line 0". That makes debugging very hard, so we do take
special measures in default_exception_handler, with the help of this function.

param: array $backtrace the stack trace to analyse.
return: boolean whether the stack trace is somewhere in output initialisation.

get_exception_info($ex)   X-Ref
Returns detailed information about specified exception.

param: Throwable $ex any sort of exception or throwable.
return: stdClass standardised info to display. Fields are clear if you look at the end of this function.

generate_uuid()   X-Ref


get_docs_url($path = null)   X-Ref
Returns the Moodle Docs URL in the users language for a given 'More help' link.

There are three cases:

1. In the normal case, $path will be a short relative path 'component/thing',
like 'mod/folder/view' 'group/import'. This gets turned into an link to
MoodleDocs in the user's language, and for the appropriate Moodle version.
E.g. 'group/import' may become 'http://docs.moodle.org/2x/en/group/import'.
The 'http://docs.moodle.org' bit comes from $CFG->docroot.

This is the only option that should be used in standard Moodle code. The other
two options have been implemented because they are useful for third-party plugins.

2. $path may be an absolute URL, starting http:// or https://. In this case,
the link is used as is.

3. $path may start %%WWWROOT%%, in which case that is replaced by
$CFG->wwwroot to make the link.

param: string $path the place to link to. See above for details.
return: string The MoodleDocs URL in the user's language. for example @link http://docs.moodle.org/2x/en/$path}

format_backtrace($callers, $plaintext = false)   X-Ref
Formats a backtrace ready for output.

This function does not include function arguments because they could contain sensitive information
not suitable to be exposed in a response.

param: array $callers backtrace array, as returned by debug_backtrace().
param: boolean $plaintext if false, generates HTML, if true generates plain text.
return: string formatted backtrace, ready for output.

ini_get_bool($ini_get_arg)   X-Ref
This function makes the return value of ini_get consistent if you are
setting server directives through the .htaccess file in apache.

Current behavior for value set from php.ini On = 1, Off = [blank]
Current behavior for value set from .htaccess On = On, Off = Off
Contributed by jdell @ unr.edu

param: string $ini_get_arg The argument to get
return: bool True for on false for not

setup_validate_php_configuration()   X-Ref
This function verifies the sanity of PHP configuration
and stops execution if anything critical found.


initialise_cfg()   X-Ref
Initialise global $CFG variable.


initialise_local_config_cache()   X-Ref
Cache any immutable config locally to avoid constant DB lookups.

Only to be used only from lib/setup.php

hash_local_config_cache()   X-Ref
Calculate a proper hash to be able to invalidate stale cached configs.

Only to be used to verify bootstrap.php status.

return: string md5 hash of all the sensible bits deciding if cached config is stale or no.

initialise_fullme()   X-Ref
Initialises $FULLME and friends. Private function. Should only be called from
setup.php.


initialise_fullme_cli()   X-Ref
Initialises $FULLME and friends for command line scripts.
This is a private method for use by initialise_fullme.


setup_get_remote_url()   X-Ref
Get the URL that PHP/the web server thinks it is serving. Private function
used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.

return: array in the same format that parse_url returns, with the addition of

workaround_max_input_vars()   X-Ref
Try to work around the 'max_input_vars' restriction if necessary.


merge_query_params(array &$target, array $values)   X-Ref
Merge parsed POST chunks.

NOTE: this is not perfect, but it should work in most cases hopefully.

param: array $target
param: array $values

init_performance_info()   X-Ref
Initializes our performance info early.

Pairs up with get_performance_info() which is actually
in moodlelib.php. This function is here so that we can
call it before all the libs are pulled in.


during_initial_install()   X-Ref
Indicates whether we are in the middle of the initial Moodle install.

Very occasionally it is necessary avoid running certain bits of code before the
Moodle installation has completed. The installed flag is set in admin/index.php
after Moodle core and all the plugins have been installed, but just before
the person doing the initial install is asked to choose the admin password.

return: boolean true if the initial install is not complete.

raise_memory_limit($newlimit)   X-Ref
Function to raise the memory limit to a new value.
Will respect the memory limit if it is higher, thus allowing
settings in php.ini, apache conf or command line switches
to override it.

The memory limit should be expressed with a constant
MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
It is possible to use strings or integers too (eg:'128M').

param: mixed $newlimit the new memory limit
return: bool success

reduce_memory_limit($newlimit)   X-Ref
Function to reduce the memory limit to a new value.
Will respect the memory limit if it is lower, thus allowing
settings in php.ini, apache conf or command line switches
to override it

The memory limit should be expressed with a string (eg:'64M')

param: string $newlimit the new memory limit
return: bool

get_real_size($size = 0)   X-Ref
Converts numbers like 10M into bytes.

param: string $size The size to be converted
return: int

disable_output_buffering()   X-Ref
Try to disable all output buffering and purge
all headers.

return: void

is_major_upgrade_required()   X-Ref
Check whether a major upgrade is needed.

That is defined as an upgrade that changes something really fundamental
in the database, so nothing can possibly work until the database has
been updated, and that is defined by the hard-coded version number in
this function.

return: bool

redirect_if_major_upgrade_required()   X-Ref
Redirect to the Notifications page if a major upgrade is required, and
terminate the current user session.


upgrade_ensure_not_running($warningonly = false)   X-Ref
Makes sure that upgrade process is not running

To be inserted in the core functions that can not be called by pluigns during upgrade.
Core upgrade should not use any API functions at all.
See {@link https://moodledev.io/docs/guides/upgrade#upgrade-code-restrictions}

param: bool $warningonly if true displays a warning instead of throwing an exception
return: bool true if executed from outside of upgrade process, false if from inside upgrade process and function is used for warning only

check_dir_exists($dir, $create = true, $recursive = true)   X-Ref
Function to check if a directory exists and by default create it if not exists.

Previously this was accepting paths only from dataroot, but we now allow
files outside of dataroot if you supply custom paths for some settings in config.php.
This function does not verify that the directory is writable.

NOTE: this function uses current file stat cache,
please use clearstatcache() before this if you expect that the
directories may have been removed recently from a different request.

param: string $dir absolute directory path
param: boolean $create directory if does not exist
param: boolean $recursive create directory recursively
return: boolean true if directory exists or created, false otherwise

make_unique_writable_directory($basedir, $exceptiononerror = true)   X-Ref
Create a new unique directory within the specified directory.

param: string $basedir The directory to create your new unique directory within.
param: bool $exceptiononerror throw exception if error encountered
return: string The created directory

make_writable_directory($dir, $exceptiononerror = true)   X-Ref
Create a directory and make sure it is writable.

param: string $dir  the full path of the directory to be created
param: bool $exceptiononerror throw exception if error encountered
return: string|false Returns full path to directory if successful, false if not; may throw exception

protect_directory($dir)   X-Ref
Protect a directory from web access.
Could be extended in the future to support other mechanisms (e.g. other webservers).

param: string $dir  the full path of the directory to be protected

make_upload_directory($directory, $exceptiononerror = true)   X-Ref
Create a directory under dataroot and make sure it is writable.
Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().

param: string $directory  the full path of the directory to be created under $CFG->dataroot
param: bool $exceptiononerror throw exception if error encountered
return: string|false Returns full path to directory if successful, false if not; may throw exception

get_request_storage_directory($exceptiononerror = true, bool $forcecreate = false)   X-Ref
Get a per-request storage directory in the tempdir.

The directory is automatically cleaned up during the shutdown handler.

param: bool    $exceptiononerror throw exception if error encountered
param: bool    $forcecreate Force creation of a new parent directory
return: string  Returns full path to directory if successful, false if not; may throw exception

make_request_directory(bool $exceptiononerror = true, bool $forcecreate = false)   X-Ref
Create a per-request directory and make sure it is writable.
This can only be used during the current request and will be tidied away
automatically afterwards.

A new, unique directory is always created within a shared base request directory.

In some exceptional cases an alternative base directory may be required. This can be accomplished using the
$forcecreate parameter. Typically this will only be requried where the file may be required during a shutdown handler
which may or may not be registered after a previous request directory has been created.

param: bool    $exceptiononerror throw exception if error encountered
param: bool    $forcecreate Force creation of a new parent directory
return: string  The full path to directory if successful, false if not; may throw exception

get_backup_temp_directory($directory)   X-Ref
Get the full path of a directory under $CFG->backuptempdir.

param: string $directory  the relative path of the directory under $CFG->backuptempdir
return: string|false Returns full path to directory given a valid string; otherwise, false.

make_backup_temp_directory($directory, $exceptiononerror = true)   X-Ref
Create a directory under $CFG->backuptempdir and make sure it is writable.

Do not use for storing generic temp files - see make_temp_directory() instead for this purpose.

Backup temporary files must be on a shared storage.

param: string $directory  the relative path of the directory to be created under $CFG->backuptempdir
param: bool $exceptiononerror throw exception if error encountered
return: string|false Returns full path to directory if successful, false if not; may throw exception

make_temp_directory($directory, $exceptiononerror = true)   X-Ref
Create a directory under tempdir and make sure it is writable.

Where possible, please use make_request_directory() and limit the scope
of your data to the current HTTP request.

Do not use for storing cache files - see make_cache_directory(), and
make_localcache_directory() instead for this purpose.

Temporary files must be on a shared storage, and heavy usage is
discouraged due to the performance impact upon clustered environments.

param: string $directory  the full path of the directory to be created under $CFG->tempdir
param: bool $exceptiononerror throw exception if error encountered
return: string|false Returns full path to directory if successful, false if not; may throw exception

make_cache_directory($directory, $exceptiononerror = true)   X-Ref
Create a directory under cachedir and make sure it is writable.

Note: this cache directory is shared by all cluster nodes.

param: string $directory  the full path of the directory to be created under $CFG->cachedir
param: bool $exceptiononerror throw exception if error encountered
return: string|false Returns full path to directory if successful, false if not; may throw exception

make_localcache_directory($directory, $exceptiononerror = true)   X-Ref
Create a directory under localcachedir and make sure it is writable.
The files in this directory MUST NOT change, use revisions or content hashes to
work around this limitation - this means you can only add new files here.

The content of this directory gets purged automatically on all cluster nodes
after calling purge_all_caches() before new data is written to this directory.

Note: this local cache directory does not need to be shared by cluster nodes.

param: string $directory the relative path of the directory to be created under $CFG->localcachedir
param: bool $exceptiononerror throw exception if error encountered
return: string|false Returns full path to directory if successful, false if not; may throw exception

set_access_log_user()   X-Ref
Webserver access user logging


Class: bootstrap_renderer  - X-Ref

This class solves the problem of how to initialise $OUTPUT.

The problem is caused be two factors
<ol>
<li>On the one hand, we cannot be sure when output will start. In particular,
an error, which needs to be displayed, could be thrown at any time.</li>
<li>On the other hand, we cannot be sure when we will have all the information
necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
(potentially) depends on the current course, course categories, and logged in user.
It also depends on whether the current page requires HTTPS.</li>
</ol>

So, it is hard to find a single natural place during Moodle script execution,
which we can guarantee is the right time to initialise $OUTPUT. Instead we
adopt the following strategy
<ol>
<li>We will initialise $OUTPUT the first time it is used.</li>
<li>If, after $OUTPUT has been initialised, the script tries to change something
that $OUTPUT depends on, we throw an exception making it clear that the script
did something wrong.
</ol>

The only problem with that is, how do we initialise $OUTPUT on first use if,
it is going to be used like $OUTPUT->somthing(...)? Well that is where this
class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
when any method is called on that object, we initialise $OUTPUT, and pass the call on.

Note that this class is used before lib/outputlib.php has been loaded, so we
must be careful referring to classes/functions from there, they may not be
defined yet, and we must avoid fatal errors.

has_started()   X-Ref
Have we started output yet?

return: boolean true if the header has been printed.

__call($method, $arguments)   X-Ref
Constructor - to be used by core code only.

param: string $method The method to call
param: array $arguments Arguments to pass to the method being called
return: string

early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null)   X-Ref
Returns nicely formatted error message in a div box.

param: string $message error message
param: string $moreinfourl (ignored in early errors)
param: string $link (ignored in early errors)
param: array $backtrace
param: string $debuginfo
return: string

early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = null)   X-Ref
This function should only be called by this class, or from exception handlers

param: string $message error message
param: string $moreinfourl (ignored in early errors)
param: string $link (ignored in early errors)
param: array $backtrace
param: string $debuginfo extra information for developers
return: string

early_notification($message, $classes = 'notifyproblem')   X-Ref
Early notification message

param: string $message
param: string $classes usually notifyproblem or notifysuccess
return: string

plain_redirect_message($encodedurl)   X-Ref
Page should redirect message.

param: string $encodedurl redirect url
return: string

early_redirect_message($encodedurl, $message, $delay)   X-Ref
Early redirection page, used before full init of $PAGE global

param: string $encodedurl redirect url
param: string $message redirect message
param: int $delay time in seconds
return: string redirect page

plain_page($title, $content, $meta = '')   X-Ref
Output basic html page.

param: string $title page title
param: string $content page content
param: string $meta meta tag
return: string html page

proxy_log_callback($code)   X-Ref
Add http stream instrumentation

This detects which any reads or writes to a php stream which uses
the 'http' handler. Ideally 100% of traffic uses the Moodle curl
libraries which do not use php streams.

param: array $code stream callback code