See Release Notes
Long Term Support Release
Differences Between: [Versions 39 and 310] [Versions 39 and 311] [Versions 39 and 400] [Versions 39 and 401] [Versions 39 and 402] [Versions 39 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: | 10678 lines (387 kb) |
Included or required: | 0 times |
Referenced: | 0 times |
Includes or requires: | 0 files |
emoticon_manager:: (67 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()
cleardoubleslashes()
remoteip_in_list()
getremoteaddr()
cleanremoteaddr()
ip_is_public()
fullclone()
bounded_number()
array_is_nested()
get_performance_info()
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:: (10 methods):
__construct()
method()
get_mnet_environment()
get_mnet_remote_client()
set_mnet_remote_client()
mnet_get_idp_jump_url()
get_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 param: boolean $selectable - If true, only return emoticons that should be selectable from a list. return: array of emoticon objects |
prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array() X-Ref |
Converts emoticon object into renderable pix_emoticon object param: stdClass $emoticon emoticon object param: array $attributes explicit HTML attributes to set return: pix_emoticon |
encode_stored_config(array $emoticons) X-Ref |
Encodes the array of emoticon objects into a string storable in config table param: array $emoticons array of emtocion objects return: string |
decode_stored_config($encoded) X-Ref |
Decodes the string into an array of emoticon objects param: string $encoded return: string|null |
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 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} return: stdClass |
rc4encrypt($data) X-Ref |
rc4encrypt param: string $data Data to encrypt. return: string The now encrypted data. |
rc4decrypt($data) X-Ref |
rc4decrypt param: string $data Data to decrypt. return: string The now decrypted data. |
endecrypt($pwd, $data, $case) X-Ref |
Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com] 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 return: string |
is_valid_plugin_name($name) X-Ref |
This method validates a plug name. It is much faster than calling clean_param. param: string $name a string that might be a plugin name. return: bool if this string is a valid 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. 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 return: array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum') |
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. 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. return: array with [plugintype][plugin] = functionname |
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. 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) return: array Sorted array of directory names found under the requested parameters |
plugin_callback($type, $name, $feature, $action, $params = null, $default = null) X-Ref |
Invoke plugin's callback functions 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. return: mixed |
component_callback($component, $function, array $params = array() X-Ref |
Invoke component's callback functions 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. return: mixed |
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. 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' return: mixed Complete function name to call if the callback exists or false if it doesn't. |
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. 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. return: mixed The return value. |
plugin_supports($type, $name, $feature, $default = null) X-Ref |
Checks whether a plugin supports a specified feature. 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 return: mixed Feature result (false if not supported, null if feature is unknown, |
check_php_version($version='5.2.4') X-Ref |
Returns true if the current version of PHP is greater that the specified one. param: string $version The version of php being tested. return: bool |
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. param: bool $fromdisk should the version if source code files be used return: string|false the major version like '2.3', false if could not be determined |
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. param: string $string The text to be searched for words. May be HTML. return: int The count of words in the specified string |
count_letters($string) X-Ref |
Count letters in a string. Letters are defined as chars not in tags and different from whitespace. param: string $string The text to be searched for letters. May be HTML. return: int The count of letters in the specified text. |
random_string($length=15) X-Ref |
Generate and return a random string of the specified length. param: int $length The length of the string to be created. return: string |
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 param: int $length Optional if set generates a string to exactly this length return: string |
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. param: int $length requested length in bytes return: string binary data |
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 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 return: string $truncate shortened string |
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. 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. return: string $shortened shortened file name |
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. 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. return: array $result Shortened paths in array. |
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 ... param: int $startdate Timestamp for the start date param: int $thedate Timestamp for the end date return: string |
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} param: int $maxlen The maximum size of the password being generated. return: string |
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'. 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 return: string locale float |
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! 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. return: mixed float|bool - false or the parsed float. |
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. param: array $array The array to be rearranged return: array |
swapshuffle_assoc($array) X-Ref |
Like {@link swapshuffle()}, but works on associative arrays param: array $array The associative array to be rearranged return: array |
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. param: array $array param: int $draws return: array |
microtime_diff($a, $b) X-Ref |
Calculate the difference between two microtimes param: string $a The first Microtime param: string $b The second Microtime return: string |
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 param: string $list The string to explode into array bits param: string $separator The separator used within the list string return: array The now assembled array |
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. param: int $gradingtype return: array |
make_unique_id_code($extra = '') X-Ref |
make_unique_id_code param: string $extra Extra string to append to the end of the code return: string |
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} 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 return: bool |
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 |
cleardoubleslashes($path) X-Ref |
Replace 1 or more slashes or backslashes to 1 slash param: string $path The path to strip return: string the path with double slashes removed |
remoteip_in_list($list) X-Ref |
Is the current ip in a given list? param: string $list return: bool |
getremoteaddr($default='0.0.0.0') X-Ref |
Returns most reliable client address param: string $default If an address can't be determined, then return this return: string The remote IP address |
cleanremoteaddr($addr, $compress=false) X-Ref |
Cleans an ip address. Internal addresses are now allowed. (Originally local addresses were not allowed.) param: string $addr IPv4 or IPv6 address param: bool $compress use IPv6 address compression return: string normalised ip address string, null if error |
ip_is_public($ip) X-Ref |
Is IP address a public address? param: string $ip The ip to check return: bool true if the ip is public |
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. param: mixed $thing Something you want cloned return: mixed What ever it is you passed it |
bounded_number($min, $value, $max) X-Ref |
Used to make sure that $min <= $value <= $max Make sure that value is between min, and max param: int $min The minimum value param: int $value The value to check param: int $max The maximum value return: int |
array_is_nested($array) X-Ref |
Check if there is a nested array within the passed array param: array $array return: bool true if there is a nested array false otherwise |
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 |
remove_dir($dir, $contentonly=false) X-Ref |
Delete directory or only its content param: string $dir directory path param: bool $contentonly return: bool success, true also if dir does not exist |
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 param: mix $obj Name of class or real object to test param: string $property name of property to find return: bool true if property exists |
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() param: mixed $var return: array |
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. param: object $user A valid user object return: bool True if the user is from a remote Moodle. |
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) param: string $url url to check return: boolean true if we should bypass the proxy |
is_newnav($navigation) X-Ref |
Check if the passed navigation is of the new style param: mixed $navigation return: bool true for yes false for no |
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. param: string $var The variable name param: object $object The object to check return: boolean |
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 param: array $array param: bool $keepkeyassoc return: array |
is_primary_admin($userid) X-Ref |
Is a userid the primary administrator? param: int $userid int id of user to check return: boolean |
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. param: string $password password to be checked against the password policy param: integer $maxchars maximum number of consecutive identical characters return: bool |
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. param: mixed $function a php callback param: mixed $arg1,... $argv arguments to partially bind with return: array Array callback |
__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_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. param: stdClass|core_course_list_element $course Moodle course object return: string Display name of course (either fullname or short + fullname) |
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. param: string $expression return: array|bool either parsed array or false if parsing was impossible. |
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 param: string $input return: stdClass |
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 param: string $lang The langauge to use when processing the string return: string |
__toString() X-Ref |
Magic __toString method for printing a string return: string |
__set_state() X-Ref |
Magic __set_state method used for var_export return: string |
__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. param: callable|string|array $callable return: string|bool Human readable name of callable, or false if not a valid 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. param: string $parname the name of the page parameter we want param: string $type expected type of parameter return: mixed |
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 param: string $parname the name of the page parameter we want param: string $type expected type of parameter return: array |
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. 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 return: mixed |
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 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 return: array |
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. param: mixed $param param: string $type PARAM_ constant param: bool $allownull are nulls valid value? param: string $debuginfo optional debug information return: mixed the $param value converted to PHP type |
clean_param_array(array $param = null, $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> param: array $param the variable array we are cleaning param: string $type expected format of param after cleaning. param: bool $recursive clean recursive arrays return: array |
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> param: mixed $param the variable we are cleaning param: string $type expected format of param after cleaning. return: mixed |
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. param: string $paramtype Constant PARAM_*. return: bool |
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. param: mixed $value return: mixed with proper utf-8 encoding |
is_number($value) X-Ref |
Return true if given value is integer or string with integer value param: mixed $value String or Int return: bool true if number, false if not |
get_host_from_url($url) X-Ref |
Returns host part from url. param: string $url full url return: string host, null if not found |
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. param: string $string a string containing HTML. return: boolean does the string contain any actual content - that is text, |
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 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 return: bool true or exception |
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 param: string $plugin full component name param: string $name default null return: mixed hash-like object or single value, return false no config found |
unset_config($name, $plugin=null) X-Ref |
Removes a key from global configuration. NOTE: this function is called from lib/db/upgrade.php param: string $name the key to set param: string $plugin (optional) the plugin scope return: boolean whether the operation succeeded. |
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 param: string $plugin a plugin, for example 'quiz' or 'qtype_multichoice'; return: boolean whether the operation succeeded. |
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. 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. return: array of user objects. |
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 param: string $type param: int $changedsince default null return: array records array |
get_cache_flag($type, $name, $changedsince=null) X-Ref |
Get volatile flags param: string $type param: string $name param: int $changedsince default null return: string|false The cache flag value or false |
set_cache_flag($type, $name, $value, $expiry = null) X-Ref |
Set a volatile flag 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 return: bool Always returns true |
unset_cache_flag($type, $name) X-Ref |
Removes a single volatile flag param: string $type the "type" namespace for the key param: string $name the key to set return: bool |
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. param: stdClass $user User object. Preferences are preloaded into 'preference' property param: int $cachelifetime Cache life time on the current page (in seconds) return: null |
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()} 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 return: bool Always true or exception |
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. 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 return: bool Always true or exception |
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. 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 return: bool Always true or exception |
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. 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 return: string|mixed|null A string containing the value of a single preference. An |
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. 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 return: int GMT timestamp |
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 param: int $totalsecs Time in seconds param: stdClass $str Should be a time object return: string A nicely formatted date/time string |
userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) X-Ref |
Returns a formatted string that represents a date in user 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. return: string the formatted date/time. |
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. 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. return: string the formatted date/time. |
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). 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 return: string the formatted date/time. |
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 param: int $time Timestamp in GMT param: float|int|string $timezone user timezone return: array An array that represents the date in user time |
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! param: int $date Timestamp in GMT param: float|int|string $timezone user timezone return: int |
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' 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. return: string the formatted string describing the time difference, e.g. '10d 11h 45m'. |
usergetmidnight($date, $timezone=99) X-Ref |
Given a time, return the GMT timestamp of the most recent midnight for the current user. param: int $date Timestamp in GMT param: float|int|string $timezone user timezone return: int Returns a GMT timestamp |
usertimezone($timezone=99) X-Ref |
Returns a string that prints the user's timezone param: float|int|string $timezone user timezone return: string |
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 param: float|int|string $tz timezone to calculate GMT time offset before return: float|string |
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. param: int $time must NOT be compensated at all, it has to be a pure timestamp param: int|float|string $strtimezone user timezone return: int |
find_day_in_month($startday, $weekday, $month, $year) X-Ref |
Calculates when the day appears in specific month 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 return: int |
days_in_month($month, $year) X-Ref |
Calculate the number of days in a given month param: int $month The month whose day count is sought param: int $year The year of the month whose day count is sought return: int |
dayofweek($day, $month, $year) X-Ref |
Calculate the position in the week of a specific calendar day 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 return: int |
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. 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 return: mixed Void, exit, and die depending on path |
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. 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 return: void |
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. param: string $keyvalue the key value param: string $script unique script identifier param: int $instance instance id return: stdClass the key entry in the user_private_key table |
require_user_key_login($script, $instance = null, $keyvalue = null) X-Ref |
Require key login. Function terminates with error if key not found or incorrect. 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. return: int Instance ID |
create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) X-Ref |
Creates a new private user access key. 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 return: string access key value |
delete_user_key($script, $userid) X-Ref |
Delete the user's new private user access keys for a particular script. param: string $script unique target identifier param: int $userid return: void |
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). 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 return: string access key value |
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. 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 return: bool |
over_bounce_threshold($user) X-Ref |
Check whether the user has exceeded the bounce threshold param: stdClass $user A {@link $USER} object return: bool true => User has exceeded bounce threshold |
set_send_count($user, $reset=false) X-Ref |
Used to increment or reset email sent count param: stdClass $user object containing an id param: bool $reset will reset the count to 0 return: void |
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 param: int $courseid The id of the course being tested return: bool |
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'. 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. return: string |
get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) X-Ref |
A centralised location for the all name fields. Returns an array / sql string snippet. param: bool $returnsql True for an sql select field snippet. param: string $tableprefix table query prefix to use in front of each field. param: string $prefix prefix added to the name fields e.g. authorfirstname. param: string $fieldprefix sql field prefix e.g. id AS userid. param: bool $order moves firstname and lastname to the top of the array / start of the string. return: array|string All name fields. |
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()} 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. return: object User name fields. |
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. param: array $values Values to be found in the string format param: string $stringformat The string which may contain values being searched for. return: array An array of values in order according to placement in the string format. |
get_extra_user_fields($context, $already = array() X-Ref |
Checks if current user is shown any extra fields when listing users. param: object $context Context param: array $already Array of fields that we're going to show anyway return: array Array of field names from user table, not including anything |
get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array() X-Ref |
If the current user is to be shown extra user fields when listing or selecting users, returns a string suitable for including in an SQL select clause to retrieve those fields. param: context $context Context param: string $alias Alias of user table, e.g. 'u' (default none) param: string $prefix Prefix for field names using AS, e.g. 'u_' (default none) param: array $already Array of fields that we're going to include anyway so don't list them (default none) return: string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank |
get_user_field_name($field) X-Ref |
Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users. param: string $field Field name, e.g. 'phone1' return: string Text description taken from language file, e.g. 'Phone number' |
exists_auth_plugin($auth) X-Ref |
Returns whether a given authentication plugin exists. param: string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}. return: boolean Whether the plugin is available. |
is_enabled_auth($auth) X-Ref |
Checks if a given plugin is in the list of enabled authentication plugins. param: string $auth Authentication plugin. return: boolean Whether the plugin is enabled. |
get_auth_plugin($auth) X-Ref |
Returns an authentication plugin instance. param: string $auth name of authentication plugin return: auth_plugin_base An instance of the required authentication plugin. |
get_enabled_auth_plugins($fix=false) X-Ref |
Returns array of active auth plugins. param: bool $fix fix $CFG->auth if needed. Only set if logged in as admin. return: array |
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 param: string $auth Form of authentication required return: bool |
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 param: string $username username to be checked return: bool |
get_user_fieldnames() X-Ref |
Returns an array of user fields return: array User field/column names |
create_user_record($username, $password, $auth = 'manual') X-Ref |
Creates a bare-bones user record 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 return: stdClass A complete user object |
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!). param: string $username user's username to update the record return: stdClass A complete user object |
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!). param: int $id user id return: stdClass A complete user object |
truncate_userinfo(array $info) X-Ref |
Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields. param: array $info Array of user properties to truncate if needed return: array The now truncated information that was passed in |
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. param: stdClass $user full user object before delete return: boolean success |
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! 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. return: stdClass|false A {@link $USER} object or false if error |
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! param: stdClass $user return: stdClass A {@link $USER} object - BC only, do not use |
password_is_legacy_hash($password) X-Ref |
Check a password hash to see if it was hashed using the legacy hash algorithm (md5). param: string $password String to check. return: boolean True if the $password matches the format of an md5 sum. |
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. param: stdClass $user (Password property may be updated). param: string $password Plain text password. return: bool True if password is valid. |
hash_internal_user_password($password, $fasthash = false) X-Ref |
Calculate hash for a plain text password. param: string $password Plain text password to be hashed. param: bool $fasthash If true, use a low cost factor when generating the hash return: string The hashed password. |
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. 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 return: bool Always returns true. |
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 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 return: mixed False, or A {@link $USER} object. |
check_password_policy($password, &$errmsg, $user = null) X-Ref |
Validate a password against the configured password policy 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. return: bool true if the password is valid according to the policy. false otherwise. |
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. 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. return: bool true if all the removals succeeded. false if there were any failures. If this |
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 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 return: bool true if all the removals succeeded. false if there were any failures. If this |
shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) X-Ref |
Change dates in module - used from course reset. 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. return: bool success |
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. param: object $data an object containing all the settings including courseid (without magic quotes) return: array status array of array component, item, error |
generate_email_processing_address($modid, $modargs) X-Ref |
Generate an email processing address. param: int $modid param: string $modargs return: string Returns email processing address |
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. param: string $action 'get', 'buffer', 'close' or 'flush' return: moodle_phpmailer|null mailer instance if 'get' used or nothing |
email_should_be_diverted($email) X-Ref |
A helper function to test for email diversion param: string $email return: bool Returns true if the email should be diverted |
generate_email_messageid($localpart = null) X-Ref |
Generate a unique email Message-ID using the moodle domain and install path param: string $localpart An optional unique message id prefix. return: string The formatted ID ready for appending to the email headers. |
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 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 return: bool Returns true if mail was sent OK and false if there was an error. |
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. 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. return: bool Returns true if we can use the from user's email adress in the "From" field. |
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. param: stdClass $user A {@link $USER} object param: bool $fasthash If true, use a low cost factor when generating the hash for speed. return: bool|string Returns "true" if mail was sent OK and "false" if there was an error |
reset_password_and_mail($user) X-Ref |
Resets specified user's password and send the new password to the user via email. param: stdClass $user A {@link $USER} object return: bool Returns true if mail was sent OK and false if there was an error. |
send_confirmation_email($user, $confirmationurl = null) X-Ref |
Send email to specified user with confirmation text and activation link. param: stdClass $user A {@link $USER} object param: string $confirmationurl user confirmation URL return: bool Returns true if mail was sent OK and false if there was an error. |
send_password_change_confirmation_email($user, $resetrecord) X-Ref |
Sends a password change confirmation email. param: stdClass $user A {@link $USER} object param: stdClass $resetrecord An object tracking metadata regarding password reset request return: bool Returns true if mail was sent OK and false if there was an error. |
send_password_change_info($user) X-Ref |
Sends an email containing information on how to change your password. param: stdClass $user A {@link $USER} object return: bool Returns true if mail was sent OK and false if there was an error. |
email_is_not_allowed($email) X-Ref |
Check that an email is allowed. It returns an error message if there was a problem. param: string $email Content of email return: string|false |
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 param: string $mimetype default application/zip return: file_packer |
valid_uploaded_file($newfile) X-Ref |
Returns current name of file on disk if it exists. param: string $newfile File to be verified return: string Current name of file on disk if true |
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. 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. return: int The maximum size for uploading files. |
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 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. return: int The maximum size for uploading files. |
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. 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, return: array |
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!) 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 return: array An array with all the filenames in all subdirectories, relative to the given rootdir |
get_directory_size($rootdir, $excludefile='') X-Ref |
Adds up all the files in a directory and works out the size. param: string $rootdir The directory to start from param: string $excludefile A file to exclude when summing directory size return: int The summed size of all files and subfiles within the root directory |
display_size($size) X-Ref |
Converts bytes into display form param: int $size The size to convert to human readable form return: string |
clean_filename($string) X-Ref |
Cleans a given filename by removing suspicious or troublesome characters param: string $string file name return: string cleaned file name |
current_language() X-Ref |
Returns the code for the current language return: string |
get_parent_language($lang=null) X-Ref |
Returns parent language of current active language if defined param: string $lang null means current language return: string |
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. param: string $language return: string previous $SESSION->forcelang value |
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. param: bool $forcereload shall the singleton be released and new instance created instead? return: core_string_manager |
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} 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 return: string The localized string. |
get_strings($array, $component = '') X-Ref |
Converts an array of strings to their localized value. param: array $array An array of strings param: string $component The language module that these strings can be found in. return: stdClass translated strings. |
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 |