Differences Between: [Versions 310 and 400] [Versions 311 and 400] [Versions 39 and 400] [Versions 400 and 401] [Versions 400 and 402] [Versions 400 and 403]
moodlelib.php - Moodle main library Main library file of miscellaneous general-purpose Moodle functions. Other main libraries: - weblib.php - functions that produce web output - datalib.php - functions that access the database
Copyright: | 1999 onwards Martin Dougiamas http://dougiamas.com |
License: | http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later |
File Size: | 10840 lines (393 kb) |
Included or required: | 0 times |
Referenced: | 0 times |
Includes or requires: | 0 files |
emoticon_manager:: (69 methods):
get_emoticons()
prepare_renderable_emoticon()
encode_stored_config()
decode_stored_config()
default_emoticons()
prepare_emoticon_object()
rc4encrypt()
rc4decrypt()
endecrypt()
is_valid_plugin_name()
get_plugin_list_with_function()
get_plugins_with_function()
get_list_of_plugins()
plugin_callback()
component_callback()
component_callback_exists()
component_class_callback()
plugin_supports()
check_php_version()
moodle_needs_upgrading()
moodle_major_version()
moodle_getlocale()
moodle_setlocale()
count_words()
count_letters()
random_string()
complex_random_string()
random_bytes_emulate()
shorten_text()
shorten_filename()
shorten_filenames()
getweek()
generate_password()
format_float()
unformat_float()
swapshuffle()
swapshuffle_assoc()
draw_rand_array()
microtime_diff()
make_menu_from_list()
make_grades_menu()
make_unique_id_code()
address_in_subnet()
mtrace()
mtrace_exception()
cleardoubleslashes()
remoteip_in_list()
getremoteaddr()
cleanremoteaddr()
ip_is_public()
fullclone()
bounded_number()
array_is_nested()
get_performance_info()
rename_to_unused_name()
remove_dir()
object_property_exists()
convert_to_array()
custom_script_path()
is_mnet_remote_user()
setup_lang_from_browser()
is_proxybypass()
is_newnav()
in_object_vars()
object_array_unique()
is_primary_admin()
get_site_identifier()
check_consecutive_identical_characters()
partial()
partial:: (11 methods):
__construct()
method()
get_mnet_environment()
get_mnet_remote_client()
set_mnet_remote_client()
mnet_get_idp_jump_url()
get_home_page()
get_default_home_page()
get_course_display_name_for_list()
unserialize_array()
unserialize_object()
lang_string:: (10 methods):
__construct()
get_string()
out()
__toString()
__set_state()
__sleep()
get_identifier()
get_component()
get_callable_name()
site_is_public()
Class: emoticon_manager - X-Ref
Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).get_emoticons($selectable = false) X-Ref |
Returns the currently enabled emoticons return: array of emoticon objects param: boolean $selectable - If true, only return emoticons that should be selectable from a list. |
prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array() X-Ref |
Converts emoticon object into renderable pix_emoticon object return: pix_emoticon param: stdClass $emoticon emoticon object param: array $attributes explicit HTML attributes to set |
encode_stored_config(array $emoticons) X-Ref |
Encodes the array of emoticon objects into a string storable in config table return: string param: array $emoticons array of emtocion objects |
decode_stored_config($encoded) X-Ref |
Decodes the string into an array of emoticon objects return: string|null param: string $encoded |
default_emoticons() X-Ref |
Returns default set of emoticons supported by Moodle return: array of sdtClasses |
prepare_emoticon_object($text, $imagename, $altidentifier = null,$altcomponent = 'core_pix', $imagecomponent = 'core') X-Ref |
Helper method preparing the stdClass with the emoticon properties return: stdClass param: string|array $text or array of strings param: string $imagename to be used by {@link pix_emoticon} param: string $altidentifier alternative string identifier, null for no alt param: string $altcomponent where the alternative string is defined param: string $imagecomponent to be used by {@link pix_emoticon} |
rc4encrypt($data) X-Ref |
rc4encrypt return: string The now encrypted data. param: string $data Data to encrypt. |
rc4decrypt($data) X-Ref |
rc4decrypt return: string The now decrypted data. param: string $data Data to decrypt. |
endecrypt($pwd, $data, $case) X-Ref |
Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com] return: string param: string $pwd The password to use when encrypting or decrypting param: string $data The data to be decrypted/encrypted param: string $case Either 'de' for decrypt or '' for encrypt |
is_valid_plugin_name($name) X-Ref |
This method validates a plug name. It is much faster than calling clean_param. return: bool if this string is a valid plugin name. param: string $name a string that might be a plugin name. |
get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') X-Ref |
Get a list of all the plugins of a given type that define a certain API function in a certain file. The plugin component names and function names are returned. return: array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum') param: string $plugintype the type of plugin, e.g. 'mod' or 'report'. param: string $function the part of the name of the function after the param: string $file the name of file within the plugin that defines the |
get_plugins_with_function($function, $file = 'lib.php', $include = true) X-Ref |
Get a list of all the plugins that define a certain API function in a certain file. return: array with [plugintype][plugin] = functionname param: string $function the part of the name of the function after the param: string $file the name of file within the plugin that defines the param: bool $include Whether to include the files that contain the functions or not. |
get_list_of_plugins($directory='mod', $exclude='', $basedir='') X-Ref |
Lists plugin-like directories within specified directory This function was originally used for standard Moodle plugins, please use new core_component::get_plugin_list() now. This function is used for general directory listing and backwards compatility. return: array Sorted array of directory names found under the requested parameters param: string $directory relative directory from root param: string $exclude dir name to exclude from the list (defaults to none) param: string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot) |
plugin_callback($type, $name, $feature, $action, $params = null, $default = null) X-Ref |
Invoke plugin's callback functions return: mixed param: string $type plugin type e.g. 'mod' param: string $name plugin name param: string $feature feature name param: string $action feature's action param: array $params parameters of callback function, should be an array param: mixed $default default value if callback function hasn't been defined, or if it retursn null. |
component_callback($component, $function, array $params = array() X-Ref |
Invoke component's callback functions return: mixed param: string $component frankenstyle component name, e.g. 'mod_quiz' param: string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron' param: array $params parameters of callback function param: mixed $default default value if callback function hasn't been defined, or if it retursn null. |
component_callback_exists($component, $function) X-Ref |
Determine if a component callback exists and return the function name to call. Note that this function will include the required library files so that the functioname returned can be called directly. return: mixed Complete function name to call if the callback exists or false if it doesn't. param: string $component frankenstyle component name, e.g. 'mod_quiz' param: string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron' |
component_class_callback($classname, $methodname, array $params, $default = null) X-Ref |
Call the specified callback method on the provided class. If the callback returns null, then the default value is returned instead. If the class does not exist, then the default value is returned. return: mixed The return value. param: string $classname The name of the class to call upon. param: string $methodname The name of the staticically defined method on the class. param: array $params The arguments to pass into the method. param: mixed $default The default value. |
plugin_supports($type, $name, $feature, $default = null) X-Ref |
Checks whether a plugin supports a specified feature. return: mixed Feature result (false if not supported, null if feature is unknown, param: string $type Plugin type e.g. 'mod' param: string $name Plugin name e.g. 'forum' param: string $feature Feature code (FEATURE_xx constant) param: mixed $default default value if feature support unknown |
check_php_version($version='5.2.4') X-Ref |
Returns true if the current version of PHP is greater that the specified one. return: bool param: string $version The version of php being tested. |
moodle_needs_upgrading() X-Ref |
Determine if moodle installation requires update. Checks version numbers of main code and all plugins to see if there are any mismatches. return: bool |
moodle_major_version($fromdisk = false) X-Ref |
Returns the major version of this site Moodle version numbers consist of three numbers separated by a dot, for example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so called major version. This function extracts the major version from either $CFG->release (default) or eventually from the $release variable defined in the main version.php. return: string|false the major version like '2.3', false if could not be determined param: bool $fromdisk should the version if source code files be used |
moodle_getlocale() X-Ref |
Gets the system locale return: string Retuns the current locale. |
moodle_setlocale($locale='') X-Ref |
Sets the system locale param: string $locale Can be used to force a locale |
count_words($string) X-Ref |
Count words in a string. Words are defined as things between whitespace. return: int The count of words in the specified string param: string $string The text to be searched for words. May be HTML. |
count_letters($string) X-Ref |
Count letters in a string. Letters are defined as chars not in tags and different from whitespace. return: int The count of letters in the specified text. param: string $string The text to be searched for letters. May be HTML. |
random_string($length=15) X-Ref |
Generate and return a random string of the specified length. return: string param: int $length The length of the string to be created. |
complex_random_string($length=null) X-Ref |
Generate a complex random string (useful for md5 salts) This function is based on the above {@link random_string()} however it uses a larger pool of characters and generates a string between 24 and 32 characters return: string param: int $length Optional if set generates a string to exactly this length |
random_bytes_emulate($length) X-Ref |
Try to generates cryptographically secure pseudo-random bytes. Note this is achieved by fallbacking between: - PHP 7 random_bytes(). - OpenSSL openssl_random_pseudo_bytes(). - In house random generator getting its entropy from various, hard to guess, pseudo-random sources. return: string binary data param: int $length requested length in bytes |
shorten_text($text, $ideal=30, $exact = false, $ending='...') X-Ref |
Given some text (which may contain HTML) and an ideal length, this function truncates the text neatly on a word boundary if possible return: string $truncate shortened string param: string $text text to be shortened param: int $ideal ideal string length param: boolean $exact if false, $text will not be cut mid-word param: string $ending The string to append if the passed string is truncated |
shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) X-Ref |
Shortens a given filename by removing characters positioned after the ideal string length. When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size. Limiting the filename to a certain size (considering multibyte characters) will prevent this. return: string $shortened shortened file name param: string $filename file name param: int $length ideal string length param: bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness. |
shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) X-Ref |
Shortens a given array of filenames by removing characters positioned after the ideal string length. return: array $result Shortened paths in array. param: array $path The paths to reduce the length. param: int $length Ideal string length param: bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness. |
getweek($startdate, $thedate) X-Ref |
Given dates in seconds, how many weeks is the date from startdate The first week is 1, the second 2 etc ... return: string param: int $startdate Timestamp for the start date param: int $thedate Timestamp for the end date |
generate_password($maxlen=10) X-Ref |
Returns a randomly generated password of length $maxlen. inspired by {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254} return: string param: int $maxlen The maximum size of the password being generated. |
format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) X-Ref |
Given a float, prints it nicely. Localized floats must not be used in calculations! The stripzeros feature is intended for making numbers look nicer in small areas where it is not necessary to indicate the degree of accuracy by showing ending zeros. If you turn it on with $decimalpoints set to 3, for example, then it will display '5.4' instead of '5.400' or '5' instead of '5.000'. return: string locale float param: float $float The float to print param: int $decimalpoints The number of decimal places to print. -1 is a special value for auto detect (full precision). param: bool $localized use localized decimal separator param: bool $stripzeros If true, removes final zeros after decimal point. It will be ignored and the trailing zeros after |
unformat_float($localefloat, $strict = false) X-Ref |
Converts locale specific floating point/comma number back to standard PHP float value Do NOT try to do any math operations before this conversion on any user submitted floats! return: mixed float|bool - false or the parsed float. param: string $localefloat locale aware float representation param: bool $strict If true, then check the input and return false if it is not a valid number. |
swapshuffle($array) X-Ref |
Given a simple array, this shuffles it up just like shuffle() Unlike PHP's shuffle() this function works on any machine. return: array param: array $array The array to be rearranged |
swapshuffle_assoc($array) X-Ref |
Like {@link swapshuffle()}, but works on associative arrays return: array param: array $array The associative array to be rearranged |
draw_rand_array($array, $draws) X-Ref |
Given an arbitrary array, and a number of draws, this function returns an array with that amount of items. The indexes are retained. return: array param: array $array param: int $draws |
microtime_diff($a, $b) X-Ref |
Calculate the difference between two microtimes return: string param: string $a The first Microtime param: string $b The second Microtime |
make_menu_from_list($list, $separator=',') X-Ref |
Given a list (eg a,b,c,d,e) this function returns an array of 1->a, 2->b, 3->c etc return: array The now assembled array param: string $list The string to explode into array bits param: string $separator The separator used within the list string |
make_grades_menu($gradingtype) X-Ref |
Creates an array that represents all the current grades that can be chosen using the given grading type. Negative numbers are scales, zero is no grade, and positive numbers are maximum grades. return: array param: int $gradingtype |
make_unique_id_code($extra = '') X-Ref |
make_unique_id_code return: string param: string $extra Extra string to append to the end of the code |
address_in_subnet($addr, $subnetstr, $checkallzeros = false) X-Ref |
Function to check the passed address is within the passed subnet The parameter is a comma separated string of subnet definitions. Subnet strings can be in one of three formats: 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask) 2: xxx.xxx.xxx.xxx-yyy or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy (a range of IP addresses in the last group) 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-) Code for type 1 modified from user posted comments by mediator at {@link http://au.php.net/manual/en/function.ip2long.php} return: bool param: string $addr The address you are checking param: string $subnetstr The string of subnet addresses param: bool $checkallzeros The state to whether check for 0.0.0.0 |
mtrace($string, $eol="\n", $sleep=0) X-Ref |
For outputting debugging info param: string $string The string to write param: string $eol The end of line char(s) to use param: string $sleep Period to make the application sleep |
mtrace_exception(Throwable $e) X-Ref |
Helper to {@see mtrace()} an exception or throwable, including all relevant information. param: Throwable $e the error to ouptput. |
cleardoubleslashes($path) X-Ref |
Replace 1 or more slashes or backslashes to 1 slash return: string the path with double slashes removed param: string $path The path to strip |
remoteip_in_list($list) X-Ref |
Is the current ip in a given list? return: bool param: string $list |
getremoteaddr($default='0.0.0.0') X-Ref |
Returns most reliable client address return: string The remote IP address param: string $default If an address can't be determined, then return this |
cleanremoteaddr($addr, $compress=false) X-Ref |
Cleans an ip address. Internal addresses are now allowed. (Originally local addresses were not allowed.) return: string normalised ip address string, null if error param: string $addr IPv4 or IPv6 address param: bool $compress use IPv6 address compression |
ip_is_public($ip) X-Ref |
Is IP address a public address? return: bool true if the ip is public param: string $ip The ip to check |
fullclone($thing) X-Ref |
This function will make a complete copy of anything it's given, regardless of whether it's an object or not. return: mixed What ever it is you passed it param: mixed $thing Something you want cloned |
bounded_number($min, $value, $max) X-Ref |
Used to make sure that $min <= $value <= $max Make sure that value is between min, and max return: int param: int $min The minimum value param: int $value The value to check param: int $max The maximum value |
array_is_nested($array) X-Ref |
Check if there is a nested array within the passed array return: bool true if there is a nested array false otherwise param: array $array |
get_performance_info() X-Ref |
get_performance_info() pairs up with init_performance_info() loaded in setup.php. Returns an array with 'html' and 'txt' values ready for use, and each of the individual stats provided separately as well. return: array |
rename_to_unused_name(string $filepath, string $prefix = '_temp_') X-Ref |
Renames a file or directory to a unique name within the same directory. This function is designed to avoid any potential race conditions, and select an unused name. return: string|bool New file path or false if failed param: string $filepath Original filepath param: string $prefix Prefix to use for the temporary name |
remove_dir($dir, $contentonly=false) X-Ref |
Delete directory or only its content return: bool success, true also if dir does not exist param: string $dir directory path param: bool $contentonly |
object_property_exists( $obj, $property ) X-Ref |
Detect if an object or a class contains a given property will take an actual object or the name of a class return: bool true if property exists param: mix $obj Name of class or real object to test param: string $property name of property to find |
convert_to_array($var) X-Ref |
Converts an object into an associative array This function converts an object into an associative array by iterating over its public properties. Because this function uses the foreach construct, Iterators are respected. It works recursively on arrays of objects. Arrays and simple values are returned as is. If class has magic properties, it can implement IteratorAggregate and return all available properties in getIterator() return: array param: mixed $var |
custom_script_path() X-Ref |
Detect a custom script replacement in the data directory that will replace an existing moodle script return: string|bool full path name if a custom script exists, false if no custom script exists |
is_mnet_remote_user($user) X-Ref |
Returns whether or not the user object is a remote MNET user. This function is in moodlelib because it does not rely on loading any of the MNET code. return: bool True if the user is from a remote Moodle. param: object $user A valid user object |
setup_lang_from_browser() X-Ref |
This function will search for browser prefereed languages, setting Moodle to use the best one available if $SESSION->lang is undefined |
is_proxybypass( $url ) X-Ref |
Check if $url matches anything in proxybypass list Any errors just result in the proxy being used (least bad) return: boolean true if we should bypass the proxy param: string $url url to check |
is_newnav($navigation) X-Ref |
Check if the passed navigation is of the new style return: bool true for yes false for no param: mixed $navigation |
in_object_vars($var, $object) X-Ref |
Checks whether the given variable name is defined as a variable within the given object. This will NOT work with stdClass objects, which have no class variables. return: boolean param: string $var The variable name param: object $object The object to check |
object_array_unique($array, $keepkeyassoc = true) X-Ref |
Returns an array without repeated objects. This function is similar to array_unique, but for arrays that have objects as values return: array param: array $array param: bool $keepkeyassoc |
is_primary_admin($userid) X-Ref |
Is a userid the primary administrator? return: boolean param: int $userid int id of user to check |
get_site_identifier() X-Ref |
Returns the site identifier return: string $CFG->siteidentifier, first making sure it is properly initialised. |
check_consecutive_identical_characters($password, $maxchars) X-Ref |
Check whether the given password has no more than the specified number of consecutive identical characters. return: bool param: string $password password to be checked against the password policy param: integer $maxchars maximum number of consecutive identical characters |
partial() X-Ref |
Helper function to do partial function binding. so we can use it for preg_replace_callback, for example this works with php functions, user functions, static methods and class methods it returns you a callback that you can pass on like so: $callback = partial('somefunction', $arg1, $arg2); or $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2); or even $obj = new someclass(); $callback = partial(array($obj, 'somemethod'), $arg1, $arg2); and then the arguments that are passed through at calltime are appended to the argument list. return: array Array callback param: mixed $function a php callback param: mixed $arg1,... $argv arguments to partially bind with |
__construct($func, $args) X-Ref |
Constructor param: string $func param: array $args |
method() X-Ref |
Calls the callback function. return: mixed |
get_mnet_environment() X-Ref |
helper function to load up and initialise the mnet environment this must be called before you use mnet functions. return: mnet_environment the equivalent of old $MNET global |
get_mnet_remote_client() X-Ref |
during xmlrpc server code execution, any code wishing to access information about the remote peer must use this to get it. return: mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global |
set_mnet_remote_client($client) X-Ref |
during the xmlrpc server code execution, this will be called to setup the object returned by {@link get_mnet_remote_client} param: mnet_remote_client $client the client to set up |
mnet_get_idp_jump_url($user) X-Ref |
return the jump url for a given remote user this is used for rewriting forum post links in emails, etc param: stdclass $user the user to get the idp url for |
get_home_page() X-Ref |
Gets the homepage to use for the current user return: int One of HOMEPAGE_* |
get_default_home_page() X-Ref |
Returns the default home page to display if current one is not defined or can't be applied. The default behaviour is to return Dashboard if it's enabled or My courses page if it isn't. return: int The default home page. |
get_course_display_name_for_list($course) X-Ref |
Gets the name of a course to be displayed when showing a list of courses. By default this is just $course->fullname but user can configure it. The result of this function should be passed through print_string. return: string Display name of course (either fullname or short + fullname) param: stdClass|core_course_list_element $course Moodle course object |
unserialize_array($expression) X-Ref |
Safe analogue of unserialize() that can only parse arrays Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed. return: array|bool either parsed array or false if parsing was impossible. param: string $expression |
unserialize_object(string $input) X-Ref |
Safe method for unserializing given input that is expected to contain only a serialized instance of an stdClass object If any class type other than stdClass is included in the input string, it will not be instantiated and will be cast to an stdClass object. The initial cast to array, then back to object is to ensure we are always returning the correct type, otherwise we would return an instances of {@see __PHP_Incomplete_class} for malformed strings return: stdClass param: string $input |
Class: lang_string - X-Ref
The lang_string class__construct($identifier, $component = '', $a = null, $lang = null) X-Ref |
Constructs a lang_string object This function should do as little processing as possible to ensure the best performance for strings that won't be used. param: string $identifier The strings identifier param: string $component The strings component param: stdClass|array $a Any arguments the string requires param: string $lang The language to use when processing the string. |
get_string() X-Ref |
Processes the string. This function actually processes the string, stores it in the string property and then returns it. You will notice that this function is VERY similar to the get_string method. That is because it is pretty much doing the same thing. However as this function is an upgrade it isn't as tolerant to backwards compatibility. return: string |
out($lang = null) X-Ref |
Returns the string return: string param: string $lang The langauge to use when processing the string |
__toString() X-Ref |
Magic __toString method for printing a string return: string |
__set_state(array $array) X-Ref |
Magic __set_state method used for var_export return: self param: array $array |
__sleep() X-Ref |
Prepares the lang_string for sleep and stores only the forcedstring and string properties... the string cannot be regenerated so we need to ensure it is generated for this. return: string |
get_identifier() X-Ref |
Returns the identifier. return: string |
get_component() X-Ref |
Returns the component. return: string |
get_callable_name($callable) X-Ref |
Get human readable name describing the given callable. This performs syntax check only to see if the given param looks like a valid function, method or closure. It does not check if the callable actually exists. return: string|bool Human readable name of callable, or false if not a valid callable. param: callable|string|array $callable |
site_is_public() X-Ref |
Tries to guess if $CFG->wwwroot is publicly accessible or not. Never put your faith on this function and rely on its accuracy as there might be false positives. It just performs some simple checks, and mainly is used for places where we want to hide some options such as site registration when $CFG->wwwroot is not publicly accessible. Good thing is there is no false negative. Note that it's possible to force the result of this check by specifying $CFG->site_is_public in config.php return: bool |
required_param($parname, $type) X-Ref |
Returns a particular value for the named variable, taken from POST or GET. If the parameter doesn't exist then an error is thrown because we require this variable. This function should be used to initialise all required values in a script that are based on parameters. Usually it will be used like this: $id = required_param('id', PARAM_INT); Please note the $type parameter is now required and the value can not be array. return: mixed param: string $parname the name of the page parameter we want param: string $type expected type of parameter |
required_param_array($parname, $type) X-Ref |
Returns a particular array value for the named variable, taken from POST or GET. If the parameter doesn't exist then an error is thrown because we require this variable. This function should be used to initialise all required values in a script that are based on parameters. Usually it will be used like this: $ids = required_param_array('ids', PARAM_INT); Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported return: array param: string $parname the name of the page parameter we want param: string $type expected type of parameter |
optional_param($parname, $default, $type) X-Ref |
Returns a particular value for the named variable, taken from POST or GET, otherwise returning a given default. This function should be used to initialise all optional values in a script that are based on parameters. Usually it will be used like this: $name = optional_param('name', 'Fred', PARAM_TEXT); Please note the $type parameter is now required and the value can not be array. return: mixed param: string $parname the name of the page parameter we want param: mixed $default the default value to return if nothing is found param: string $type expected type of parameter |
optional_param_array($parname, $default, $type) X-Ref |
Returns a particular array value for the named variable, taken from POST or GET, otherwise returning a given default. This function should be used to initialise all optional values in a script that are based on parameters. Usually it will be used like this: $ids = optional_param('id', array(), PARAM_INT); Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported return: array param: string $parname the name of the page parameter we want param: mixed $default the default value to return if nothing is found param: string $type expected type of parameter |
validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') X-Ref |
Strict validation of parameter values, the values are only converted to requested PHP type. Internally it is using clean_param, the values before and after cleaning must be equal - otherwise an invalid_parameter_exception is thrown. Objects and classes are not accepted. return: mixed the $param value converted to PHP type param: mixed $param param: string $type PARAM_ constant param: bool $allownull are nulls valid value? param: string $debuginfo optional debug information |
clean_param_array(?array $param, $type, $recursive = false) X-Ref |
Makes sure array contains only the allowed types, this function does not validate array key names! <code> $options = clean_param($options, PARAM_INT); </code> return: array param: array|null $param the variable array we are cleaning param: string $type expected format of param after cleaning. param: bool $recursive clean recursive arrays |
clean_param($param, $type) X-Ref |
Used by {@link optional_param()} and {@link required_param()} to clean the variables and/or cast to specific types, based on an options field. <code> $course->format = clean_param($course->format, PARAM_ALPHA); $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT); </code> return: mixed param: mixed $param the variable we are cleaning param: string $type expected format of param after cleaning. |
is_rtl_compatible($paramtype) X-Ref |
Whether the PARAM_* type is compatible in RTL. Being compatible with RTL means that the data they contain can flow from right-to-left or left-to-right without compromising the user experience. Take URLs for example, they are not RTL compatible as they should always flow from the left to the right. This also applies to numbers, email addresses, configuration snippets, base64 strings, etc... This function tries to best guess which parameters can contain localised strings. return: bool param: string $paramtype Constant PARAM_*. |
fix_utf8($value) X-Ref |
Makes sure the data is using valid utf8, invalid characters are discarded. Note: this function is not intended for full objects with methods and private properties. return: mixed with proper utf-8 encoding param: mixed $value |
is_number($value) X-Ref |
Return true if given value is integer or string with integer value return: bool true if number, false if not param: mixed $value String or Int |
get_host_from_url($url) X-Ref |
Returns host part from url. return: string host, null if not found param: string $url full url |
html_is_blank($string) X-Ref |
Tests whether anything was returned by text editor This function is useful for testing whether something you got back from the HTML editor actually contains anything. Sometimes the HTML editor appear to be empty, but actually you get back a <br> tag or something. return: boolean does the string contain any actual content - that is text, param: string $string a string containing HTML. |
set_config($name, $value, $plugin=null) X-Ref |
Set a key in global configuration Set a key/value pair in both this session's {@link $CFG} global variable and in the 'config' database table for future sessions. Can also be used to update keys for plugin-scoped configs in config_plugin table. In that case it doesn't affect $CFG. A NULL value will delete the entry. NOTE: this function is called from lib/db/upgrade.php return: bool true or exception param: string $name the key to set param: string $value the value to set (without magic quotes) param: string $plugin (optional) the plugin scope, default null |
get_config($plugin, $name = null) X-Ref |
Get configuration values from the global config table or the config_plugins table. If called with one parameter, it will load all the config variables for one plugin, and return them as an object. If called with 2 parameters it will return a string single value or false if the value is not found. NOTE: this function is called from lib/db/upgrade.php return: mixed hash-like object or single value, return false no config found param: string $plugin full component name param: string $name default null |
unset_config($name, $plugin=null) X-Ref |
Removes a key from global configuration. NOTE: this function is called from lib/db/upgrade.php return: boolean whether the operation succeeded. param: string $name the key to set param: string $plugin (optional) the plugin scope |
unset_all_config_for_plugin($plugin) X-Ref |
Remove all the config variables for a given plugin. NOTE: this function is called from lib/db/upgrade.php return: boolean whether the operation succeeded. param: string $plugin a plugin, for example 'quiz' or 'qtype_multichoice'; |
get_users_from_config($value, $capability, $includeadmins = true) X-Ref |
Use this function to get a list of users from a config setting of type admin_setting_users_with_capability. All users are verified if they still have the necessary capability. return: array of user objects. param: string $value the value of the config setting. param: string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor. param: bool $includeadmins include administrators. |
purge_all_caches() X-Ref |
Invalidates browser caches and cached data in temp. return: void |
purge_caches($options = []) X-Ref |
Selectively invalidate different types of cache. Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific areas alone or in combination. param: bool[] $options Specific parts of the cache to purge. Valid options are: |
purge_other_caches() X-Ref |
Purge all non-MUC caches not otherwise purged in purge_caches. IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at {@link phpunit_util::reset_dataroot()} |
get_cache_flags($type, $changedsince = null) X-Ref |
Get volatile flags return: array records array param: string $type param: int $changedsince default null |
get_cache_flag($type, $name, $changedsince=null) X-Ref |
Get volatile flags return: string|false The cache flag value or false param: string $type param: string $name param: int $changedsince default null |
set_cache_flag($type, $name, $value, $expiry = null) X-Ref |
Set a volatile flag return: bool Always returns true param: string $type the "type" namespace for the key param: string $name the key to set param: string $value the value to set (without magic quotes) - null will remove the flag param: int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs |
unset_cache_flag($type, $name) X-Ref |
Removes a single volatile flag return: bool param: string $type the "type" namespace for the key param: string $name the key to set |
gc_cache_flags() X-Ref |
Garbage-collect volatile flags return: bool Always returns true |
check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) X-Ref |
Refresh user preference cache. This is used most often for $USER object that is stored in session, but it also helps with performance in cron script. Preferences for each user are loaded on first use on every page, then again after the timeout expires. return: null param: stdClass $user User object. Preferences are preloaded into 'preference' property param: int $cachelifetime Cache life time on the current page (in seconds) |
mark_user_preferences_changed($userid) X-Ref |
Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions. NOTE: internal function, do not call from other code. param: integer $userid the user whose prefs were changed. |
set_user_preference($name, $value, $user = null) X-Ref |
Sets a preference for the specified user. If a $user object is submitted it's 'preference' property is used for the preferences cache. When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()} return: bool Always true or exception param: string $name The key to set as preference for the specified user param: string $value The value to set for the $name key in the specified user's param: stdClass|int|null $user A moodle user object or id, null means current user |
set_user_preferences(array $prefarray, $user = null) X-Ref |
Sets a whole array of preferences for the current user If a $user object is submitted it's 'preference' property is used for the preferences cache. return: bool Always true or exception param: array $prefarray An array of key/value pairs to be set param: stdClass|int|null $user A moodle user object or id, null means current user |
unset_user_preference($name, $user = null) X-Ref |
Unsets a preference completely by deleting it from the database If a $user object is submitted it's 'preference' property is used for the preferences cache. return: bool Always true or exception param: string $name The key to unset as preference for the specified user param: stdClass|int|null $user A moodle user object or id, null means current user |
get_user_preferences($name = null, $default = null, $user = null) X-Ref |
Used to fetch user preference(s) If no arguments are supplied this function will return all of the current user preferences as an array. If a name is specified then this function attempts to return that particular preference value. If none is found, then the optional value $default is returned, otherwise null. If a $user object is submitted it's 'preference' property is used for the preferences cache. return: string|mixed|null A string containing the value of a single preference. An param: string $name Name of the key to use in finding a preference value param: mixed|null $default Value to be returned if the $name key is not set in the user preferences param: stdClass|int|null $user A moodle user object or id, null means current user |
make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) X-Ref |
Given Gregorian date parts in user time produce a GMT timestamp. return: int GMT timestamp param: int $year The year part to create timestamp of param: int $month The month part to create timestamp of param: int $day The day part to create timestamp of param: int $hour The hour part to create timestamp of param: int $minute The minute part to create timestamp of param: int $second The second part to create timestamp of param: int|float|string $timezone Timezone modifier, used to calculate GMT time offset. param: bool $applydst Toggle Daylight Saving Time, default true, will be |
format_time($totalsecs, $str = null) X-Ref |
Format a date/time (seconds) as weeks, days, hours etc as needed Given an amount of time in seconds, returns string formatted nicely as years, days, hours etc as needed return: string A nicely formatted date/time string param: int $totalsecs Time in seconds param: stdClass $str Should be a time object |
userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) X-Ref |
Returns a formatted string that represents a date in user time. return: string the formatted date/time. param: int $date the timestamp in UTC, as obtained from the database. param: string $format strftime format. You should probably get this using param: int|float|string $timezone by default, uses the user's time zone. if numeric and param: bool $fixday If true (default) then the leading zero from %d is removed. param: bool $fixhour If true (default) then the leading zero from %I is removed. |
userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) X-Ref |
Returns a html "time" tag with both the exact user date with timezone information as a datetime attribute in the W3C format, and the user readable date and time as text. return: string the formatted date/time. param: int $date the timestamp in UTC, as obtained from the database. param: string $format strftime format. You should probably get this using param: int|float|string $timezone by default, uses the user's time zone. if numeric and param: bool $fixday If true (default) then the leading zero from %d is removed. param: bool $fixhour If true (default) then the leading zero from %I is removed. |
date_format_string($date, $format, $tz = 99) X-Ref |
Returns a formatted date ensuring it is UTF-8. If we are running under Windows convert to Windows encoding and then back to UTF-8 (because it's impossible to specify UTF-8 to fetch locale info in Win32). return: string the formatted date/time. param: int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp param: string $format strftime format. param: int|float|string $tz the user timezone |
usergetdate($time, $timezone=99) X-Ref |
Given a $time timestamp in GMT (seconds since epoch), returns an array that represents the Gregorian date in user time return: array An array that represents the date in user time param: int $time Timestamp in GMT param: float|int|string $timezone user timezone |
usertime($date, $timezone=99) X-Ref |
Given a GMT timestamp (seconds since epoch), offsets it by the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds NOTE: this function does not include DST properly, you should use the PHP date stuff instead! return: int param: int $date Timestamp in GMT param: float|int|string $timezone user timezone |
get_time_interval_string(int $time1, int $time2, string $format = '') X-Ref |
Get a formatted string representation of an interval between two unix timestamps. E.g. $intervalstring = get_time_interval_string(12345600, 12345660); Will produce the string: '0d 0h 1m' return: string the formatted string describing the time difference, e.g. '10d 11h 45m'. param: int $time1 unix timestamp param: int $time2 unix timestamp param: string $format string (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php. |
usergetmidnight($date, $timezone=99) X-Ref |
Given a time, return the GMT timestamp of the most recent midnight for the current user. return: int Returns a GMT timestamp param: int $date Timestamp in GMT param: float|int|string $timezone user timezone |
usertimezone($timezone=99) X-Ref |
Returns a string that prints the user's timezone return: string param: float|int|string $timezone user timezone |
get_user_timezone($tz = 99) X-Ref |
Returns a float or a string which denotes the user's timezone A float value means that a simple offset from GMT is used, while a string (it will be the name of a timezone in the database) means that for this timezone there are also DST rules to be taken into account Checks various settings and picks the most dominant of those which have a value return: float|string param: float|int|string $tz timezone to calculate GMT time offset before |
dst_offset_on($time, $strtimezone = null) X-Ref |
Calculates the Daylight Saving Offset for a given date/time (timestamp) - Note: Daylight saving only works for string timezones and not for float. return: int param: int $time must NOT be compensated at all, it has to be a pure timestamp param: int|float|string $strtimezone user timezone |
find_day_in_month($startday, $weekday, $month, $year) X-Ref |
Calculates when the day appears in specific month return: int param: int $startday starting day of the month param: int $weekday The day when week starts (normally taken from user preferences) param: int $month The month whose day is sought param: int $year The year of the month whose day is sought |
days_in_month($month, $year) X-Ref |
Calculate the number of days in a given month return: int param: int $month The month whose day count is sought param: int $year The year of the month whose day count is sought |
dayofweek($day, $month, $year) X-Ref |
Calculate the position in the week of a specific calendar day return: int param: int $day The day of the date whose position in the week is sought param: int $month The month of the date whose position in the week is sought param: int $year The year of the date whose position in the week is sought |
get_login_url() X-Ref |
Returns full login url. Any form submissions for authentication to this URL must include username, password as well as a logintoken generated by \core\session\manager::get_login_token(). return: string login url |
require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) X-Ref |
This function checks that the current user is logged in and has the required privileges This function checks that the current user is logged in, and optionally whether they are allowed to be in a particular course and view a particular course module. If they are not logged in, then it redirects them to the site login unless $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which case they are automatically logged in as guests. If $courseid is given and the user is not enrolled in that course then the user is redirected to the course enrolment page. If $cm is given and the course module is hidden and the user is not a teacher in the course then the user is redirected to the course home page. When $cm parameter specified, this function sets page layout to 'module'. You need to change it manually later if some other layout needed. return: mixed Void, exit, and die depending on path param: mixed $courseorid id of the course or course object param: bool $autologinguest default true param: object $cm course module object param: bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to param: bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions |
require_admin() X-Ref |
A convenience function for where we must be logged in as admin return: void |
require_logout() X-Ref |
This function just makes sure a user is logged out. |
require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) X-Ref |
Weaker version of require_login() This is a weaker version of {@link require_login()} which only requires login when called from within a course rather than the site page, unless the forcelogin option is turned on. return: void param: mixed $courseorid The course object or id in question param: bool $autologinguest Allow autologin guests if that is wanted param: object $cm Course activity module if known param: bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to param: bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions |
validate_user_key($keyvalue, $script, $instance) X-Ref |
Validates a user key, checking if the key exists, is not expired and the remote ip is correct. return: stdClass the key entry in the user_private_key table param: string $keyvalue the key value param: string $script unique script identifier param: int $instance instance id |
require_user_key_login($script, $instance = null, $keyvalue = null) X-Ref |
Require key login. Function terminates with error if key not found or incorrect. return: int Instance ID param: string $script unique script identifier param: int $instance optional instance id param: string $keyvalue The key. If not supplied, this will be fetched from the current session. |
create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) X-Ref |
Creates a new private user access key. return: string access key value param: string $script unique target identifier param: int $userid param: int $instance optional instance id param: string $iprestriction optional ip restricted access param: int $validuntil key valid only until given data |
delete_user_key($script, $userid) X-Ref |
Delete the user's new private user access keys for a particular script. return: void param: string $script unique target identifier param: int $userid |
get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) X-Ref |
Gets a private user access key (and creates one if one doesn't exist). return: string access key value param: string $script unique target identifier param: int $userid param: int $instance optional instance id param: string $iprestriction optional ip restricted access param: int $validuntil key valid only until given date |
update_user_login_times() X-Ref |
Modify the user table by setting the currently logged in user's last login to now. return: bool Always returns true |
user_not_fully_set_up($user, $strict = true) X-Ref |
Determines if a user has completed setting up their account. The lax mode (with $strict = false) has been introduced for special cases only where we want to skip certain checks intentionally. This is valid in certain mnet or ajax scenarios when the user cannot / should not be redirected to edit their profile. In most cases, you should perform the strict check. return: bool param: stdClass $user A {@link $USER} object to test for the existence of a valid name and email param: bool $strict Be more strict and assert id and custom profile fields set, too |
over_bounce_threshold($user) X-Ref |
Check whether the user has exceeded the bounce threshold return: bool true => User has exceeded bounce threshold param: stdClass $user A {@link $USER} object |
set_send_count($user, $reset=false) X-Ref |
Used to increment or reset email sent count return: void param: stdClass $user object containing an id param: bool $reset will reset the count to 0 |
set_bounce_count($user, $reset=false) X-Ref |
Increment or reset user's email bounce count param: stdClass $user object containing an id param: bool $reset will reset the count to 0 |
ismoving($courseid) X-Ref |
Determines if the logged in user is currently moving an activity return: bool param: int $courseid The id of the course being tested |
fullname($user, $override=false) X-Ref |
Returns a persons full name Given an object containing all of the users name values, this function returns a string with the full name of the person. The result may depend on system settings or language. 'override' will force the alternativefullnameformat to be used. In English, fullname as well as alternativefullnameformat is set to 'firstname lastname' by default. But you could have fullname set to 'firstname lastname' and alternativefullnameformat set to 'firstname middlename alternatename lastname'. return: string param: stdClass $user A {@link $USER} object to get full name of. param: bool $override If true then the alternativefullnameformat format rather than fullnamedisplay format will be used. |
username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) X-Ref |
Reduces lines of duplicated code for getting user name fields. See also {@link user_picture::unalias()} return: object User name fields. param: object $addtoobject Object to add user name fields to. param: object $secondobject Object that contains user name field information. param: string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname. param: array $additionalfields Additional fields to be matched with data in the second object. |
order_in_string($values, $stringformat) X-Ref |
Returns an array of values in order of occurance in a provided string. The key in the result is the character postion in the string. return: array An array of values in order according to placement in the string format. param: array $values Values to be found in the string format param: string $stringformat The string which may contain values being searched for. |
exists_auth_plugin($auth) X-Ref |
Returns whether a given authentication plugin exists. return: boolean Whether the plugin is available. param: string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}. |
is_enabled_auth($auth) X-Ref |
Checks if a given plugin is in the list of enabled authentication plugins. return: boolean Whether the plugin is enabled. param: string $auth Authentication plugin. |
get_auth_plugin($auth) X-Ref |
Returns an authentication plugin instance. return: auth_plugin_base An instance of the required authentication plugin. param: string $auth name of authentication plugin |
get_enabled_auth_plugins($fix=false) X-Ref |
Returns array of active auth plugins. return: array param: bool $fix fix $CFG->auth if needed. Only set if logged in as admin. |
is_internal_auth($auth) X-Ref |
Returns true if an internal authentication method is being used. if method not specified then, global default is assumed return: bool param: string $auth Form of authentication required |
is_restored_user($username) X-Ref |
Returns true if the user is a 'restored' one. Used in the login process to inform the user and allow him/her to reset the password return: bool param: string $username username to be checked |
get_user_fieldnames() X-Ref |
Returns an array of user fields return: array User field/column names |
get_newuser_language() X-Ref |
Returns the string of the language for the new user. return: string language for the new user |
create_user_record($username, $password, $auth = 'manual') X-Ref |
Creates a bare-bones user record return: stdClass A complete user object param: string $username New user's username to add to record param: string $password New user's password to add to record param: string $auth Form of authentication required |
update_user_record($username) X-Ref |
Will update a local user record from an external source (MNET users can not be updated using this method!). return: stdClass A complete user object param: string $username user's username to update the record |
update_user_record_by_id($id) X-Ref |
Will update a local user record from an external source (MNET users can not be updated using this method!). return: stdClass A complete user object param: int $id user id |
truncate_userinfo(array $info) X-Ref |
Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields. return: array The now truncated information that was passed in param: array $info Array of user properties to truncate if needed |
delete_user(stdClass $user) X-Ref |
Marks user deleted in internal user database and notifies the auth plugin. Also unenrols user from all roles and does other cleanup. Any plugin that needs to purge user data should register the 'user_deleted' event. return: boolean success param: stdClass $user full user object before delete |
guest_user() X-Ref |
Retrieve the guest user object. return: stdClass A {@link $USER} object |
authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null, $logintoken=false) X-Ref |
Authenticates a user against the chosen authentication mechanism Given a username and password, this function looks them up using the currently selected authentication mechanism, and if the authentication is successful, it returns a valid $user object from the 'user' table. Uses auth_ functions from the currently active auth module After authenticate_user_login() returns success, you will need to log that the user has logged in, and call complete_user_login() to set the session up. Note: this function works only with non-mnet accounts! return: stdClass|false A {@link $USER} object or false if error param: string $username User's username (or also email if $CFG->authloginviaemail enabled) param: string $password User's password param: bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO param: int $failurereason login failure reason, can be used in renderers (it may disclose if account exists) param: mixed logintoken If this is set to a string it is validated against the login token for the session. |
complete_user_login($user) X-Ref |
Call to complete the user login process after authenticate_user_login() has succeeded. It will setup the $USER variable and other required bits and pieces. NOTE: - It will NOT log anything -- up to the caller to decide what to log. - this function does not set any cookies any more! return: stdClass A {@link $USER} object - BC only, do not use param: stdClass $user |
password_is_legacy_hash($password) X-Ref |
Check a password hash to see if it was hashed using the legacy hash algorithm (md5). return: boolean True if the $password matches the format of an md5 sum. param: string $password String to check. |
validate_internal_user_password($user, $password) X-Ref |
Compare password against hash stored in user object to determine if it is valid. If necessary it also updates the stored hash to the current format. return: bool True if password is valid. param: stdClass $user (Password property may be updated). param: string $password Plain text password. |
hash_internal_user_password($password, $fasthash = false) X-Ref |
Calculate hash for a plain text password. return: string The hashed password. param: string $password Plain text password to be hashed. param: bool $fasthash If true, use a low cost factor when generating the hash |
update_internal_user_password($user, $password, $fasthash = false) X-Ref |
Update password hash in user object (if necessary). The password is updated if: 1. The password has changed (the hash of $user->password is different to the hash of $password). 2. The existing hash is using an out-of-date algorithm (or the legacy md5 algorithm). Updating the password will modify the $user object and the database record to use the current hashing algorithm. It will remove Web Services user tokens too. return: bool Always returns true. param: stdClass $user User object (password property may be updated). param: string $password Plain text password. param: bool $fasthash If true, use a low cost factor when generating the hash |
get_complete_user_data($field, $value, $mnethostid = null, $throwexception = false) X-Ref |
Get a complete user record, which includes all the info in the user record. Intended for setting as $USER session variable return: mixed False, or A {@link $USER} object. param: string $field The user field to be checked for a given value. param: string $value The value to match for $field. param: int $mnethostid param: bool $throwexception If true, it will throw an exception when there's no record found or when there are multiple records |
check_password_policy($password, &$errmsg, $user = null) X-Ref |
Validate a password against the configured password policy return: bool true if the password is valid according to the policy. false otherwise. param: string $password the password to be checked against the password policy param: string $errmsg the error message to display when the password doesn't comply with the policy. param: stdClass $user the user object to perform password validation against. Defaults to null if not provided. |
set_login_session_preferences() X-Ref |
When logging in, this function is run to set certain preferences for the current SESSION. |
delete_course($courseorid, $showfeedback = true) X-Ref |
Delete a course, including all related data from the database, and any associated files. return: bool true if all the removals succeeded. false if there were any failures. If this param: mixed $courseorid The id of the course or course object to delete. param: bool $showfeedback Whether to display notifications of each action the function performs. |
remove_course_contents($courseid, $showfeedback = true, array $options = null) X-Ref |
Clear a course out completely, deleting all content but don't delete the course itself. This function does not verify any permissions. Please note this function also deletes all user enrolments, enrolment instances and role assignments by default. $options: - 'keep_roles_and_enrolments' - false by default - 'keep_groups_and_groupings' - false by default return: bool true if all the removals succeeded. false if there were any failures. If this param: int $courseid The id of the course that is being deleted param: bool $showfeedback Whether to display notifications of each action the function performs. param: array $options extra options |
shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) X-Ref |
Change dates in module - used from course reset. return: bool success param: string $modname forum, assignment, etc param: array $fields array of date fields from mod table param: int $timeshift time difference param: int $courseid param: int $modid (Optional) passed if specific mod instance in course needs to be updated. |
reset_course_userdata($data) X-Ref |
This function will empty a course of user data. It will retain the activities and the structure of the course. return: array status array of array component, item, error param: object $data an object containing all the settings including courseid (without magic quotes) |
generate_email_processing_address($modid, $modargs) X-Ref |
Generate an email processing address. return: string Returns email processing address param: int $modid param: string $modargs |
moodle_process_email($modargs, $body) X-Ref |
? param: string $modargs param: string $body Currently unused |
get_mailer($action='get') X-Ref |
Get mailer instance, enable buffering, flush buffer or disable buffering. return: moodle_phpmailer|null mailer instance if 'get' used or nothing param: string $action 'get', 'buffer', 'close' or 'flush' |
email_should_be_diverted($email) X-Ref |
A helper function to test for email diversion return: bool Returns true if the email should be diverted param: string $email |
generate_email_messageid($localpart = null) X-Ref |
Generate a unique email Message-ID using the moodle domain and install path return: string The formatted ID ready for appending to the email headers. param: string $localpart An optional unique message id prefix. |
email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',$usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) X-Ref |
Send an email to a specified user return: bool Returns true if mail was sent OK and false if there was an error. param: stdClass $user A {@link $USER} object param: stdClass $from A {@link $USER} object param: string $subject plain text subject line of the email param: string $messagetext plain text version of the message param: string $messagehtml complete html version of the message (optional) param: string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in one of param: string $attachname the name of the file (extension indicates MIME) param: bool $usetrueaddress determines whether $from email address should param: string $replyto Email address to reply to param: string $replytoname Name of reply to recipient param: int $wordwrapwidth custom word wrap width, default 79 |
can_send_from_real_email_address($from, $user, $unused = null) X-Ref |
Check to see if a user's real email address should be used for the "From" field. return: bool Returns true if we can use the from user's email adress in the "From" field. param: object $from The user object for the user we are sending the email from. param: object $user The user object that we are sending the email to. param: array $unused No longer used. |
generate_email_signoff() X-Ref |
Generate a signoff for emails based on support settings return: string |
setnew_password_and_mail($user, $fasthash = false) X-Ref |
Sets specified user's password and send the new password to the user via email. return: bool|string Returns "true" if mail was sent OK and "false" if there was an error param: stdClass $user A {@link $USER} object param: bool $fasthash If true, use a low cost factor when generating the hash for speed. |
reset_password_and_mail($user) X-Ref |
Resets specified user's password and send the new password to the user via email. return: bool Returns true if mail was sent OK and false if there was an error. param: stdClass $user A {@link $USER} object |
send_confirmation_email($user, $confirmationurl = null) X-Ref |
Send email to specified user with confirmation text and activation link. return: bool Returns true if mail was sent OK and false if there was an error. param: stdClass $user A {@link $USER} object param: string $confirmationurl user confirmation URL |
send_password_change_confirmation_email($user, $resetrecord) X-Ref |
Sends a password change confirmation email. return: bool Returns true if mail was sent OK and false if there was an error. param: stdClass $user A {@link $USER} object param: stdClass $resetrecord An object tracking metadata regarding password reset request |
send_password_change_info($user) X-Ref |
Sends an email containing information on how to change your password. return: bool Returns true if mail was sent OK and false if there was an error. param: stdClass $user A {@link $USER} object |
email_is_not_allowed($email) X-Ref |
Check that an email is allowed. It returns an error message if there was a problem. return: string|false param: string $email Content of email |
get_file_storage($reset = false) X-Ref |
Returns local file storage instance return: file_storage |
get_file_browser() X-Ref |
Returns local file storage instance return: file_browser |
get_file_packer($mimetype='application/zip') X-Ref |
Returns file packer return: file_packer param: string $mimetype default application/zip |
valid_uploaded_file($newfile) X-Ref |
Returns current name of file on disk if it exists. return: string Current name of file on disk if true param: string $newfile File to be verified |
get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) X-Ref |
Returns the maximum size for uploading files. There are seven possible upload limits: 1. in Apache using LimitRequestBody (no way of checking or changing this) 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP) 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP) 4. in php.ini for 'post_max_size' (can not be changed inside PHP) 5. by the Moodle admin in $CFG->maxbytes 6. by the teacher in the current course $course->maxbytes 7. by the teacher for the current module, eg $assignment->maxbytes These last two are passed to this function as arguments (in bytes). Anything defined as 0 is ignored. The smallest of all the non-zero numbers is returned. return: int The maximum size for uploading files. param: int $sitebytes Set maximum size param: int $coursebytes Current course $course->maxbytes (in bytes) param: int $modulebytes Current module ->maxbytes (in bytes) param: bool $unused This parameter has been deprecated and is not used any more. |
get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,$unused = false) X-Ref |
Returns the maximum size for uploading files for the current user This function takes in account {@link get_max_upload_file_size()} the user's capabilities return: int The maximum size for uploading files. param: context $context The context in which to check user capabilities param: int $sitebytes Set maximum size param: int $coursebytes Current course $course->maxbytes (in bytes) param: int $modulebytes Current module ->maxbytes (in bytes) param: stdClass $user The user param: bool $unused This parameter has been deprecated and is not used any more. |
get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) X-Ref |
Returns an array of possible sizes in local language Related to {@link get_max_upload_file_size()} - this function returns an array of possible sizes in an array, translated to the local language. The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes. If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)" with the value set to 0. This option will be the first in the list. return: array param: int $sitebytes Set maximum size param: int $coursebytes Current course $course->maxbytes (in bytes) param: int $modulebytes Current module ->maxbytes (in bytes) param: int|array $custombytes custom upload size/s which will be added to list, |
get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) X-Ref |
Returns an array with all the filenames in all subdirectories, relative to the given rootdir. If excludefiles is defined, then that file/directory is ignored If getdirs is true, then (sub)directories are included in the output If getfiles is true, then files are included in the output (at least one of these must be true!) return: array An array with all the filenames in all subdirectories, relative to the given rootdir param: string $rootdir A given root directory to start from param: string|array $excludefiles If defined then the specified file/directory is ignored param: bool $descend If true then subdirectories are recursed as well param: bool $getdirs If true then (sub)directories are included in the output param: bool $getfiles If true then files are included in the output |
get_directory_size($rootdir, $excludefile='') X-Ref |
Adds up all the files in a directory and works out the size. return: int The summed size of all files and subfiles within the root directory param: string $rootdir The directory to start from param: string $excludefile A file to exclude when summing directory size |
display_size($size, int $decimalplaces = 1, string $fixedunits = '') X-Ref |
Converts bytes into display form return: string Display version of size param: int $size The size to convert to human readable form param: int $decimalplaces If specified, uses fixed number of decimal places param: string $fixedunits If specified, uses fixed units (e.g. 'KB') |
clean_filename($string) X-Ref |
Cleans a given filename by removing suspicious or troublesome characters return: string cleaned file name param: string $string file name |
current_language() X-Ref |
Returns the code for the current language return: string |
fix_current_language(string $lang) X-Ref |
Fix the current language to the given language code. return: void param: string $lang The language code to use. |
get_parent_language($lang=null) X-Ref |
Returns parent language of current active language if defined return: string param: string $lang null means current language |
force_current_language($language) X-Ref |
Force the current language to get strings and dates localised in the given language. After calling this function, all strings will be provided in the given language until this function is called again, or equivalent code is run. return: string previous $SESSION->forcelang value param: string $language |
get_string_manager($forcereload=false) X-Ref |
Returns current string_manager instance. The param $forcereload is needed for CLI installer only where the string_manager instance must be replaced during the install.php script life time. return: core_string_manager param: bool $forcereload shall the singleton be released and new instance created instead? |
get_string($identifier, $component = '', $a = null, $lazyload = false) X-Ref |
Returns a localized string. Returns the translated string specified by $identifier as for $module. Uses the same format files as STphp. $a is an object, string or number that can be used within translation strings eg 'hello {$a->firstname} {$a->lastname}' or 'hello {$a}' If you would like to directly echo the localized string use the function {@link print_string()} Example usage of this function involves finding the string you would like a local equivalent of and using its identifier and module information to retrieve it.<br/> If you open moodle/lang/en/moodle.php and look near line 278 you will find a string to prompt a user for their word for 'course' <code> $string['course'] = 'Course'; </code> So if you want to display the string 'Course' in any language that supports it on your site you just need to use the identifier 'course' <code> $mystring = '<strong>'. get_string('course') .'</strong>'; or </code> If the string you want is in another file you'd take a slightly different approach. Looking in moodle/lang/en/calendar.php you find around line 75: <code> $string['typecourse'] = 'Course event'; </code> If you want to display the string "Course event" in any language supported you would use the identifier 'typecourse' and the module 'calendar' (because it is in the file calendar.php): <code> $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>'; </code> As a last resort, should the identifier fail to map to a string the returned string will be [[ $identifier ]] In Moodle 2.3 there is a new argument to this function $lazyload. Setting $lazyload to true causes get_string to return a lang_string object rather than the string itself. The fetching of the string is then put off until the string object is first used. The object can be used by calling it's out method or by casting the object to a string, either directly e.g. (string)$stringobject or indirectly by using the string within another string or echoing it out e.g. echo $stringobject return "<p>{$stringobject}</p>"; It is worth noting that using $lazyload and attempting to use the string as an array key will cause a fatal error as objects cannot be used as array keys. But you should never do that anyway! For more information {@link lang_string} return: string The localized string. param: string $identifier The key identifier for the localized string param: string $component The module where the key identifier is stored, param: string|object|array $a An object, string or number that can be used param: bool $lazyload If set to true a string object is returned instead of |
get_strings($array, $component = '') X-Ref |
Converts an array of strings to their localized value. return: stdClass translated strings. param: array $array An array of strings param: string $component The language module that these strings can be found in. |
print_string($identifier, $component = '', $a = null) X-Ref |
Prints out a translated string. Prints out a translated string using the return value from the {@link get_string()} function. Example usage of this function when the string is in the moodle.php file:<br/> <code> echo '<strong>'; print_string('course'); echo '</strong>'; </code> Example usage of this function when the string is not in the moodle.php file:<br/> <code> echo '<h1>'; print_string('typecourse', 'calendar'); echo '</h1>'; </code> param: string $identifier The key identifier for the localized string param: string $component The module where the key identifier is stored. If none is specified then moodle.php is used. param: string|object|array $a An object, string or number that can be used within translation strings |
get_list_of_charsets() X-Ref |
Returns a list of charset codes Returns a list of charset codes. It's hardcoded, so they should be added manually (checking that such charset is supported by the texlib library!) return: array And associative array with contents in the form of charset => charset |
get_list_of_themes() X-Ref |
Returns a list of valid and compatible themes return: array |
get_emoticon_manager() X-Ref |
Factory function for emoticon_manager return: emoticon_manager singleton |