Moodle APIs 4.3
Moodle 4.3.6 (Build: 20240812)
preference

Classes

class  emoticon_manager
 Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter). More...
 
class  lang_string
 The lang_string class. More...
 

Functions

 address_in_subnet ($addr, $subnetstr, $checkallzeros=false)
 Function to check the passed address is within the passed subnet.
 
 ajax_capture_output ()
 Starts capturing output whilst processing an AJAX request.
 
 ajax_check_captured_output ()
 Check captured output for content.
 
 array_is_nested ($array)
 Check if there is a nested array within the passed array.
 
 authenticate_user_login ( $username, $password, $ignorelockout=false, &$failurereason=null, $logintoken=false, string|bool $loginrecaptcha=false,)
 Authenticates a user against the chosen authentication mechanism.
 
 bounded_number ($min, $value, $max)
 Used to make sure that $min <= $value <= $max.
 
 calculate_entropy (#[\SensitiveParameter] string $pepper)
 Calculate the Shannon entropy of a string.
 
 can_send_from_real_email_address ($from, $user, $unused=null)
 Check to see if a user's real email address should be used for the "From" field.
 
 check_consecutive_identical_characters ($password, $maxchars)
 Check whether the given password has no more than the specified number of consecutive identical characters.
 
 check_password_policy ($password, &$errmsg, $user=null)
 Validate a password against the configured password policy.
 
 check_php_version ($version='5.2.4')
 Returns true if the current version of PHP is greater that the specified one.
 
 check_user_preferences_loaded (stdClass $user, $cachelifetime=120)
 Refresh user preference cache.
 
 clean_filename ($string)
 Cleans a given filename by removing suspicious or troublesome characters.
 
 clean_param ($param, $type)
 Used by optional_param() and required_param() to clean the variables and/or cast to specific types, based on an options field.
 
 clean_param_array (?array $param, $type, $recursive=false)
 Makes sure array contains only the allowed types, this function does not validate array key names!
 
 cleanremoteaddr ($addr, $compress=false)
 Cleans an ip address.
 
 cleardoubleslashes ($path)
 Replace 1 or more slashes or backslashes to 1 slash.
 
 complete_user_login ($user, array $extrauserinfo=[])
 Call to complete the user login process after authenticate_user_login() has succeeded.
 
 complex_random_string ($length=null)
 Generate a complex random string (useful for md5 salts)
 
 component_callback ($component, $function, array $params=array(), $default=null, bool $migratedtohook=false)
 Invoke component's callback functions.
 
 component_callback_exists ($component, $function)
 Determine if a component callback exists and return the function name to call.
 
 component_class_callback ($classname, $methodname, array $params, $default=null)
 Call the specified callback method on the provided class.
 
 convert_to_array ($var)
 Converts an object into an associative array.
 
 count_letters ($string, $format=null)
 Count letters in a string.
 
 count_words ($string, $format=null)
 Count words in a string.
 
 create_user_key ($script, $userid, $instance=null, $iprestriction=null, $validuntil=null)
 Creates a new private user access key.
 
 create_user_record ($username, $password, $auth='manual')
 Creates a bare-bones user record.
 
 current_language ()
 Returns the code for the current language.
 
 custom_script_path ()
 Detect a custom script replacement in the data directory that will replace an existing moodle script.
 
 date_format_string ($date, $format, $tz=99)
 Returns a formatted date ensuring it is UTF-8.
 
 dayofweek ($day, $month, $year)
 Calculate the position in the week of a specific calendar day.
 
 days_in_month ($month, $year)
 Calculate the number of days in a given month.
 
 delete_course ($courseorid, $showfeedback=true)
 Delete a course, including all related data from the database, and any associated files.
 
 delete_user (stdClass $user)
 Marks user deleted in internal user database and notifies the auth plugin.
 
 delete_user_key ($script, $userid)
 Delete the user's new private user access keys for a particular script.
 
 display_size ($size, int $decimalplaces=1, string $fixedunits='')
 Converts bytes into display form.
 
 draw_rand_array ($array, $draws)
 Given an arbitrary array, and a number of draws, this function returns an array with that amount of items.
 
 dst_offset_on ($time, $strtimezone=null)
 Calculates the Daylight Saving Offset for a given date/time (timestamp)
 
 email_is_not_allowed ($email)
 Check that an email is allowed.
 
 email_should_be_diverted ($email)
 A helper function to test for email diversion.
 
 email_to_user ($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true, $replyto='', $replytoname='', $wordwrapwidth=79)
 Send an email to a specified user.
 
 endecrypt ($pwd, $data, $case)
 Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com].
 
 exceeds_password_length (string $password, int $pepperlength=0)
 Validates user's password length.
 
 exists_auth_plugin ($auth)
 Returns whether a given authentication plugin exists.
 
 find_day_in_month ($startday, $weekday, $month, $year)
 Calculates when the day appears in specific month.
 
 fix_current_language (string $lang)
 Fix the current language to the given language code.
 
 fix_utf8 ($value)
 Makes sure the data is using valid utf8, invalid characters are discarded.
 
 force_current_language ($language)
 Force the current language to get strings and dates localised in the given language.
 
 format_float ($float, $decimalpoints=1, $localized=true, $stripzeros=false)
 Given a float, prints it nicely.
 
 format_time ($totalsecs, $str=null)
 Format a date/time (seconds) as weeks, days, hours etc as needed.
 
 fullclone ($thing)
 This function will make a complete copy of anything it's given, regardless of whether it's an object or not.
 
 fullname ($user, $override=false)
 Returns a persons full name.
 
 gc_cache_flags ()
 Garbage-collect volatile flags.
 
 generate_email_messageid ($localpart=null)
 Generate a unique email Message-ID using the moodle domain and install path.
 
 generate_email_processing_address ($modid, $modargs)
 Generate an email processing address.
 
 generate_email_signoff ()
 Generate a signoff for emails based on support settings.
 
 generate_password ($maxlen=10)
 Returns a randomly generated password of length $maxlen.
 
 get_auth_plugin ($auth)
 Returns an authentication plugin instance.
 
 get_cache_flag ($type, $name, $changedsince=null)
 Get volatile flags.
 
 get_cache_flags ($type, $changedsince=null)
 Get volatile flags.
 
 get_callable_name ($callable)
 Get human readable name describing the given callable.
 
 get_complete_user_data ($field, $value, $mnethostid=null, $throwexception=false)
 Get a complete user record, which includes all the info in the user record.
 
 get_config ($plugin, $name=null)
 Get configuration values from the global config table or the config_plugins table.
 
 get_course_display_name_for_list ($course)
 Gets the name of a course to be displayed when showing a list of courses.
 
 get_default_home_page ()
 Returns the default home page to display if current one is not defined or can't be applied.
 
 get_directory_list ($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true)
 Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
 
 get_directory_size ($rootdir, $excludefile='')
 Adds up all the files in a directory and works out the size.
 
 get_emoticon_manager ()
 Factory function for emoticon_manager.
 
 get_enabled_auth_plugins ($fix=false)
 Returns array of active auth plugins.
 
 get_file_browser ()
 Returns local file storage instance.
 
 get_file_packer ($mimetype='application/zip')
 Returns file packer.
 
 get_file_storage ($reset=false)
 Returns local file storage instance.
 
 get_home_page ()
 Gets the homepage to use for the current user.
 
 get_host_from_url ($url)
 Returns host part from url.
 
 get_list_of_charsets ()
 Returns a list of charset codes.
 
 get_list_of_plugins ($directory='mod', $exclude='', $basedir='')
 Lists plugin-like directories within specified directory.
 
 get_list_of_themes ()
 Returns a list of valid and compatible themes.
 
 get_login_url ()
 Returns full login url.
 
 get_mailer ($action='get')
 Get mailer instance, enable buffering, flush buffer or disable buffering.
 
 get_max_upload_file_size ($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused=false)
 Returns the maximum size for uploading files.
 
 get_max_upload_sizes ($sitebytes=0, $coursebytes=0, $modulebytes=0, $custombytes=null)
 Returns an array of possible sizes in local language.
 
 get_mnet_environment ()
 helper function to load up and initialise the mnet environment this must be called before you use mnet functions.
 
 get_mnet_remote_client ()
 during xmlrpc server code execution, any code wishing to access information about the remote peer must use this to get it.
 
 get_newuser_language ()
 Returns the string of the language for the new user.
 
 get_parent_language ($lang=null)
 Returns parent language of current active language if defined.
 
 get_password_peppers ()
 Get the available password peppers.
 
 get_performance_info ()
 get_performance_info() pairs up with init_performance_info() loaded in setup.php.
 
 get_plugin_list_with_function ($plugintype, $function, $file='lib.php')
 Get a list of all the plugins of a given type that define a certain API function in a certain file.
 
 get_plugins_with_function ($function, $file='lib.php', $include=true, bool $migratedtohook=false)
 Get a list of all the plugins that define a certain API function in a certain file.
 
 get_site_identifier ()
 Returns the site identifier.
 
 get_string ($identifier, $component='', $a=null, $lazyload=false)
 Returns a localized string.
 
 get_string_manager ($forcereload=false)
 Returns current string_manager instance.
 
 get_strings ($array, $component='')
 Converts an array of strings to their localized value.
 
 get_time_interval_string (int $time1, int $time2, string $format='', bool $dropzeroes=false, bool $fullformat=false)
 Get a formatted string representation of an interval between two unix timestamps.
 
 get_user_fieldnames ()
 Returns an array of user fields.
 
 get_user_key ($script, $userid, $instance=null, $iprestriction=null, $validuntil=null)
 Gets a private user access key (and creates one if one doesn't exist).
 
 get_user_max_upload_file_size ($context, $sitebytes=0, $coursebytes=0, $modulebytes=0, $user=null, $unused=false)
 Returns the maximum size for uploading files for the current user.
 
 get_user_preferences ($name=null, $default=null, $user=null)
 Used to fetch user preference(s)
 
 get_user_timezone ($tz=99)
 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.
 
 get_users_from_config ($value, $capability, $includeadmins=true)
 Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
 
 getremoteaddr ($default='0.0.0.0')
 Returns most reliable client address.
 
 getweek ($startdate, $thedate)
 Given dates in seconds, how many weeks is the date from startdate The first week is 1, the second 2 etc ...
 
 guest_user ()
 Retrieve the guest user object.
 
 hash_internal_user_password (#[\SensitiveParameter] string $password, $fasthash=false, $pepperlength=0)
 Calculate hash for a plain text password.
 
 html_is_blank ($string)
 Tests whether anything was returned by text editor.
 
 in_object_vars ($var, $object)
 Checks whether the given variable name is defined as a variable within the given object.
 
 ip_is_public ($ip)
 Is IP address a public address?
 
 is_enabled_auth ($auth)
 Checks if a given plugin is in the list of enabled authentication plugins.
 
 is_internal_auth ($auth)
 Returns true if an internal authentication method is being used.
 
 is_mnet_remote_user ($user)
 Returns whether or not the user object is a remote MNET user.
 
 is_newnav ($navigation)
 Check if the passed navigation is of the new style.
 
 is_number ($value)
 Return true if given value is integer or string with integer value.
 
 is_primary_admin ($userid)
 Is a userid the primary administrator?
 
 is_proxybypass ( $url)
 Check if $url matches anything in proxybypass list.
 
 is_restored_user ($username)
 Returns true if the user is a 'restored' one.
 
 is_rtl_compatible ($paramtype)
 Whether the PARAM_* type is compatible in RTL.
 
 is_valid_plugin_name ($name)
 This method validates a plug name.
 
 ismoving ($courseid)
 Determines if the logged in user is currently moving an activity.
 
 make_grades_menu ($gradingtype)
 Creates an array that represents all the current grades that can be chosen using the given grading type.
 
 make_menu_from_list ($list, $separator=',')
 Given a list (eg a,b,c,d,e) this function returns an array of 1->a, 2->b, 3->c etc.
 
 make_timestamp ($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true)
 Given Gregorian date parts in user time produce a GMT timestamp.
 
 make_unique_id_code ($extra='')
 make_unique_id_code
 
 microtime_diff ($a, $b)
 Calculate the difference between two microtimes.
 
 mnet_get_idp_jump_url ($user)
 return the jump url for a given remote user this is used for rewriting forum post links in emails, etc
 
 moodle_getlocale ()
 Gets the system locale.
 
 moodle_major_version ($fromdisk=false)
 Returns the major version of this site.
 
 moodle_needs_upgrading ($checkupgradeflag=true)
 Determine if moodle installation requires update.
 
 moodle_process_email ($modargs, $body)
 ?
 
 moodle_setlocale ($locale='')
 Sets the system locale.
 
 mtrace ($string, $eol="\n", $sleep=0)
 For outputting debugging info.
 
 mtrace_exception (Throwable $e)
 Helper to {.
 
 object_array_unique ($array, $keepkeyassoc=true)
 Returns an array without repeated objects.
 
 object_property_exists ( $obj, $property)
 Detect if an object or a class contains a given property will take an actual object or the name of a class.
 
 optional_param ($parname, $default, $type)
 Returns a particular value for the named variable, taken from POST or GET, otherwise returning a given default.
 
 optional_param_array ($parname, $default, $type)
 Returns a particular array value for the named variable, taken from POST or GET, otherwise returning a given default.
 
 order_in_string ($values, $stringformat)
 Returns an array of values in order of occurance in a provided string.
 
 over_bounce_threshold ($user)
 Check whether the user has exceeded the bounce threshold.
 
 partial ()
 Helper function to do partial function binding.
 
 password_is_legacy_hash (#[\SensitiveParameter] string $password)
 Check a password hash to see if it was hashed using the legacy hash algorithm (bcrypt).
 
 plugin_callback ($type, $name, $feature, $action, $params=null, $default=null, bool $migratedtohook=false)
 Invoke plugin's callback functions.
 
 plugin_supports ($type, $name, $feature, $default=null)
 Checks whether a plugin supports a specified feature.
 
 print_string ($identifier, $component='', $a=null)
 Prints out a translated string.
 
 purge_all_caches ()
 Invalidates browser caches and cached data in temp.
 
 purge_caches ($options=[])
 Selectively invalidate different types of cache.
 
 purge_other_caches ()
 Purge all non-MUC caches not otherwise purged in purge_caches.
 
 random_string ($length=15)
 Generate and return a random string of the specified length.
 
 rc4decrypt ($data)
 rc4decrypt
 
 rc4encrypt ($data)
 rc4encrypt
 
 remoteip_in_list ($list)
 Is the current ip in a given list?
 
 remove_course_contents ($courseid, $showfeedback=true, array $options=null)
 Clear a course out completely, deleting all content but don't delete the course itself.
 
 remove_dir ($dir, $contentonly=false)
 Delete directory or only its content.
 
 rename_to_unused_name (string $filepath, string $prefix='_temp_')
 Renames a file or directory to a unique name within the same directory.
 
 require_admin ()
 A convenience function for where we must be logged in as admin.
 
 require_course_login ($courseorid, $autologinguest=true, $cm=null, $setwantsurltome=true, $preventredirect=false)
 Weaker version of require_login()
 
 require_login ($courseorid=null, $autologinguest=true, $cm=null, $setwantsurltome=true, $preventredirect=false)
 This function checks that the current user is logged in and has the required privileges.
 
 require_logout ()
 This function just makes sure a user is logged out.
 
 require_user_key_login ($script, $instance=null, $keyvalue=null)
 Require key login.
 
 required_param ($parname, $type)
 Returns a particular value for the named variable, taken from POST or GET.
 
 required_param_array ($parname, $type)
 Returns a particular array value for the named variable, taken from POST or GET.
 
 reset_course_userdata ($data)
 This function will empty a course of user data.
 
 reset_password_and_mail ($user)
 Resets specified user's password and send the new password to the user via email.
 
 send_confirmation_email ($user, $confirmationurl=null)
 Send email to specified user with confirmation text and activation link.
 
 send_password_change_confirmation_email ($user, $resetrecord)
 Sends a password change confirmation email.
 
 send_password_change_info ($user)
 Sends an email containing information on how to change your password.
 
 set_bounce_count ($user, $reset=false)
 Increment or reset user's email bounce count.
 
 set_cache_flag ($type, $name, $value, $expiry=null)
 Set a volatile flag.
 
 set_config ($name, $value, $plugin=null)
 Set a key in global configuration.
 
 set_login_session_preferences ()
 When logging in, this function is run to set certain preferences for the current SESSION.
 
 set_mnet_remote_client ($client)
 during the xmlrpc server code execution, this will be called to setup the object returned by get_mnet_remote_client
 
 set_send_count ($user, $reset=false)
 Used to increment or reset email sent count.
 
 set_user_preference ($name, $value, $user=null)
 Sets a preference for the specified user.
 
 set_user_preferences (array $prefarray, $user=null)
 Sets a whole array of preferences for the current user.
 
 setnew_password_and_mail ($user, $fasthash=false)
 Sets specified user's password and send the new password to the user via email.
 
 setup_lang_from_browser ()
 This function will search for browser prefereed languages, setting Moodle to use the best one available if $SESSION->lang is undefined.
 
 shift_course_mod_dates ($modname, $fields, $timeshift, $courseid, $modid=0)
 Change dates in module - used from course reset.
 
 shorten_filename ($filename, $length=MAX_FILENAME_SIZE, $includehash=false)
 Shortens a given filename by removing characters positioned after the ideal string length.
 
 shorten_filenames (array $path, $length=MAX_FILENAME_SIZE, $includehash=false)
 Shortens a given array of filenames by removing characters positioned after the ideal string length.
 
 shorten_text ($text, $ideal=30, $exact=false, $ending='...')
 Given some text (which may contain HTML) and an ideal length, this function truncates the text neatly on a word boundary if possible.
 
 site_is_public ()
 Tries to guess if $CFG->wwwroot is publicly accessible or not.
 
 swapshuffle ($array)
 Given a simple array, this shuffles it up just like shuffle() Unlike PHP's shuffle() this function works on any machine.
 
 swapshuffle_assoc ($array)
 Like swapshuffle(), but works on associative arrays.
 
 truncate_userinfo (array $info)
 Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
 
 unformat_float ($localefloat, $strict=false)
 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!
 
 unserialize_array ($expression)
 Safe analogue of unserialize() that can only parse arrays.
 
 unserialize_object (string $input)
 Safe method for unserializing given input that is expected to contain only a serialized instance of an stdClass object.
 
 unset_all_config_for_plugin ($plugin)
 Remove all the config variables for a given plugin.
 
 unset_cache_flag ($type, $name)
 Removes a single volatile flag.
 
 unset_config ($name, $plugin=null)
 Removes a key from global configuration.
 
 unset_user_preference ($name, $user=null)
 Unsets a preference completely by deleting it from the database.
 
 update_internal_user_password (stdClass $user, #[\SensitiveParameter] ?string $password, bool $fasthash=false)
 Update password hash in user object (if necessary).
 
 update_user_login_times ()
 Modify the user table by setting the currently logged in user's last login to now.
 
 update_user_record ($username)
 Will update a local user record from an external source (MNET users can not be updated using this method!).
 
 update_user_record_by_id ($id)
 Will update a local user record from an external source (MNET users can not be updated using this method!).
 
 user_not_fully_set_up ($user, $strict=true)
 Determines if a user has completed setting up their account.
 
 user_preference_allow_ajax_update ($name, $paramtype)
 Library functions to facilitate the use of ajax JavaScript in Moodle.
 
 userdate ($date, $format='', $timezone=99, $fixday=true, $fixhour=true)
 Returns a formatted string that represents a date in user time.
 
 userdate_htmltime ($date, $format='', $timezone=99, $fixday=true, $fixhour=true)
 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.
 
 usergetdate ($time, $timezone=99)
 Given a $time timestamp in GMT (seconds since epoch), returns an array that represents the Gregorian date in user time.
 
 usergetmidnight ($date, $timezone=99)
 Given a time, return the GMT timestamp of the most recent midnight for the current user.
 
 username_load_fields_from_object ($addtoobject, $secondobject, $prefix=null, $additionalfields=null)
 Reduces lines of duplicated code for getting user name fields.
 
 usertime ($date, $timezone=99)
 Given a GMT timestamp (seconds since epoch), offsets it by the timezone.
 
 usertimezone ($timezone=99)
 Returns a string that prints the user's timezone.
 
 valid_uploaded_file ($newfile)
 Returns current name of file on disk if it exists.
 
 validate_internal_user_password (stdClass $user, #[\SensitiveParameter] string $password)
 Compare password against hash stored in user object to determine if it is valid.
 
 validate_param ($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='')
 Strict validation of parameter values, the values are only converted to requested PHP type.
 
 validate_user_key ($keyvalue, $script, $instance)
 Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
 

Variables

const AUTH_PASSWORD_NOT_CACHED 'not cached'
 Authentication constant: String used in password field when password is not stored.
 
const BLOG_COURSE_LEVEL 3
 
const BLOG_GLOBAL_LEVEL 5
 
const BLOG_GROUP_LEVEL 2
 
const BLOG_SITE_LEVEL 4
 
const BLOG_USER_LEVEL 1
 
const CONTACT_SUPPORT_ANYONE 2
 Contact site support form/link available to anyone visiting the site.
 
const CONTACT_SUPPORT_AUTHENTICATED 1
 Contact site support form/link only available to authenticated users.
 
const CONTACT_SUPPORT_DISABLED 0
 Contact site support form/link disabled.
 
const COURSE_DISPLAY_MULTIPAGE 1
 Course display settings: split pages into a page per section.
 
const COURSE_DISPLAY_SINGLEPAGE 0
 Course display settings: display all sections on one page.
 
const DAYMINS 1440
 Time constant - the number of minutes in a day.
 
const DAYSECS 86400
 Time constant - the number of seconds in a day.
 
 defined ( 'HUB_MOODLEORGHUBURL')||define( 'HUB_MOODLEORGHUBURL'
 URL of the Moodle sites registration portal.
 
const EMAIL_VIA_ALWAYS 1
 Email from header to always include via information.
 
const EMAIL_VIA_NEVER 0
 Email from header to never include via information.
 
const EMAIL_VIA_NO_REPLY_ONLY 2
 Email from header to only include via information if the address is no-reply.
 
const EXTERNAL_TOKEN_EMBEDDED 1
 Security token used for allowing access of embedded applications, the code is executed in the active user session.
 
const EXTERNAL_TOKEN_PERMANENT 0
 Security token used for allowing access from external application such as web services.
 
const FEATURE_ADVANCED_GRADING 'grade_advanced_grading'
 True if module supports advanced grading methods.
 
const FEATURE_BACKUP_MOODLE2 'backup_moodle2'
 True if module supports backup/restore of moodle2 format.
 
const FEATURE_COMMENT 'comment'
 
const FEATURE_COMPLETION_HAS_RULES 'completion_has_rules'
 True if module has custom completion rules.
 
const FEATURE_COMPLETION_TRACKS_VIEWS 'completion_tracks_views'
 True if module has code to track whether somebody viewed it.
 
const FEATURE_CONTROLS_GRADE_VISIBILITY 'controlsgradevisbility'
 True if module controls the grade visibility over the gradebook.
 
const FEATURE_GRADE_HAS_GRADE 'grade_has_grade'
 True if module can provide a grade.
 
const FEATURE_GRADE_OUTCOMES 'outcomes'
 True if module supports outcomes.
 
const FEATURE_GROUPINGS 'groupings'
 True if module supports groupings.
 
const FEATURE_GROUPMEMBERSONLY 'groupmembersonly'
 True if module supports groupmembersonly (which no longer exists)
 
const FEATURE_GROUPS 'groups'
 True if module supports groups.
 
const FEATURE_IDNUMBER 'idnumber'
 True (which is default) if the module wants support for setting the ID number for grade calculation purposes.
 
const FEATURE_MOD_ARCHETYPE 'mod_archetype'
 Type of module.
 
const FEATURE_MOD_INTRO 'mod_intro'
 True if module supports intro editor.
 
const FEATURE_MOD_PURPOSE 'mod_purpose'
 Type of module.
 
const FEATURE_MODEDIT_DEFAULT_COMPLETION 'modedit_default_completion'
 True if module has default completion.
 
const FEATURE_NO_VIEW_LINK 'viewlink'
 True if module has no 'view' page (like label)
 
const FEATURE_PLAGIARISM 'plagiarism'
 True if module supports plagiarism plugins.
 
const FEATURE_RATE 'rate'
 
const FEATURE_SHOW_DESCRIPTION 'showdescription'
 True if module can show description on course main page.
 
const FEATURE_USES_QUESTIONS 'usesquestions'
 True if module uses the question bank.
 
const GETREMOTEADDR_SKIP_DEFAULT GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR|GETREMOTEADDR_SKIP_HTTP_CLIENT_IP
 GETREMOTEADDR_SKIP_DEFAULT defines the default behavior remote IP address validation.
 
const GETREMOTEADDR_SKIP_HTTP_CLIENT_IP '1'
 Get remote addr constant.
 
const GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR '2'
 Get remote addr constant.
 
const HOMEPAGE_MY 1
 The home page should be the users my page.
 
const HOMEPAGE_MYCOURSES 3
 The home page should be the users my courses page.
 
const HOMEPAGE_SITE 0
 The home page should be the site home.
 
const HOMEPAGE_USER 2
 The home page can be chosen by the user.
 
const HOURMINS 60
 Time constant - the number of minutes in an hour.
 
const HOURSECS 3600
 Time constant - the number of seconds in an hour.
 
const MAX_FILENAME_SIZE 100
 Maximum filename char size.
 
const MAX_PASSWORD_CHARACTERS 128
 Maximum number of characters for password.
 
const MINSECS 60
 Time constant - the number of seconds in a minute.
 
const MOD_ARCHETYPE_ASSIGNMENT 2
 Assignment module archetype.
 
const MOD_ARCHETYPE_OTHER 0
 Unspecified module archetype.
 
const MOD_ARCHETYPE_RESOURCE 1
 Resource-like type module.
 
const MOD_ARCHETYPE_SYSTEM 3
 System (not user-addable) module archetype.
 
const MOD_PURPOSE_ADMINISTRATION 'administration'
 Module purpose administration.
 
const MOD_PURPOSE_ASSESSMENT 'assessment'
 Module purpose assessment.
 
const MOD_PURPOSE_COLLABORATION 'collaboration'
 Module purpose communication.
 
const MOD_PURPOSE_COMMUNICATION 'communication'
 Module purpose communication.
 
const MOD_PURPOSE_CONTENT 'content'
 Module purpose content.
 
const MOD_PURPOSE_INTERFACE 'interface'
 Module purpose interface.
 
const MOD_PURPOSE_OTHER 'other'
 Module purpose other.
 
const MOODLE_OFFICIAL_MOBILE_SERVICE 'moodle_mobile_app'
 Moodle mobile app service name.
 
const NULL_ALLOWED true
 NULL_ALLOWED - the parameter can be set to null in the database.
 
const NULL_NOT_ALLOWED false
 NULL_NOT_ALLOWED - the parameter can not be set to null in the database.
 
const PAGE_COURSE_VIEW 'course-view'
 PAGE_COURSE_VIEW is a definition of a page type.
 
const PARAM_ACTION 'alphanumext'
 PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls NOTE: originally alias for PARAM_APLHA.
 
const PARAM_ALPHA 'alpha'
 PARAM_ALPHA - contains only English ascii letters [a-zA-Z].
 
const PARAM_ALPHAEXT 'alphaext'
 PARAM_ALPHAEXT the same contents as PARAM_ALPHA (English ascii letters [a-zA-Z]) plus the chars in quotes: "_-" allowed NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed.
 
const PARAM_ALPHANUM 'alphanum'
 PARAM_ALPHANUM - expected numbers 0-9 and English ascii letters [a-zA-Z] only.
 
const PARAM_ALPHANUMEXT 'alphanumext'
 PARAM_ALPHANUMEXT - expected numbers 0-9, letters (English ascii letters [a-zA-Z]) and _- only.
 
const PARAM_AREA 'area'
 PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
 
const PARAM_AUTH 'auth'
 PARAM_AUTH - actually checks to make sure the string is a valid auth plugin.
 
const PARAM_BASE64 'base64'
 PARAM_BASE64 - Base 64 encoded format.
 
const PARAM_BOOL 'bool'
 PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
 
const PARAM_CAPABILITY 'capability'
 PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'.
 
const PARAM_CLEAN 'clean'
 PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
 
const PARAM_CLEANFILE 'file'
 PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too.
 
const PARAM_CLEANHTML 'cleanhtml'
 PARAM_CLEANHTML - cleans submitted HTML code.
 
const PARAM_COMPONENT 'component'
 PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
 
const PARAM_EMAIL 'email'
 PARAM_EMAIL - an email address following the RFC.
 
const PARAM_FILE 'file'
 PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals.
 
const PARAM_FLOAT 'float'
 PARAM_FLOAT - a real/floating point number.
 
const PARAM_FORMAT 'alphanumext'
 PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
 
const PARAM_HOST 'host'
 PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
 
const PARAM_INT 'int'
 PARAM_INT - integers only, use when expecting only numbers.
 
const PARAM_INTEGER 'int'
 PARAM_INTEGER - deprecated alias for PARAM_INT.
 
const PARAM_LANG 'lang'
 PARAM_LANG - checks to see if the string is a valid installed language in the current site.
 
const PARAM_LOCALISEDFLOAT 'localisedfloat'
 PARAM_LOCALISEDFLOAT - a localised real/floating point number.
 
const PARAM_LOCALURL 'localurl'
 PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself.
 
const PARAM_MULTILANG 'text'
 PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
 
const PARAM_NOTAGS 'notags'
 PARAM_NOTAGS - all html tags are stripped from the text.
 
const PARAM_NUMBER 'float'
 PARAM_NUMBER - deprecated alias of PARAM_FLOAT.
 
const PARAM_PATH 'path'
 PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals note: the leading slash is not removed, window drive letter is not allowed.
 
const PARAM_PEM 'pem'
 PARAM_PEM - Privacy Enhanced Mail format.
 
const PARAM_PERMISSION 'permission'
 PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
 
const PARAM_PLUGIN 'plugin'
 PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'paypal', 'completionstatus'.
 
const PARAM_RAW 'raw'
 PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters.
 
const PARAM_RAW_TRIMMED 'raw_trimmed'
 PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
 
const PARAM_SAFEDIR 'safedir'
 PARAM_SAFEDIR - safe directory name, suitable for include() and require()
 
const PARAM_SAFEPATH 'safepath'
 PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths and other references to Moodle code files.
 
const PARAM_SEQUENCE 'sequence'
 PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9.
 
const PARAM_STRINGID 'stringid'
 PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
 
const PARAM_TAG 'tag'
 PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported.
 
const PARAM_TAGLIST 'taglist'
 PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
 
const PARAM_TEXT 'text'
 PARAM_TEXT - general plain text compatible with multilang filter, no other html tags.
 
const PARAM_THEME 'theme'
 PARAM_THEME - Checks to see if the string is a valid theme name in the current site.
 
const PARAM_TIMEZONE 'timezone'
 PARAM_TIMEZONE - expected timezone.
 
const PARAM_URL 'url'
 PARAM_URL - expected properly formatted URL.
 
const PARAM_USERNAME 'username'
 PARAM_USERNAME - Clean username to only contains allowed characters.
 
const PASSWORD_DIGITS '0123456789'
 
const PASSWORD_LOWER 'abcdefghijklmnopqrstuvwxyz'
 
const PASSWORD_NONALPHANUM '.,;:!?_-+/*@#&$'
 
const PASSWORD_UPPER 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
 
const PEPPER_ENTROPY 112
 Required password pepper entropy.
 
const TAG_MAX_LENGTH 50
 To prevent problems with multibytes strings,Flag updating in nav not working on the review page.
 
const USER_CAN_IGNORE_FILE_SIZE_LIMITS -1
 Indicates the user has the capabilities required to ignore activity and course file size restrictions.
 
const VALUE_DEFAULT 0
 VALUE_DEFAULT - if the parameter is not supplied, then the default value is used.
 
const VALUE_OPTIONAL 2
 VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value.
 
const VALUE_REQUIRED 1
 VALUE_REQUIRED - if the parameter is not supplied, there is an error.
 
const WEEKSECS 604800
 Time constant - the number of seconds in a week.
 
const YEARSECS 31536000
 Time constant - the number of seconds in a year.
 

Detailed Description

Function Documentation

◆ address_in_subnet()

address_in_subnet ( $addr,
$subnetstr,
$checkallzeros = false )

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

Parameters
string$addrThe address you are checking
string$subnetstrThe string of subnet addresses
bool$checkallzerosThe state to whether check for 0.0.0.0
Return values
bool

◆ ajax_capture_output()

ajax_capture_output ( )

Starts capturing output whilst processing an AJAX request.

This should be used in combination with ajax_check_captured_output to report any captured output to the user.

Return values
BooleanReturns true on success or false on failure.

◆ ajax_check_captured_output()

ajax_check_captured_output ( )

Check captured output for content.

If the site has a debug level of debugdeveloper set, and the content is non-empty, then throw a coding exception which can be captured by the Y.IO request and displayed to the user.

Return values
Anyoutput that was captured.

◆ array_is_nested()

array_is_nested ( $array)

Check if there is a nested array within the passed array.

Parameters
array$array
Return values
booltrue if there is a nested array false otherwise

◆ authenticate_user_login()

authenticate_user_login ( $username,
$password,
$ignorelockout = false,
& $failurereason = null,
$logintoken = false,
string|bool $loginrecaptcha = false )

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!

Parameters
string$usernameUser's username (or also email if $CFG->authloginviaemail enabled)
string$passwordUser's password
bool$ignorelockoutuseful when guessing is prevented by other mechanism such as captcha or SSO
int$failurereasonlogin failure reason, can be used in renderers (it may disclose if account exists)
string | bool$logintokenIf this is set to a string it is validated against the login token for the session.
string | bool$loginrecaptchaIf this is set to a string it is validated against Google reCaptcha.
Return values
stdClass|falseA $USER object or false if error

◆ bounded_number()

bounded_number ( $min,
$value,
$max )

Used to make sure that $min <= $value <= $max.

Make sure that value is between min, and max

Parameters
int$minThe minimum value
int$valueThe value to check
int$maxThe maximum value
Return values
int

◆ calculate_entropy()

calculate_entropy ( # string $pepper[\SensitiveParameter])

Calculate the Shannon entropy of a string.

Parameters
string$pepperThe pepper to calculate the entropy of.
Return values
floatThe Shannon entropy of the string.

◆ can_send_from_real_email_address()

can_send_from_real_email_address ( $from,
$user,
$unused = null )

Check to see if a user's real email address should be used for the "From" field.

Parameters
object$fromThe user object for the user we are sending the email from.
object$userThe user object that we are sending the email to.
array$unusedNo longer used.
Return values
boolReturns true if we can use the from user's email adress in the "From" field.

◆ check_consecutive_identical_characters()

check_consecutive_identical_characters ( $password,
$maxchars )

Check whether the given password has no more than the specified number of consecutive identical characters.

Parameters
string$passwordpassword to be checked against the password policy
integer$maxcharsmaximum number of consecutive identical characters
Return values
bool

◆ check_password_policy()

check_password_policy ( $password,
& $errmsg,
$user = null )

Validate a password against the configured password policy.

Parameters
string$passwordthe password to be checked against the password policy
string$errmsgthe error message to display when the password doesn't comply with the policy.
stdClass$userthe user object to perform password validation against. Defaults to null if not provided.
Return values
booltrue if the password is valid according to the policy. false otherwise.

◆ check_php_version()

check_php_version ( $version = '5.2.4')

Returns true if the current version of PHP is greater that the specified one.

Todo
Check PHP version being required here is it too low?
Parameters
string$versionThe version of php being tested.
Return values
bool

◆ check_user_preferences_loaded()

check_user_preferences_loaded ( stdClass $user,
$cachelifetime = 120 )

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.

Parameters
stdClass$userUser object. Preferences are preloaded into 'preference' property
int$cachelifetimeCache life time on the current page (in seconds)
Exceptions
coding_exception
Return values
null

◆ clean_filename()

clean_filename ( $string)

Cleans a given filename by removing suspicious or troublesome characters.

See also
clean_param()
Parameters
string$stringfile name
Return values
stringcleaned file name

◆ clean_param()

clean_param ( $param,
$type )

Used by optional_param() and required_param() to clean the variables and/or cast to specific types, based on an options field.

$course->format = clean_param($course->format, PARAM_ALPHA); $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);

Parameters
mixed$paramthe variable we are cleaning
string$typeexpected format of param after cleaning.
Return values
mixed
Exceptions
coding_exception

◆ clean_param_array()

clean_param_array ( ?array $param,
$type,
$recursive = false )

Makes sure array contains only the allowed types, this function does not validate array key names!

$options = clean_param($options, PARAM_INT);

Parameters
array | null$paramthe variable array we are cleaning
string$typeexpected format of param after cleaning.
bool$recursiveclean recursive arrays
Return values
array
Exceptions
coding_exception

◆ cleanremoteaddr()

cleanremoteaddr ( $addr,
$compress = false )

Cleans an ip address.

Internal addresses are now allowed. (Originally local addresses were not allowed.)

Parameters
string$addrIPv4 or IPv6 address
bool$compressuse IPv6 address compression
Return values
stringnormalised ip address string, null if error

◆ cleardoubleslashes()

cleardoubleslashes ( $path)

Replace 1 or more slashes or backslashes to 1 slash.

Parameters
string$pathThe path to strip
Return values
stringthe path with double slashes removed

◆ complete_user_login()

complete_user_login ( $user,
array $extrauserinfo = [] )

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!
Parameters
stdClass$user
array$extrauserinfo
Return values
stdClassA $USER object - BC only, do not use

◆ complex_random_string()

complex_random_string ( $length = null)

Generate a complex random string (useful for md5 salts)

This function is based on the above random_string() however it uses a larger pool of characters and generates a string between 24 and 32 characters

Parameters
int$lengthOptional if set generates a string to exactly this length
Return values
string

◆ component_callback()

component_callback ( $component,
$function,
array $params = array(),
$default = null,
bool $migratedtohook = false )

Invoke component's callback functions.

Parameters
string$componentfrankenstyle component name, e.g. 'mod_quiz'
string$functionthe rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
array$paramsparameters of callback function
mixed$defaultdefault value if callback function hasn't been defined, or if it retursn null.
bool$migratedtohookif true this is a deprecated callback, if hook callback is present then do nothing
Return values
mixed

◆ component_callback_exists()

component_callback_exists ( $component,
$function )

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.

Parameters
string$componentfrankenstyle component name, e.g. 'mod_quiz'
string$functionthe rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
Return values
mixedComplete function name to call if the callback exists or false if it doesn't.
Exceptions
coding_exceptionif invalid component specfied

◆ component_class_callback()

component_class_callback ( $classname,
$methodname,
array $params,
$default = null )

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.

Parameters
string$classnameThe name of the class to call upon.
string$methodnameThe name of the staticically defined method on the class.
array$paramsThe arguments to pass into the method.
mixed$defaultThe default value.
Return values
mixedThe return value.

◆ convert_to_array()

convert_to_array ( $var)

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()

Parameters
mixed$var
Return values
array

◆ count_letters()

count_letters ( $string,
$format = null )

Count letters in a string.

Letters are defined as chars not in tags and different from whitespace.

Parameters
string$stringThe text to be searched for letters. May be HTML.
int | null$format
Return values
intThe count of letters in the specified text.

◆ count_words()

count_words ( $string,
$format = null )

Count words in a string.

Words are defined as things between whitespace.

Parameters
string$stringThe text to be searched for words. May be HTML.
int | null$format
Return values
intThe count of words in the specified string

◆ create_user_key()

create_user_key ( $script,
$userid,
$instance = null,
$iprestriction = null,
$validuntil = null )

Creates a new private user access key.

Parameters
string$scriptunique target identifier
int$userid
int$instanceoptional instance id
string$iprestrictionoptional ip restricted access
int$validuntilkey valid only until given data
Return values
stringaccess key value

◆ create_user_record()

create_user_record ( $username,
$password,
$auth = 'manual' )

Creates a bare-bones user record.

Todo
Outline auth types and provide code example
Parameters
string$usernameNew user's username to add to record
string$passwordNew user's password to add to record
string$authForm of authentication required
Return values
stdClassA complete user object

◆ current_language()

current_language ( )

Returns the code for the current language.

Return values
string

◆ custom_script_path()

custom_script_path ( )

Detect a custom script replacement in the data directory that will replace an existing moodle script.

Return values
string|boolfull path name if a custom script exists, false if no custom script exists

◆ date_format_string()

date_format_string ( $date,
$format,
$tz = 99 )

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).

Parameters
int$datethe timestamp - since Moodle 2.9 this is a real UTC timestamp
string$formatstrftime format.
int | float | string$tzthe user timezone
Return values
stringthe formatted date/time.
Since
Moodle 2.3.3

◆ dayofweek()

dayofweek ( $day,
$month,
$year )

Calculate the position in the week of a specific calendar day.

Parameters
int$dayThe day of the date whose position in the week is sought
int$monthThe month of the date whose position in the week is sought
int$yearThe year of the date whose position in the week is sought
Return values
int

◆ days_in_month()

days_in_month ( $month,
$year )

Calculate the number of days in a given month.

Parameters
int$monthThe month whose day count is sought
int$yearThe year of the month whose day count is sought
Return values
int

◆ delete_course()

delete_course ( $courseorid,
$showfeedback = true )

Delete a course, including all related data from the database, and any associated files.

Parameters
mixed$courseoridThe id of the course or course object to delete.
bool$showfeedbackWhether to display notifications of each action the function performs.
Return values
booltrue if all the removals succeeded. false if there were any failures. If this method returns false, some of the removals will probably have succeeded, and others failed, but you have no way of knowing which.

◆ delete_user()

delete_user ( stdClass $user)

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.

Parameters
stdClass$userfull user object before delete
Return values
booleansuccess
Exceptions
coding_exceptionif invalid $user parameter detected

◆ delete_user_key()

delete_user_key ( $script,
$userid )

Delete the user's new private user access keys for a particular script.

Parameters
string$scriptunique target identifier
int$userid
Return values
void

◆ display_size()

display_size ( $size,
int $decimalplaces = 1,
string $fixedunits = '' )

Converts bytes into display form.

Parameters
int$sizeThe size to convert to human readable form
int$decimalplacesIf specified, uses fixed number of decimal places
string$fixedunitsIf specified, uses fixed units (e.g. 'KB')
Return values
stringDisplay version of size

◆ draw_rand_array()

draw_rand_array ( $array,
$draws )

Given an arbitrary array, and a number of draws, this function returns an array with that amount of items.

The indexes are retained.

Todo
Finish documenting this function
Parameters
array$array
int$draws
Return values
array

◆ dst_offset_on()

dst_offset_on ( $time,
$strtimezone = null )

Calculates the Daylight Saving Offset for a given date/time (timestamp)

  • Note: Daylight saving only works for string timezones and not for float.
Parameters
int$timemust NOT be compensated at all, it has to be a pure timestamp
int | float | string$strtimezoneuser timezone
Return values
int

◆ email_is_not_allowed()

email_is_not_allowed ( $email)

Check that an email is allowed.

It returns an error message if there was a problem.

Parameters
string$emailContent of email
Return values
string|false

◆ email_should_be_diverted()

email_should_be_diverted ( $email)

A helper function to test for email diversion.

Parameters
string$email
Return values
boolReturns true if the email should be diverted

◆ email_to_user()

email_to_user ( $user,
$from,
$subject,
$messagetext,
$messagehtml = '',
$attachment = '',
$attachname = '',
$usetrueaddress = true,
$replyto = '',
$replytoname = '',
$wordwrapwidth = 79 )

Send an email to a specified user.

Parameters
stdClass$userA $USER object
stdClass$fromA $USER object
string$subjectplain text subject line of the email
string$messagetextplain text version of the message
string$messagehtmlcomplete html version of the message (optional)
string$attachmenta file on the filesystem, either relative to $CFG->dataroot or a full path to a file in one of the following directories: $CFG->cachedir, $CFG->dataroot, $CFG->dirroot, $CFG->localcachedir, $CFG->tempdir
string$attachnamethe name of the file (extension indicates MIME)
bool$usetrueaddressdetermines whether $from email address should be sent out. Will be overruled by user profile setting for maildisplay
string$replytoEmail address to reply to
string$replytonameName of reply to recipient
int$wordwrapwidthcustom word wrap width, default 79
Return values
boolReturns true if mail was sent OK and false if there was an error.

◆ endecrypt()

endecrypt ( $pwd,
$data,
$case )

Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com].

Todo
Finish documenting this function
Parameters
string$pwdThe password to use when encrypting or decrypting
string$dataThe data to be decrypted/encrypted
string$caseEither 'de' for decrypt or '' for encrypt
Return values
string

◆ exceeds_password_length()

exceeds_password_length ( string $password,
int $pepperlength = 0 )

Validates user's password length.

Parameters
string$password
int$pepperlengthThe length of the used peppers
Return values
bool

◆ exists_auth_plugin()

exists_auth_plugin ( $auth)

Returns whether a given authentication plugin exists.

Parameters
string$authForm of authentication to check for. Defaults to the global setting in $CFG.
Return values
booleanWhether the plugin is available.

◆ find_day_in_month()

find_day_in_month ( $startday,
$weekday,
$month,
$year )

Calculates when the day appears in specific month.

Parameters
int$startdaystarting day of the month
int$weekdayThe day when week starts (normally taken from user preferences)
int$monthThe month whose day is sought
int$yearThe year of the month whose day is sought
Return values
int

◆ fix_current_language()

fix_current_language ( string $lang)

Fix the current language to the given language code.

Parameters
string$langThe language code to use.
Return values
void

◆ fix_utf8()

fix_utf8 ( $value)

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.

Parameters
mixed$value
Return values
mixedwith proper utf-8 encoding

◆ force_current_language()

force_current_language ( $language)

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.

Parameters
string$language
Return values
stringprevious $SESSION->forcelang value

◆ format_float()

format_float ( $float,
$decimalpoints = 1,
$localized = true,
$stripzeros = false )

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'.

Parameters
float$floatThe float to print
int$decimalpointsThe number of decimal places to print. -1 is a special value for auto detect (full precision).
bool$localizeduse localized decimal separator
bool$stripzerosIf true, removes final zeros after decimal point. It will be ignored and the trailing zeros after the decimal point are always striped if $decimalpoints is -1.
Return values
stringlocale float

◆ format_time()

format_time ( $totalsecs,
$str = null )

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

@uses MINSECS @uses HOURSECS @uses DAYSECS @uses YEARSECS

Parameters
int$totalsecsTime in seconds
stdClass$strShould be a time object
Return values
stringA nicely formatted date/time string

◆ fullclone()

fullclone ( $thing)

This function will make a complete copy of anything it's given, regardless of whether it's an object or not.

Parameters
mixed$thingSomething you want cloned
Return values
mixedWhat ever it is you passed it

◆ fullname()

fullname ( $user,
$override = false )

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'.

Parameters
stdClass$userA $USER object to get full name of.
bool$overrideIf true then the alternativefullnameformat format rather than fullnamedisplay format will be used.
Return values
string

◆ gc_cache_flags()

gc_cache_flags ( )

Garbage-collect volatile flags.

Return values
boolAlways returns true

◆ generate_email_messageid()

generate_email_messageid ( $localpart = null)

Generate a unique email Message-ID using the moodle domain and install path.

Parameters
string$localpartAn optional unique message id prefix.
Return values
stringThe formatted ID ready for appending to the email headers.

◆ generate_email_processing_address()

generate_email_processing_address ( $modid,
$modargs )

Generate an email processing address.

Parameters
int$modid
string$modargs
Return values
stringReturns email processing address

◆ generate_email_signoff()

generate_email_signoff ( )

Generate a signoff for emails based on support settings.

Return values
string

◆ generate_password()

generate_password ( $maxlen = 10)

Returns a randomly generated password of length $maxlen.

inspired by

and

Parameters
int$maxlenThe maximum size of the password being generated.
Return values
string

◆ get_auth_plugin()

get_auth_plugin ( $auth)

Returns an authentication plugin instance.

Parameters
string$authname of authentication plugin
Return values
auth_plugin_baseAn instance of the required authentication plugin.

◆ get_cache_flag()

get_cache_flag ( $type,
$name,
$changedsince = null )

Get volatile flags.

Parameters
string$type
string$name
int$changedsincedefault null
Return values
string|falseThe cache flag value or false

◆ get_cache_flags()

get_cache_flags ( $type,
$changedsince = null )

Get volatile flags.

Parameters
string$type
int$changedsincedefault null
Return values
arrayrecords array

◆ get_callable_name()

get_callable_name ( $callable)

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.

Parameters
callable | string | array$callable
Return values
string|boolHuman readable name of callable, or false if not a valid callable.

◆ get_complete_user_data()

get_complete_user_data ( $field,
$value,
$mnethostid = null,
$throwexception = false )

Get a complete user record, which includes all the info in the user record.

Intended for setting as $USER session variable

Parameters
string$fieldThe user field to be checked for a given value.
string$valueThe value to match for $field.
int$mnethostid
bool$throwexceptionIf true, it will throw an exception when there's no record found or when there are multiple records found. Otherwise, it will just return false.
Return values
mixedFalse, or A $USER object.

◆ get_config()

get_config ( $plugin,
$name = null )

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

Parameters
string$pluginfull component name
string$namedefault null
Return values
mixedhash-like object or single value, return false no config found
Exceptions
dml_exception

◆ get_course_display_name_for_list()

get_course_display_name_for_list ( $course)

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.

Parameters
stdClass | core_course_list_element$courseMoodle course object
Return values
stringDisplay name of course (either fullname or short + fullname)

◆ get_default_home_page()

get_default_home_page ( )

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 values
intThe default home page.

◆ get_directory_list()

get_directory_list ( $rootdir,
$excludefiles = '',
$descend = true,
$getdirs = false,
$getfiles = true )

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!)

Todo
Finish documenting this function. Add examples of $excludefile usage.
Parameters
string$rootdirA given root directory to start from
string | array$excludefilesIf defined then the specified file/directory is ignored
bool$descendIf true then subdirectories are recursed as well
bool$getdirsIf true then (sub)directories are included in the output
bool$getfilesIf true then files are included in the output
Return values
arrayAn array with all the filenames in all subdirectories, relative to the given rootdir

◆ get_directory_size()

get_directory_size ( $rootdir,
$excludefile = '' )

Adds up all the files in a directory and works out the size.

Parameters
string$rootdirThe directory to start from
string$excludefileA file to exclude when summing directory size
Return values
intThe summed size of all files and subfiles within the root directory

◆ get_emoticon_manager()

get_emoticon_manager ( )

Factory function for emoticon_manager.

Return values
emoticon_managersingleton

◆ get_enabled_auth_plugins()

get_enabled_auth_plugins ( $fix = false)

Returns array of active auth plugins.

Parameters
bool$fixfix $CFG->auth if needed. Only set if logged in as admin.
Return values
array

◆ get_file_browser()

get_file_browser ( )

Returns local file storage instance.

Return values
file_browser

◆ get_file_packer()

get_file_packer ( $mimetype = 'application/zip')

Returns file packer.

Parameters
string$mimetypedefault application/zip
Return values
file_packer

◆ get_file_storage()

get_file_storage ( $reset = false)

Returns local file storage instance.

Return values
file_storage

◆ get_home_page()

get_home_page ( )

Gets the homepage to use for the current user.

Return values
intOne of HOMEPAGE_*

◆ get_host_from_url()

get_host_from_url ( $url)

Returns host part from url.

Parameters
string$urlfull url
Return values
stringhost, null if not found

◆ get_list_of_charsets()

get_list_of_charsets ( )

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 values
arrayAnd associative array with contents in the form of charset => charset

◆ get_list_of_plugins()

get_list_of_plugins ( $directory = 'mod',
$exclude = '',
$basedir = '' )

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.

Parameters
string$directoryrelative directory from root
string$excludedir name to exclude from the list (defaults to none)
string$basedirfull path to the base dir where $plugin resides (defaults to $CFG->dirroot)
Return values
arraySorted array of directory names found under the requested parameters

◆ get_list_of_themes()

get_list_of_themes ( )

Returns a list of valid and compatible themes.

Return values
array

◆ get_login_url()

get_login_url ( )

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 values
stringlogin url

◆ get_mailer()

get_mailer ( $action = 'get')

Get mailer instance, enable buffering, flush buffer or disable buffering.

Parameters
string$action'get', 'buffer', 'close' or 'flush'
Return values
moodle_phpmailer|nullmailer instance if 'get' used or nothing

◆ get_max_upload_file_size()

get_max_upload_file_size ( $sitebytes = 0,
$coursebytes = 0,
$modulebytes = 0,
$unused = false )

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.

Todo
Finish documenting this function
Parameters
int$sitebytesSet maximum size
int$coursebytesCurrent course $course->maxbytes (in bytes)
int$modulebytesCurrent module ->maxbytes (in bytes)
bool$unusedThis parameter has been deprecated and is not used any more.
Return values
intThe maximum size for uploading files.

◆ get_max_upload_sizes()

get_max_upload_sizes ( $sitebytes = 0,
$coursebytes = 0,
$modulebytes = 0,
$custombytes = null )

Returns an array of possible sizes in local language.

Related to 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.

@uses SORT_NUMERIC

Parameters
int$sitebytesSet maximum size
int$coursebytesCurrent course $course->maxbytes (in bytes)
int$modulebytesCurrent module ->maxbytes (in bytes)
int | array$custombytescustom upload size/s which will be added to list, Only value/s smaller then maxsize will be added to list.
Return values
array

◆ get_mnet_environment()

get_mnet_environment ( )

helper function to load up and initialise the mnet environment this must be called before you use mnet functions.

Return values
mnet_environmentthe equivalent of old $MNET global

◆ get_mnet_remote_client()

get_mnet_remote_client ( )

during xmlrpc server code execution, any code wishing to access information about the remote peer must use this to get it.

Return values
mnet_remote_clientthe equivalent of old $MNETREMOTE_CLIENT global

◆ get_newuser_language()

get_newuser_language ( )

Returns the string of the language for the new user.

Return values
stringlanguage for the new user

◆ get_parent_language()

get_parent_language ( $lang = null)

Returns parent language of current active language if defined.

Parameters
string$langnull means current language
Return values
string

◆ get_password_peppers()

get_password_peppers ( )

Get the available password peppers.

The latest pepper is checked for minimum entropy as part of this function. We only calculate the entropy of the most recent pepper, because passwords are always updated to the latest pepper, and in the past we may have enforced a lower minimum entropy. Also, we allow the latest pepper to be empty, to allow admins to migrate off peppers.

Return values
arrayThe password peppers.
Exceptions
coding_exceptionIf the entropy of the password pepper is less than the recommended minimum.

◆ get_performance_info()

get_performance_info ( )

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 values
array

◆ get_plugin_list_with_function()

get_plugin_list_with_function ( $plugintype,
$function,
$file = 'lib.php' )

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.

Parameters
string$plugintypethe type of plugin, e.g. 'mod' or 'report'.
string$functionthe part of the name of the function after the frankenstyle prefix. e.g 'hook' if you are looking for functions with names like report_courselist_hook.
string$filethe name of file within the plugin that defines the function. Defaults to lib.php.
Return values
arraywith frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum') and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').

◆ get_plugins_with_function()

get_plugins_with_function ( $function,
$file = 'lib.php',
$include = true,
bool $migratedtohook = false )

Get a list of all the plugins that define a certain API function in a certain file.

Parameters
string$functionthe part of the name of the function after the frankenstyle prefix. e.g 'hook' if you are looking for functions with names like report_courselist_hook.
string$filethe name of file within the plugin that defines the function. Defaults to lib.php.
bool$includeWhether to include the files that contain the functions or not.
bool$migratedtohookif true this is a deprecated lib.php callback, if hook callback is present then do nothing
Return values
arraywith [plugintype][plugin] = functionname

◆ get_site_identifier()

get_site_identifier ( )

Returns the site identifier.

Return values
string\$CFG-,>siteidentifier,firstmaking sure it is properly initialised.

◆ get_string()

get_string ( $identifier,
$component = '',
$a = null,
$lazyload = false )

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 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.
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' $string['course'] = 'Course'; 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' $mystring = ''. get_string('course') .''; or 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: $string['typecourse'] = 'Course event'; 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): $mystring = '

'. get_string('typecourse', 'calendar') .'

';

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 lang_string

Parameters
string$identifierThe key identifier for the localized string
string$componentThe module where the key identifier is stored, usually expressed as the filename in the language pack without the .php on the end but can also be written as mod/forum or grade/export/xls. If none is specified then moodle.php is used.
string | object | array | int$aAn object, string or number that can be used within translation strings
bool$lazyloadIf set to true a string object is returned instead of the string itself. The string then isn't calculated until it is first used.
Return values
stringThe localized string.
Exceptions
coding_exception

◆ get_string_manager()

get_string_manager ( $forcereload = false)

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.

Parameters
bool$forcereloadshall the singleton be released and new instance created instead?
Return values
core_string_manager

◆ get_strings()

get_strings ( $array,
$component = '' )

Converts an array of strings to their localized value.

Parameters
array$arrayAn array of strings
string$componentThe language module that these strings can be found in.
Return values
stdClasstranslated strings.

◆ get_time_interval_string()

get_time_interval_string ( int $time1,
int $time2,
string $format = '',
bool $dropzeroes = false,
bool $fullformat = false )

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'

Parameters
int$time1unix timestamp
int$time2unix timestamp
string$formatstring (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php.
bool$dropzeroesIf format is not provided and this is set to true, do not include zero time units. e.g. a duration of 3 days and 2 hours will be displayed as '3d 2h' instead of '3d 2h 0s'
bool$fullformatIf format is not provided and this is set to true, display time units in full format. e.g. instead of showing "3d", "3 days" will be returned.
Return values
stringthe formatted string describing the time difference, e.g. '10d 11h 45m'.

◆ get_user_fieldnames()

get_user_fieldnames ( )

Returns an array of user fields.

Return values
arrayUser field/column names

◆ get_user_key()

get_user_key ( $script,
$userid,
$instance = null,
$iprestriction = null,
$validuntil = null )

Gets a private user access key (and creates one if one doesn't exist).

Parameters
string$scriptunique target identifier
int$userid
int$instanceoptional instance id
string$iprestrictionoptional ip restricted access
int$validuntilkey valid only until given date
Return values
stringaccess key value

◆ get_user_max_upload_file_size()

get_user_max_upload_file_size ( $context,
$sitebytes = 0,
$coursebytes = 0,
$modulebytes = 0,
$user = null,
$unused = false )

Returns the maximum size for uploading files for the current user.

This function takes in account get_max_upload_file_size() the user's capabilities

Parameters
context$contextThe context in which to check user capabilities
int$sitebytesSet maximum size
int$coursebytesCurrent course $course->maxbytes (in bytes)
int$modulebytesCurrent module ->maxbytes (in bytes)
stdClass$userThe user
bool$unusedThis parameter has been deprecated and is not used any more.
Return values
intThe maximum size for uploading files.

◆ get_user_preferences()

get_user_preferences ( $name = null,
$default = null,
$user = null )

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.

Parameters
string$nameName of the key to use in finding a preference value
mixed | null$defaultValue to be returned if the $name key is not set in the user preferences
stdClass | int | null$userA moodle user object or id, null means current user
Exceptions
coding_exception
Return values
string|mixed|nullA string containing the value of a single preference. An array with all of the preferences or null

◆ get_user_timezone()

get_user_timezone ( $tz = 99)

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.

Parameters
float | int | string$tztimezone to calculate GMT time offset before calculating user timezone, 99 is default user timezone
Return values
float|string

◆ get_users_from_config()

get_users_from_config ( $value,
$capability,
$includeadmins = true )

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.

Parameters
string$valuethe value of the config setting.
string$capabilitythe capability - must match the one passed to the admin_setting_users_with_capability constructor.
bool$includeadminsinclude administrators.
Return values
arrayof user objects.

◆ getremoteaddr()

getremoteaddr ( $default = '0.0.0.0')

Returns most reliable client address.

Parameters
string$defaultIf an address can't be determined, then return this
Return values
stringThe remote IP address

◆ getweek()

getweek ( $startdate,
$thedate )

Given dates in seconds, how many weeks is the date from startdate The first week is 1, the second 2 etc ...

Parameters
int$startdateTimestamp for the start date
int$thedateTimestamp for the end date
Return values
string

◆ guest_user()

guest_user ( )

Retrieve the guest user object.

Return values
stdClassA $USER object

◆ hash_internal_user_password()

hash_internal_user_password ( # string $password[\SensitiveParameter],
$fasthash = false,
$pepperlength = 0 )

Calculate hash for a plain text password.

Parameters
string$passwordPlain text password to be hashed.
bool$fasthashIf true, use a low number of rounds when generating the hash This is faster to generate but makes the hash less secure. It is used when lots of hashes need to be generated quickly.
int$pepperlengthLenght of the peppers
Return values
stringThe hashed password.
Exceptions
moodle_exceptionIf a problem occurs while generating the hash.

◆ html_is_blank()

html_is_blank ( $string)

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
tag or something.

Parameters
string$stringa string containing HTML.
Return values
booleandoes the string contain any actual content - that is text, images, objects, etc.

◆ in_object_vars()

in_object_vars ( $var,
$object )

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.

Parameters
string$varThe variable name
object$objectThe object to check
Return values
boolean

◆ ip_is_public()

ip_is_public ( $ip)

Is IP address a public address?

Parameters
string$ipThe ip to check
Return values
booltrue if the ip is public

◆ is_enabled_auth()

is_enabled_auth ( $auth)

Checks if a given plugin is in the list of enabled authentication plugins.

Parameters
string$authAuthentication plugin.
Return values
booleanWhether the plugin is enabled.

◆ is_internal_auth()

is_internal_auth ( $auth)

Returns true if an internal authentication method is being used.

if method not specified then, global default is assumed

Parameters
string$authForm of authentication required
Return values
bool

◆ is_mnet_remote_user()

is_mnet_remote_user ( $user)

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.

Parameters
object$userA valid user object
Return values
boolTrue if the user is from a remote Moodle.

◆ is_newnav()

is_newnav ( $navigation)

Check if the passed navigation is of the new style.

Parameters
mixed$navigation
Return values
booltrue for yes false for no

◆ is_number()

is_number ( $value)

Return true if given value is integer or string with integer value.

Parameters
mixed$valueString or Int
Return values
booltrue if number, false if not

◆ is_primary_admin()

is_primary_admin ( $userid)

Is a userid the primary administrator?

Parameters
int$useridint id of user to check
Return values
boolean

◆ is_proxybypass()

is_proxybypass ( $url)

Check if $url matches anything in proxybypass list.

Any errors just result in the proxy being used (least bad)

Parameters
string$urlurl to check
Return values
booleantrue if we should bypass the proxy

◆ is_restored_user()

is_restored_user ( $username)

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

Parameters
string$usernameusername to be checked
Return values
bool

◆ is_rtl_compatible()

is_rtl_compatible ( $paramtype)

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.

Parameters
string$paramtypeConstant PARAM_*.
Return values
bool

◆ is_valid_plugin_name()

is_valid_plugin_name ( $name)

This method validates a plug name.

It is much faster than calling clean_param.

Parameters
string$namea string that might be a plugin name.
Return values
boolif this string is a valid plugin name.

◆ ismoving()

ismoving ( $courseid)

Determines if the logged in user is currently moving an activity.

Parameters
int$courseidThe id of the course being tested
Return values
bool

◆ make_grades_menu()

make_grades_menu ( $gradingtype)

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.

Todo
Finish documenting this function or better deprecated this completely!
Parameters
int$gradingtype
Return values
array

◆ make_menu_from_list()

make_menu_from_list ( $list,
$separator = ',' )

Given a list (eg a,b,c,d,e) this function returns an array of 1->a, 2->b, 3->c etc.

Parameters
string$listThe string to explode into array bits
string$separatorThe separator used within the list string
Return values
arrayThe now assembled array

◆ make_timestamp()

make_timestamp ( $year,
$month = 1,
$day = 1,
$hour = 0,
$minute = 0,
$second = 0,
$timezone = 99,
$applydst = true )

Given Gregorian date parts in user time produce a GMT timestamp.

Parameters
int$yearThe year part to create timestamp of
int$monthThe month part to create timestamp of
int$dayThe day part to create timestamp of
int$hourThe hour part to create timestamp of
int$minuteThe minute part to create timestamp of
int$secondThe second part to create timestamp of
int | float | string$timezoneTimezone modifier, used to calculate GMT time offset. if 99 then default user's timezone is used
bool$applydstToggle Daylight Saving Time, default true, will be applied only if timezone is 99 or string.
Return values
intGMT timestamp

◆ make_unique_id_code()

make_unique_id_code ( $extra = '')

make_unique_id_code

Todo
Finish documenting this function

@uses $_SERVER

Parameters
string$extraExtra string to append to the end of the code
Return values
string

◆ microtime_diff()

microtime_diff ( $a,
$b )

Calculate the difference between two microtimes.

Parameters
string$aThe first Microtime
string$bThe second Microtime
Return values
string

◆ mnet_get_idp_jump_url()

mnet_get_idp_jump_url ( $user)

return the jump url for a given remote user this is used for rewriting forum post links in emails, etc

Parameters
stdclass$userthe user to get the idp url for

◆ moodle_getlocale()

moodle_getlocale ( )

Gets the system locale.

Return values
stringRetuns the current locale.

◆ moodle_major_version()

moodle_major_version ( $fromdisk = false)

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.

Parameters
bool$fromdiskshould the version if source code files be used
Return values
string|falsethe major version like '2.3', false if could not be determined

◆ moodle_needs_upgrading()

moodle_needs_upgrading ( $checkupgradeflag = true)

Determine if moodle installation requires update.

Checks version numbers of main code and all plugins to see if there are any mismatches.

Parameters
bool$checkupgradeflagcheck the outagelessupgrade flag to see if an upgrade is running.
Return values
bool

◆ moodle_process_email()

moodle_process_email ( $modargs,
$body )

?

Todo
Finish documenting this function
Parameters
string$modargs
string$bodyCurrently unused

◆ moodle_setlocale()

moodle_setlocale ( $locale = '')

Sets the system locale.

Parameters
string$localeCan be used to force a locale

◆ mtrace()

mtrace ( $string,
$eol = "\n",
$sleep = 0 )

For outputting debugging info.

Parameters
string$stringThe string to write
string$eolThe end of line char(s) to use
string$sleepPeriod to make the application sleep This ensures any messages have time to display before redirect

◆ mtrace_exception()

mtrace_exception ( Throwable $e)

Helper to {.

See also
mtrace()} an exception or throwable, including all relevant information.
Parameters
Throwable$ethe error to ouptput.

◆ object_array_unique()

object_array_unique ( $array,
$keepkeyassoc = true )

Returns an array without repeated objects.

This function is similar to array_unique, but for arrays that have objects as values

Parameters
array$array
bool$keepkeyassoc
Return values
array

◆ object_property_exists()

object_property_exists ( $obj,
$property )

Detect if an object or a class contains a given property will take an actual object or the name of a class.

Parameters
mixed$objName of class or real object to test
string$propertyname of property to find
Return values
booltrue if property exists

◆ optional_param()

optional_param ( $parname,
$default,
$type )

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.

Parameters
string$parnamethe name of the page parameter we want
mixed$defaultthe default value to return if nothing is found
string$typeexpected type of parameter
Return values
mixed
Exceptions
coding_exception

◆ optional_param_array()

optional_param_array ( $parname,
$default,
$type )

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

Parameters
string$parnamethe name of the page parameter we want
mixed$defaultthe default value to return if nothing is found
string$typeexpected type of parameter
Return values
array
Exceptions
coding_exception

◆ order_in_string()

order_in_string ( $values,
$stringformat )

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.

Parameters
array$valuesValues to be found in the string format
string$stringformatThe string which may contain values being searched for.
Return values
arrayAn array of values in order according to placement in the string format.

◆ over_bounce_threshold()

over_bounce_threshold ( $user)

Check whether the user has exceeded the bounce threshold.

Parameters
stdClass$userA $USER object
Return values
booltrue => User has exceeded bounce threshold

◆ partial()

partial ( )

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.

Parameters
mixed$functiona php callback
mixed$arg1,...$argv arguments to partially bind with
Return values
arrayArray callback

◆ password_is_legacy_hash()

password_is_legacy_hash ( # string $password[\SensitiveParameter])

Check a password hash to see if it was hashed using the legacy hash algorithm (bcrypt).

Parameters
string$passwordString to check.
Return values
boolTrue if the $password matches the format of a bcrypt hash.

◆ plugin_callback()

plugin_callback ( $type,
$name,
$feature,
$action,
$params = null,
$default = null,
bool $migratedtohook = false )

Invoke plugin's callback functions.

Parameters
string$typeplugin type e.g. 'mod'
string$nameplugin name
string$featurefeature name
string$actionfeature's action
array$paramsparameters of callback function, should be an array
mixed$defaultdefault value if callback function hasn't been defined, or if it retursn null.
bool$migratedtohookif true this is a deprecated callback, if hook callback is present then do nothing
Return values
mixed
Todo
Decide about to deprecate and drop plugin_callback() - MDL-30743

◆ plugin_supports()

plugin_supports ( $type,
$name,
$feature,
$default = null )

Checks whether a plugin supports a specified feature.

Parameters
string$typePlugin type e.g. 'mod'
string$namePlugin name e.g. 'forum'
string$featureFeature code (FEATURE_xx constant)
mixed$defaultdefault value if feature support unknown
Return values
mixedFeature result (false if not supported, null if feature is unknown, otherwise usually true but may have other feature-specific value such as array)
Exceptions
coding_exception

◆ print_string()

print_string ( $identifier,
$component = '',
$a = null )

Prints out a translated string.

Prints out a translated string using the return value from the get_string() function.

Example usage of this function when the string is in the moodle.php file:
echo ''; print_string('course'); echo '';

Example usage of this function when the string is not in the moodle.php file:
echo '

'; print_string('typecourse', 'calendar'); echo '

';

Parameters
string$identifierThe key identifier for the localized string
string$componentThe module where the key identifier is stored. If none is specified then moodle.php is used.
string | object | array$aAn object, string or number that can be used within translation strings

◆ purge_all_caches()

purge_all_caches ( )

Invalidates browser caches and cached data in temp.

Return values
void

◆ purge_caches()

purge_caches ( $options = [])

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.

Parameters
bool[]$optionsSpecific parts of the cache to purge. Valid options are: 'muc' Purge MUC caches? 'theme' Purge theme cache? 'lang' Purge language string cache? 'js' Purge javascript cache? 'filter' Purge text filter cache? 'other' Purge all other caches?

◆ purge_other_caches()

purge_other_caches ( )

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 phpunit_util::reset_dataroot()

◆ random_string()

random_string ( $length = 15)

Generate and return a random string of the specified length.

Parameters
int$lengthThe length of the string to be created.
Return values
string

◆ rc4decrypt()

rc4decrypt ( $data)

rc4decrypt

Parameters
string$dataData to decrypt.
Return values
stringThe now decrypted data.

◆ rc4encrypt()

rc4encrypt ( $data)

rc4encrypt

Parameters
string$dataData to encrypt.
Return values
stringThe now encrypted data.

◆ remoteip_in_list()

remoteip_in_list ( $list)

Is the current ip in a given list?

Parameters
string$list
Return values
bool

◆ remove_course_contents()

remove_course_contents ( $courseid,
$showfeedback = true,
array $options = null )

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
Parameters
int$courseidThe id of the course that is being deleted
bool$showfeedbackWhether to display notifications of each action the function performs.
array$optionsextra options
Return values
booltrue if all the removals succeeded. false if there were any failures. If this method returns false, some of the removals will probably have succeeded, and others failed, but you have no way of knowing which.

◆ remove_dir()

remove_dir ( $dir,
$contentonly = false )

Delete directory or only its content.

Parameters
string$dirdirectory path
bool$contentonly
Return values
boolsuccess, true also if dir does not exist

◆ rename_to_unused_name()

rename_to_unused_name ( string $filepath,
string $prefix = '_temp_' )

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.

Parameters
string$filepathOriginal filepath
string$prefixPrefix to use for the temporary name
Return values
string|boolNew file path or false if failed
Since
Moodle 3.10

◆ require_admin()

require_admin ( )

A convenience function for where we must be logged in as admin.

Return values
void

◆ require_course_login()

require_course_login ( $courseorid,
$autologinguest = true,
$cm = null,
$setwantsurltome = true,
$preventredirect = false )

Weaker version of require_login()

This is a weaker version of require_login() which only requires login when called from within a course rather than the site page, unless the forcelogin option is turned on.

See also
require_login()
Parameters
mixed$courseoridThe course object or id in question
bool$autologinguestAllow autologin guests if that is wanted
object$cmCourse activity module if known
bool$setwantsurltomeDefine if we want to set $SESSION->wantsurl, defaults to true. Used to avoid (=false) some scripts (file.php...) to set that variable, in order to keep redirects working properly. MDL-14495
bool$preventredirectset to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
Return values
void
Exceptions
coding_exception

◆ require_login()

require_login ( $courseorid = null,
$autologinguest = true,
$cm = null,
$setwantsurltome = true,
$preventredirect = false )

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 $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.

Parameters
mixed$courseoridid of the course or course object
bool$autologinguestdefault true
object$cmcourse module object
bool$setwantsurltomeDefine if we want to set $SESSION->wantsurl, defaults to true. Used to avoid (=false) some scripts (file.php...) to set that variable, in order to keep redirects working properly. MDL-14495
bool$preventredirectset to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
Return values
mixedVoid, exit, and die depending on path
Exceptions
coding_exception
require_login_exception
moodle_exception

◆ require_user_key_login()

require_user_key_login ( $script,
$instance = null,
$keyvalue = null )

Require key login.

Function terminates with error if key not found or incorrect.

@uses NO_MOODLE_COOKIES @uses PARAM_ALPHANUM

Parameters
string$scriptunique script identifier
int$instanceoptional instance id
string$keyvalueThe key. If not supplied, this will be fetched from the current session.
Return values
intInstance ID

◆ required_param()

required_param ( $parname,
$type )

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.

Parameters
string$parnamethe name of the page parameter we want
string$typeexpected type of parameter
Return values
mixed
Exceptions
coding_exception

◆ required_param_array()

required_param_array ( $parname,
$type )

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

Parameters
string$parnamethe name of the page parameter we want
string$typeexpected type of parameter
Return values
array
Exceptions
coding_exception

◆ reset_course_userdata()

reset_course_userdata ( $data)

This function will empty a course of user data.

It will retain the activities and the structure of the course.

Parameters
object$dataan object containing all the settings including courseid (without magic quotes)
Return values
arraystatus array of array component, item, error

◆ reset_password_and_mail()

reset_password_and_mail ( $user)

Resets specified user's password and send the new password to the user via email.

Parameters
stdClass$userA $USER object
Return values
boolReturns true if mail was sent OK and false if there was an error.

◆ send_confirmation_email()

send_confirmation_email ( $user,
$confirmationurl = null )

Send email to specified user with confirmation text and activation link.

Parameters
stdClass$userA $USER object
string$confirmationurluser confirmation URL
Return values
boolReturns true if mail was sent OK and false if there was an error.

◆ send_password_change_confirmation_email()

send_password_change_confirmation_email ( $user,
$resetrecord )

Sends a password change confirmation email.

Parameters
stdClass$userA $USER object
stdClass$resetrecordAn object tracking metadata regarding password reset request
Return values
boolReturns true if mail was sent OK and false if there was an error.

◆ send_password_change_info()

send_password_change_info ( $user)

Sends an email containing information on how to change your password.

Parameters
stdClass$userA $USER object
Return values
boolReturns true if mail was sent OK and false if there was an error.

◆ set_bounce_count()

set_bounce_count ( $user,
$reset = false )

Increment or reset user's email bounce count.

Parameters
stdClass$userobject containing an id
bool$resetwill reset the count to 0

◆ set_cache_flag()

set_cache_flag ( $type,
$name,
$value,
$expiry = null )

Set a volatile flag.

Parameters
string$typethe "type" namespace for the key
string$namethe key to set
string$valuethe value to set (without magic quotes) - null will remove the flag
int$expiry(optional) epoch indicating expiry - defaults to now()+ 24hs
Return values
boolAlways returns true

◆ set_config()

set_config ( $name,
$value,
$plugin = null )

Set a key in global configuration.

Set a key/value pair in both this session's $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

Parameters
string$namethe key to set
string$valuethe value to set (without magic quotes)
string$plugin(optional) the plugin scope, default null
Return values
booltrue or exception

◆ set_mnet_remote_client()

set_mnet_remote_client ( $client)

during the xmlrpc server code execution, this will be called to setup the object returned by get_mnet_remote_client

Parameters
mnet_remote_client$clientthe client to set up
Exceptions
moodle_exception

◆ set_send_count()

set_send_count ( $user,
$reset = false )

Used to increment or reset email sent count.

Parameters
stdClass$userobject containing an id
bool$resetwill reset the count to 0
Return values
void

◆ set_user_preference()

set_user_preference ( $name,
$value,
$user = null )

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 also
useredit_update_user_preference()}
Parameters
string$nameThe key to set as preference for the specified user
string$valueThe value to set for the $name key in the specified user's record, null means delete current value.
stdClass | int | null$userA moodle user object or id, null means current user
Exceptions
coding_exception
Return values
boolAlways true or exception

◆ set_user_preferences()

set_user_preferences ( array $prefarray,
$user = null )

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.

Parameters
array$prefarrayAn array of key/value pairs to be set
stdClass | int | null$userA moodle user object or id, null means current user
Return values
boolAlways true or exception

◆ setnew_password_and_mail()

setnew_password_and_mail ( $user,
$fasthash = false )

Sets specified user's password and send the new password to the user via email.

Parameters
stdClass$userA $USER object
bool$fasthashIf true, use a low cost factor when generating the hash for speed.
Return values
bool|stringReturns "true" if mail was sent OK and "false" if there was an error

◆ shift_course_mod_dates()

shift_course_mod_dates ( $modname,
$fields,
$timeshift,
$courseid,
$modid = 0 )

Change dates in module - used from course reset.

Parameters
string$modnameforum, assignment, etc
array$fieldsarray of date fields from mod table
int$timeshifttime difference
int$courseid
int$modid(Optional) passed if specific mod instance in course needs to be updated.
Return values
boolsuccess

◆ shorten_filename()

shorten_filename ( $filename,
$length = MAX_FILENAME_SIZE,
$includehash = false )

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.

Parameters
string$filenamefile name
int$lengthideal string length
bool$includehashWhether to include a file hash in the shortened version. This ensures uniqueness.
Return values
string\$shortenedshortened file name

◆ shorten_filenames()

shorten_filenames ( array $path,
$length = MAX_FILENAME_SIZE,
$includehash = false )

Shortens a given array of filenames by removing characters positioned after the ideal string length.

Parameters
array$pathThe paths to reduce the length.
int$lengthIdeal string length
bool$includehashWhether to include a file hash in the shortened version. This ensures uniqueness.
Return values
array\$resultShortened paths in array.

◆ shorten_text()

shorten_text ( $text,
$ideal = 30,
$exact = false,
$ending = '...' )

Given some text (which may contain HTML) and an ideal length, this function truncates the text neatly on a word boundary if possible.

Parameters
string$texttext to be shortened
int$idealideal string length
boolean$exactif false, $text will not be cut mid-word
string$endingThe string to append if the passed string is truncated
Return values
string\$truncateshortened string

◆ site_is_public()

site_is_public ( )

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 values
bool

◆ swapshuffle()

swapshuffle ( $array)

Given a simple array, this shuffles it up just like shuffle() Unlike PHP's shuffle() this function works on any machine.

Parameters
array$arrayThe array to be rearranged
Return values
array

◆ swapshuffle_assoc()

swapshuffle_assoc ( $array)

Like swapshuffle(), but works on associative arrays.

Parameters
array$arrayThe associative array to be rearranged
Return values
array

◆ truncate_userinfo()

truncate_userinfo ( array $info)

Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.

Parameters
array$infoArray of user properties to truncate if needed
Return values
arrayThe now truncated information that was passed in

◆ unformat_float()

unformat_float ( $localefloat,
$strict = false )

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!

Parameters
string$localefloatlocale aware float representation
bool$strictIf true, then check the input and return false if it is not a valid number.
Return values
mixedfloat|bool - false or the parsed float.

◆ unserialize_array()

unserialize_array ( $expression)

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.

Parameters
string$expression
Return values
array|booleither parsed array or false if parsing was impossible.

◆ unserialize_object()

unserialize_object ( string $input)

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 also
__PHP_Incomplete_class} for malformed strings
Parameters
string$input
Return values
stdClass

◆ unset_all_config_for_plugin()

unset_all_config_for_plugin ( $plugin)

Remove all the config variables for a given plugin.

NOTE: this function is called from lib/db/upgrade.php

Parameters
string$plugina plugin, for example 'quiz' or 'qtype_multichoice';
Return values
booleanwhether the operation succeeded.

◆ unset_cache_flag()

unset_cache_flag ( $type,
$name )

Removes a single volatile flag.

Parameters
string$typethe "type" namespace for the key
string$namethe key to set
Return values
bool

◆ unset_config()

unset_config ( $name,
$plugin = null )

Removes a key from global configuration.

NOTE: this function is called from lib/db/upgrade.php

Parameters
string$namethe key to set
string$plugin(optional) the plugin scope
Return values
booleanwhether the operation succeeded.

◆ unset_user_preference()

unset_user_preference ( $name,
$user = null )

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.

Parameters
string$nameThe key to unset as preference for the specified user
stdClass | int | null$userA moodle user object or id, null means current user
Exceptions
coding_exception
Return values
boolAlways true or exception

◆ update_internal_user_password()

update_internal_user_password ( stdClass $user,
# ?string $password[\SensitiveParameter],
bool $fasthash = false )

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).

The password is peppered with the latest pepper before hashing, if peppers are available. 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.

Parameters
stdClass$userUser object (password property may be updated).
string | null$passwordPlain text password.
bool$fasthashIf true, use a low cost factor when generating the hash This is much faster to generate but makes the hash less secure. It is used when lots of hashes need to be generated quickly.
Return values
boolAlways returns true.

◆ update_user_login_times()

update_user_login_times ( )

Modify the user table by setting the currently logged in user's last login to now.

Return values
boolAlways returns true

◆ update_user_record()

update_user_record ( $username)

Will update a local user record from an external source (MNET users can not be updated using this method!).

Parameters
string$usernameuser's username to update the record
Return values
stdClassA complete user object

◆ update_user_record_by_id()

update_user_record_by_id ( $id)

Will update a local user record from an external source (MNET users can not be updated using this method!).

Parameters
int$iduser id
Return values
stdClassA complete user object

◆ user_not_fully_set_up()

user_not_fully_set_up ( $user,
$strict = true )

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.

Parameters
stdClass$userA $USER object to test for the existence of a valid name and email
bool$strictBe more strict and assert id and custom profile fields set, too
Return values
bool

◆ user_preference_allow_ajax_update()

user_preference_allow_ajax_update ( $name,
$paramtype )

Library functions to facilitate the use of ajax JavaScript in Moodle.

License
http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later You need to call this function if you wish to use the set_user_preference method in javascript_static.php, to white-list the preference you want to update from JavaScript, and to specify the type of cleaning you expect to be done on values.
Parameters
string$namethe name of the user_perference we should allow to be updated by remote calls.
integer$paramtypeone of the PARAM_{TYPE} constants, user to clean submitted values before set_user_preference is called.
Return values
null
Deprecated
since Moodle 4.3

◆ userdate()

userdate ( $date,
$format = '',
$timezone = 99,
$fixday = true,
$fixhour = true )

Returns a formatted string that represents a date in user time.

Parameters
int$datethe timestamp in UTC, as obtained from the database.
string$formatstrftime format. You should probably get this using get_string('strftime...', 'langconfig');
int | float | string$timezoneby default, uses the user's time zone. if numeric and not 99 then daylight saving will not be added.
bool$fixdayIf true (default) then the leading zero from d is removed. If false then the leading zero is maintained.
bool$fixhourIf true (default) then the leading zero from I is removed.
Return values
stringthe formatted date/time.

◆ userdate_htmltime()

userdate_htmltime ( $date,
$format = '',
$timezone = 99,
$fixday = true,
$fixhour = true )

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.

Parameters
int$datethe timestamp in UTC, as obtained from the database.
string$formatstrftime format. You should probably get this using get_string('strftime...', 'langconfig');
int | float | string$timezoneby default, uses the user's time zone. if numeric and not 99 then daylight saving will not be added.
bool$fixdayIf true (default) then the leading zero from d is removed. If false then the leading zero is maintained.
bool$fixhourIf true (default) then the leading zero from I is removed.
Return values
stringthe formatted date/time.

◆ usergetdate()

usergetdate ( $time,
$timezone = 99 )

Given a $time timestamp in GMT (seconds since epoch), returns an array that represents the Gregorian date in user time.

Parameters
int$timeTimestamp in GMT
float | int | string$timezoneuser timezone
Return values
arrayAn array that represents the date in user time

◆ usergetmidnight()

usergetmidnight ( $date,
$timezone = 99 )

Given a time, return the GMT timestamp of the most recent midnight for the current user.

Parameters
int$dateTimestamp in GMT
float | int | string$timezoneuser timezone
Return values
intReturns a GMT timestamp

◆ username_load_fields_from_object()

username_load_fields_from_object ( $addtoobject,
$secondobject,
$prefix = null,
$additionalfields = null )

Reduces lines of duplicated code for getting user name fields.

See also user_picture::unalias()

Parameters
object$addtoobjectObject to add user name fields to.
object$secondobjectObject that contains user name field information.
string$prefixprefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
array$additionalfieldsAdditional fields to be matched with data in the second object. The key can be set to the user table field name.
Return values
objectUser name fields.

◆ usertime()

usertime ( $date,
$timezone = 99 )

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!

Parameters
int$dateTimestamp in GMT
float | int | string$timezoneuser timezone
Return values
int

◆ usertimezone()

usertimezone ( $timezone = 99)

Returns a string that prints the user's timezone.

Parameters
float | int | string$timezoneuser timezone
Return values
string

◆ valid_uploaded_file()

valid_uploaded_file ( $newfile)

Returns current name of file on disk if it exists.

Parameters
string$newfileFile to be verified
Return values
stringCurrent name of file on disk if true

◆ validate_internal_user_password()

validate_internal_user_password ( stdClass $user,
# string $password[\SensitiveParameter] )

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.

Parameters
stdClass$user(Password property may be updated).
string$passwordPlain text password.
Return values
boolTrue if password is valid.

◆ validate_param()

validate_param ( $param,
$type,
$allownull = NULL_NOT_ALLOWED,
$debuginfo = '' )

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.

Parameters
mixed$param
string$typePARAM_ constant
bool$allownullare nulls valid value?
string$debuginfooptional debug information
Return values
mixedthe $param value converted to PHP type
Exceptions
invalid_parameter_exceptionif $param is not of given type

◆ validate_user_key()

validate_user_key ( $keyvalue,
$script,
$instance )

Validates a user key, checking if the key exists, is not expired and the remote ip is correct.

Parameters
string$keyvaluethe key value
string$scriptunique script identifier
int$instanceinstance id
Return values
stdClassthe key entry in the user_private_key table
Since
Moodle 3.2
Exceptions
moodle_exception

Variable Documentation

◆ defined

defined('HUB_STATSPUBLICKEY')||define('HUB_STATSPUBLICKEY' ( 'HUB_MOODLEORGHUBURL' )

URL of the Moodle sites registration portal.

URL of the statistic server public key.

◆ EXTERNAL_TOKEN_EMBEDDED

const EXTERNAL_TOKEN_EMBEDDED 1

Security token used for allowing access of embedded applications, the code is executed in the active user session.

Token is invalidated after user logs out. Scripts are executed serially - normal session locking is used.

◆ EXTERNAL_TOKEN_PERMANENT

const EXTERNAL_TOKEN_PERMANENT 0

Security token used for allowing access from external application such as web services.

Scripts do not use any session, performance is relatively low because we need to load access info in each request. Scripts are executed in parallel.

◆ FEATURE_GROUPMEMBERSONLY

const FEATURE_GROUPMEMBERSONLY 'groupmembersonly'

True if module supports groupmembersonly (which no longer exists)

Deprecated
Since Moodle 2.8

◆ PAGE_COURSE_VIEW

const PAGE_COURSE_VIEW 'course-view'

PAGE_COURSE_VIEW is a definition of a page type.

For more information on the page class see moodle/lib/pagelib.php.

◆ PARAM_ACTION

const PARAM_ACTION 'alphanumext'

PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls NOTE: originally alias for PARAM_APLHA.

Deprecated
since 2.0

◆ PARAM_AREA

const PARAM_AREA 'area'

PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.

It is usually used together with context id and component. Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.

◆ PARAM_CAPABILITY

const PARAM_CAPABILITY 'capability'

PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'.

Actually checked against the list of capabilities in the database.

◆ PARAM_CLEAN

const PARAM_CLEAN 'clean'

PARAM_CLEAN - obsoleted, please use a more specific type of parameter.

It was one of the first types, that is why it is abused so much ;-)

Deprecated
since 2.0

◆ PARAM_CLEANHTML

const PARAM_CLEANHTML 'cleanhtml'

PARAM_CLEANHTML - cleans submitted HTML code.

Note that you almost never want to use this. The normal mode of operation is to use PARAM_RAW when receiving the input (required/optional_param or formslib) and then sanitise the HTML using format_text on output. This is for the rare cases when you want to sanitise the HTML on input. This cleaning may also fix xhtml strictness.

◆ PARAM_COMPONENT

const PARAM_COMPONENT 'component'

PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.

Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'. Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter. NOTE: numbers and underscores are strongly discouraged in plugin names!

◆ PARAM_FLOAT

const PARAM_FLOAT 'float'

PARAM_FLOAT - a real/floating point number.

Note that you should not use PARAM_FLOAT for numbers typed in by the user. It does not work for languages that use , as a decimal separator. Use PARAM_LOCALISEDFLOAT instead.

◆ PARAM_FORMAT

const PARAM_FORMAT 'alphanumext'

PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.

NOTE: originally alias for PARAM_APLHA

Deprecated
since 2.0

◆ PARAM_INTEGER

const PARAM_INTEGER 'int'

PARAM_INTEGER - deprecated alias for PARAM_INT.

Deprecated
since 2.0

◆ PARAM_LOCALISEDFLOAT

const PARAM_LOCALISEDFLOAT 'localisedfloat'

PARAM_LOCALISEDFLOAT - a localised real/floating point number.

This is preferred over PARAM_FLOAT for numbers typed in by the user. Cleans localised numbers to computer readable numbers; false for invalid numbers.

◆ PARAM_LOCALURL

const PARAM_LOCALURL 'localurl'

PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself.

(NOT orthogonal to the others! Implies PARAM_URL!)

◆ PARAM_MULTILANG

const PARAM_MULTILANG 'text'

PARAM_MULTILANG - deprecated alias of PARAM_TEXT.

Deprecated
since 2.0

◆ PARAM_NOTAGS

const PARAM_NOTAGS 'notags'

PARAM_NOTAGS - all html tags are stripped from the text.

Do not abuse this type.

◆ PARAM_NUMBER

const PARAM_NUMBER 'float'

PARAM_NUMBER - deprecated alias of PARAM_FLOAT.

Deprecated
since 2.0

◆ PARAM_PLUGIN

const PARAM_PLUGIN 'plugin'

PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'paypal', 'completionstatus'.

Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter. NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.

◆ PARAM_SAFEPATH

const PARAM_SAFEPATH 'safepath'

PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths and other references to Moodle code files.

This is NOT intended to be used for absolute paths or any user uploaded files.

◆ PARAM_SEQUENCE

const PARAM_SEQUENCE 'sequence'

PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9.

Numbers and comma only.

◆ PARAM_TEXT

const PARAM_TEXT 'text'

PARAM_TEXT - general plain text compatible with multilang filter, no other html tags.

Please note '<', or '>' are allowed here.

◆ PARAM_TIMEZONE

const PARAM_TIMEZONE 'timezone'

PARAM_TIMEZONE - expected timezone.

Timezone can be int +-(0-13) or float +-(0.5-12.5) or string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem America/Port-au-Prince)

◆ PARAM_URL

const PARAM_URL 'url'

PARAM_URL - expected properly formatted URL.

Please note that domain part is required, http://localhost/ is not accepted but http://localhost.localdomain/ is ok.

◆ PARAM_USERNAME

const PARAM_USERNAME 'username'

PARAM_USERNAME - Clean username to only contains allowed characters.

This is to be used ONLY when manually creating user accounts, do NOT use when syncing with external systems!!

◆ TAG_MAX_LENGTH

const TAG_MAX_LENGTH 50

To prevent problems with multibytes strings,Flag updating in nav not working on the review page.

this should not exceed the length of "varchar(255) / 3 (bytes / utf-8 character) = 85". TODO: this is not correct, varchar(255) are 255 unicode chars ;-)

Todo
define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)