Moodle APIs 4.3
Moodle 4.3.6 (Build: 20240812)
log

Functions

object _fix_course_cats ($children, &$sortorder, $parent, $depth, $path, &$fixcontexts)
 Internal recursive category verification function, do not use directly!
 
moodle_database add_to_config_log ($name, $oldvalue, $value, $plugin)
 Add an entry to the config log table.
 
 decompose_update_into_safe_changes (array $newvalues, $unusedvalue)
 Helper used by update_field_with_unique_index().
 
object fix_course_sortorder ()
 Fixes course category and course sortorder, also verifies category and course parents and paths.
 
 get_admin ()
 Returns $user object of the main admin user.
 
 get_admins ()
 Returns list of all admins, using 1 DB query.
 
 get_all_instances_in_course ($modulename, $course, $userid=NULL, $includeinvisible=false)
 Returns an array of all the active instances of a particular module in a given course, sorted in the order they are defined.
 
object get_all_instances_in_courses ($modulename, $courses, $userid=NULL, $includeinvisible=false)
 Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined.
 
 get_course ($courseid, $clone=true)
 Gets a course object from database.
 
object get_course_mods ($courseid)
 MODULE FUNCTIONS /////////////////////////////////////////////////.
 
object get_coursemodule_from_id ($modulename, $cmid, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING)
 Given an id of a course module, finds the coursemodule description.
 
object get_coursemodule_from_instance ($modulename, $instance, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING)
 Given an instance number of a module, finds the coursemodule description.
 
 get_coursemodules_in_course ($modulename, $courseid, $extrafields='')
 Returns all course modules of given activity in course.
 
object get_courses ($categoryid="all", $sort="c.sortorder ASC", $fields="c.*")
 Returns list of courses, for whole site, or category.
 
object get_courses_search ($searchterms, $sort, $page, $recordsperpage, &$totalcount, $requiredcapabilities=array(), $searchcond=[], $params=[])
 A list of courses that match a search.
 
 get_log_manager ($forcereload=false)
 LOG FUNCTIONS /////////////////////////////////////////////////////.
 
 get_max_courses_in_category ()
 Return maximum number of courses in a category.
 
object get_my_remotecourses ($userid=0)
 List of remote courses that a user has access to via MNET.
 
object get_my_remotehosts ()
 List of remote hosts that a user has access to via MNET.
 
 get_safe_orderby (array $orderbymap, string $orderbykey, string $direction='', bool $useprefix=true)
 Prepare a safe ORDER BY statement from user interactable requests.
 
 get_safe_orderby_multiple (array $orderbymap, array $orderbykeys, array $directions=[])
 Prepare a safe ORDER BY statement from user interactable requests using multiple values.
 
object get_scales_menu ($courseid=0)
 Returns a menu of all available scales from the site as well as the given course.
 
 get_site ()
 OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////.
 
object get_users ($get=true, $search='', $confirmed=false, array $exceptions=null, $sort='firstname ASC', $firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields=' *', $extraselect='', array $extraparams=null)
 Returns a subset of users.
 
object get_users_confirmed ()
 Full list of users that have confirmed their accounts.
 
 get_users_listing ($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0, $search='', $firstinitial='', $lastinitial='', $extraselect='', array $extraparams=null, $extracontext=null)
 Return filtered (if provided) list of users in site, except guest and deleted users.
 
 increment_revision_number ($table, $field, $select, array $params=null)
 Increment standard revision field.
 
object instance_is_visible ($moduletype, $module)
 Determine whether a module instance is visible within a course.
 
 print_object ($item, array $expandclasses=['/./'], bool $textonly=false, bool $return=false, int $depth=0, array $done=[])
 GENERAL HELPFUL THINGS ///////////////////////////////////.
 
object search_users ($courseid, $groupid, $searchtext, $sort='', array $exceptions=null)
 Search through course users.
 
 update_field_with_unique_index ($table, $field, array $newvalues, array $otherconditions, $unusedvalue=-1)
 This method can update the values in mulitple database rows for a colum with a unique index, without violating that constraint.
 
stdClass user_accesstime_log ($courseid=0)
 Store user last access times - called when use enters a course or site.
 
object user_can_create_courses ()
 @uses CONTEXT_COURSECAT
 
 users_order_by_sql (string $usertablealias='', string $search=null, context $context=null, array $customfieldmappings=[])
 This function generates the standard ORDER BY clause for use when generating lists of users.
 
 users_search_sql (string $search, string $u='u', int $searchtype=USER_SEARCH_STARTS_WITH, array $extrafields=[], array $exclude=null, array $includeonly=null)
 Returns SQL used to search through user table to find users (in a query which may also join and apply other conditions).
 
 xmldb_debug ($message, $object)
 This function is the official hook inside XMLDB stuff to delegate its debug to one external function.
 

Variables

global $DB
 
 $logs
 
const MAX_COURSE_CATEGORIES 10000
 The maximum number of course categories MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
 
const MAX_COURSES_IN_CATEGORY 10000
 The maximum courses in a category MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
 
const USER_SEARCH_CONTAINS 1
 
const USER_SEARCH_EXACT_MATCH 2
 
const USER_SEARCH_STARTS_WITH (!defined('LASTACCESS_UPDATE_SECS')) 0
 Number of seconds to wait before updating lastaccess information in DB.
 

Detailed Description

Function Documentation

◆ _fix_course_cats()

object _fix_course_cats ( $children,
& $sortorder,
$parent,
$depth,
$path,
& $fixcontexts )

Internal recursive category verification function, do not use directly!

Todo
Document the arguments of this function better

@uses CONTEXT_COURSECAT

Parameters
array$children
int$sortorder
string$parent
int$depth
string$path
array$fixcontexts
Return values
boolif changes were made

◆ add_to_config_log()

moodle_database add_to_config_log ( $name,
$oldvalue,
$value,
$plugin )

Add an entry to the config log table.

These are "action" focussed rather than web server hits, and provide a way to easily reconstruct changes to Moodle configuration.

$DB @global stdClass $USER

Parameters
string$nameThe name of the configuration change action For example 'filter_active' when activating or deactivating a filter
string$oldvalueThe config setting's previous value
string$valueThe config setting's new value
string$pluginPlugin name, for example a filter name when changing filter configuration
Return values
void

◆ decompose_update_into_safe_changes()

decompose_update_into_safe_changes ( array $newvalues,
$unusedvalue )

Helper used by update_field_with_unique_index().

Given a desired set of changes, break them down into single udpates that can be done one at a time without breaking any unique index constraints.

Suppose the input is array(1 => 2, 2 => 1) and -1. Then the output will be array (array(1, -1), array(2, 1), array(-1, 2)). This function solves this problem in the general case, not just for simple swaps. The unit tests give more examples.

Note that, it is the responsibility of the caller to make sure that the requested rename is legal. For example, if you ask for something impossible like array(1 => 2, 2 => 2) then the results are undefined. (You will probably get a unique key violation error from the database later.)

Parameters
array$newvaluesThe desired re-ordering. E.g. array(1 => 4, 2 => 1, 3 => 3, 4 => 2).
int$unusedvalueA value that is not currently used.
Return values
arrayA safe way to perform the re-order. An array of two-element arrays array($from, $to). E.g. array(array(1, -1), array(2, 1), array(4, 2), array(-1, 4)).

◆ fix_course_sortorder()

object fix_course_sortorder ( )

Fixes course category and course sortorder, also verifies category and course parents and paths.

(circular references are not fixed)

@global object @uses MAX_COURSE_CATEGORIES @uses SITEID @uses CONTEXT_COURSE

Return values
void

◆ get_admin()

get_admin ( )
static

Returns $user object of the main admin user.

stdClass $mainadmin

Return values
stdClass$USER record from DB, false if not found

◆ get_admins()

get_admins ( )

Returns list of all admins, using 1 DB query.

Return values
array

◆ get_all_instances_in_course()

get_all_instances_in_course ( $modulename,
$course,
$userid = NULL,
$includeinvisible = false )

Returns an array of all the active instances of a particular module in a given course, sorted in the order they are defined.

Returns an array of all the active instances of a particular module in a given course, sorted in the order they are defined in the course. Returns an empty array on any errors.

The returned objects includle the columns cw.section, cm.visible, cm.groupmode, and cm.groupingid, and are indexed by cm.id.

Simply calls all_instances_in_courses() with a single provided course

Parameters
string$modulenameThe name of the module to get instances for
object$courseThe course obect.
Return values
arrayof module instance objects, including some extra fields from the course_modules and course_sections tables, or an empty array if an error occurred.
Parameters
int$userid
int$includeinvisible

◆ get_all_instances_in_courses()

object get_all_instances_in_courses ( $modulename,
$courses,
$userid = NULL,
$includeinvisible = false )

Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined.

Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined in the course. Returns an empty array on any errors.

The returned objects includle the columns cw.section, cm.visible, cm.groupmode, cm.groupingid and cm.lang and are indexed by cm.id.

@global object

Parameters
string$modulenameThe name of the module to get instances for
array$coursesan array of course objects.
int$userid
int$includeinvisible
Return values
arrayof module instance objects, including some extra fields from the course_modules and course_sections tables, or an empty array if an error occurred.

◆ get_course()

get_course ( $courseid,
$clone = true )

Gets a course object from database.

If the course id corresponds to an already-loaded $COURSE or $SITE object, then the loaded object will be used, saving a database query.

If it reuses an existing object, by default the object will be cloned. This means you can modify the object safely without affecting other code.

Parameters
int$courseidCourse id
bool$cloneIf true (default), makes a clone of the record
Return values
stdClassA course object
Exceptions
dml_exceptionIf not found in database

◆ get_course_mods()

object get_course_mods ( $courseid)

MODULE FUNCTIONS /////////////////////////////////////////////////.

Just gets a raw list of all modules in a course

Parameters
int$courseidThe id of the course as found in the 'course' table.
Return values
array

◆ get_coursemodule_from_id()

object get_coursemodule_from_id ( $modulename,
$cmid,
$courseid = 0,
$sectionnum = false,
$strictness = IGNORE_MISSING )

Given an id of a course module, finds the coursemodule description.

Please note that this function performs 1-2 DB queries. When possible use cached course modinfo. For example get_fast_modinfo($courseorid)->get_cm($cmid) See also cm_info::get_course_module_record()

Parameters
string$modulenamename of module type, eg. resource, assignment,... (optional, slower and less safe if not specified)
int$cmidcourse module id (id in course_modules table)
int$courseidoptional course id for extra validation
bool$sectionnuminclude relative section number (0,1,2 ...)
int$strictnessIGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found; IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended); MUST_EXIST means throw exception if no record or multiple records found
Return values
stdClass

◆ get_coursemodule_from_instance()

object get_coursemodule_from_instance ( $modulename,
$instance,
$courseid = 0,
$sectionnum = false,
$strictness = IGNORE_MISSING )

Given an instance number of a module, finds the coursemodule description.

Please note that this function performs DB query. When possible use cached course modinfo. For example get_fast_modinfo($courseorid)->instances[$modulename][$instance] See also cm_info::get_course_module_record()

Parameters
string$modulenamename of module type, eg. resource, assignment,...
int$instancemodule instance number (id in resource, assignment etc. table)
int$courseidoptional course id for extra validation
bool$sectionnuminclude relative section number (0,1,2 ...)
int$strictnessIGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found; IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended); MUST_EXIST means throw exception if no record or multiple records found
Return values
stdClass

◆ get_coursemodules_in_course()

get_coursemodules_in_course ( $modulename,
$courseid,
$extrafields = '' )

Returns all course modules of given activity in course.

Parameters
string$modulenameThe module name (forum, quiz, etc.)
int$courseidThe course id to get modules for
string$extrafieldsextra fields starting with m.
Return values
arrayArray of results

◆ get_courses()

object get_courses ( $categoryid = "all",
$sort = "c.sortorder ASC",
$fields = "c.*" )

Returns list of courses, for whole site, or category.

Returns list of courses, for whole site, or category Important: Using c.* for fields is extremely expensive because we are using distinct. You almost NEVER need all the fields in such a large SELECT

Consider using core_course_category\get_courses() or core_course_category\search_courses() instead since they use caching.

@global object @global object @uses CONTEXT_COURSE

Parameters
string | int$categoryidEither a category id or 'all' for everything
string$sortA field and direction to sort by
string$fieldsThe additional fields to return (note that "id, category, visible" are always present)
Return values
arrayArray of courses

◆ get_courses_search()

object get_courses_search ( $searchterms,
$sort,
$page,
$recordsperpage,
& $totalcount,
$requiredcapabilities = array(),
$searchcond = [],
$params = [] )

A list of courses that match a search.

@global object

Parameters
array$searchtermsAn array of search criteria
string$sortA field and direction to sort by
int$pageThe page number to get
int$recordsperpageThe number of records per page
int$totalcountPassed in by reference.
array$requiredcapabilitiesExtra list of capabilities used to filter courses
array$searchcondadditional search conditions, for example ['c.enablecompletion = :p1']
array$paramsnamed parameters for additional search conditions, for example ['p1' => 1]
Return values
stdClass[]$COURSE records

◆ get_log_manager()

get_log_manager ( $forcereload = false)

LOG FUNCTIONS /////////////////////////////////////////////////////.

Get instance of log manager.

Parameters
bool$forcereload
Return values
core\log\manager

◆ get_max_courses_in_category()

get_max_courses_in_category ( )

Return maximum number of courses in a category.

@uses MAX_COURSES_IN_CATEGORY

Return values
intnumber of courses

◆ get_my_remotecourses()

object get_my_remotecourses ( $userid = 0)

List of remote courses that a user has access to via MNET.

Works only on the IDP

@global object

Parameters
int@userid The user id to get remote courses for
Return values
arrayArray of $COURSE of course objects

◆ get_my_remotehosts()

object get_my_remotehosts ( )

List of remote hosts that a user has access to via MNET.

Works on the SP

@global object

Return values
array|boolArray of host objects or false

◆ get_safe_orderby()

get_safe_orderby ( array $orderbymap,
string $orderbykey,
string $direction = '',
bool $useprefix = true )

Prepare a safe ORDER BY statement from user interactable requests.

This allows safe user specified sorting (ORDER BY), by abstracting the SQL from the value being requested by the user. A standard string (and optional direction) can be specified, which will be mapped to a predefined allow list of SQL ordering. The mapping can optionally include a 'default', which will be used if the key provided is invalid.

Example usage: -If $orderbymap = [ 'courseid' => 'c.id', 'somecustomvalue'=> 'c.startdate, c.shortname', 'default' => 'c.fullname', ] -A value from the map array's keys can be passed in by a user interaction (eg web service) along with an optional direction. -get_safe_orderby($orderbymap, 'courseid', 'DESC') would return: ORDER BY c.id DESC -get_safe_orderby($orderbymap, 'somecustomvalue') would return: ORDER BY c.startdate, c.shortname -get_safe_orderby($orderbymap, 'invalidblah', 'DESC') would return: ORDER BY c.fullname DESC -If no default key was specified in $orderbymap, the invalidblah example above would return empty string.

Parameters
array$orderbymapAn array in the format [keystring => sqlstring]. A default fallback can be set with the key 'default'.
string$orderbykeyA string to be mapped to a key in $orderbymap.
string$directionOptional ORDER BY direction (ASC/DESC, case insensitive).
bool$useprefixWhether ORDER BY is prefixed to the output (true by default). This should not be modified in most cases. It is included to enable get_safe_orderby_multiple() to use this function multiple times.
Return values
stringThe ORDER BY statement, or empty string if $orderbykey is invalid and no default is mapped.

◆ get_safe_orderby_multiple()

get_safe_orderby_multiple ( array $orderbymap,
array $orderbykeys,
array $directions = [] )

Prepare a safe ORDER BY statement from user interactable requests using multiple values.

This allows safe user specified sorting (ORDER BY) similar to get_safe_orderby(), but supports multiple keys and directions. This is useful in cases where combinations of columns are needed and/or each item requires a specified direction (ASC/DESC). The mapping can optionally include a 'default', which will be used if the key provided is invalid.

Example usage: -If $orderbymap = [ 'courseid' => 'c.id', 'fullname'=> 'c.fullname', 'default' => 'c.startdate', ] -An array of values from the map's keys can be passed in by a user interaction (eg web service), with optional directions. -get_safe_orderby($orderbymap, ['courseid', 'fullname'], ['DESC', 'ASC']) would return: ORDER BY c.id DESC, c.fullname ASC -get_safe_orderby($orderbymap, ['courseid', 'invalidblah'], ['aaa', 'DESC']) would return: ORDER BY c.id, c.startdate DESC -If no default key was specified in $orderbymap, the invalidblah example above would return: ORDER BY c.id

Parameters
array$orderbymapAn array in the format [keystring => sqlstring]. A default fallback can be set with the key 'default'.
array$orderbykeysAn array of strings to be mapped to keys in $orderbymap.
array$directionsOptional array of ORDER BY direction (ASC/DESC, case insensitive). The array keys should match array keys in $orderbykeys.
Return values
stringThe ORDER BY statement, or empty string if $orderbykeys contains no valid items and no default is mapped.

◆ get_scales_menu()

object get_scales_menu ( $courseid = 0)

Returns a menu of all available scales from the site as well as the given course.

Parameters
int$courseidThe id of the course as found in the 'course' table.
Return values
array

◆ get_site()

get_site ( )

OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////.

Returns $course object of the top-level site.

Return values
objectA $COURSE object for the site, exception if not found

◆ get_users()

object get_users ( $get = true,
$search = '',
$confirmed = false,
array $exceptions = null,
$sort = 'firstname ASC',
$firstinitial = '',
$lastinitial = '',
$page = '',
$recordsperpage = '',
$fields = '*',
$extraselect = '',
array $extraparams = null )

Returns a subset of users.

@uses DEBUG_DEVELOPER @uses SQL_PARAMS_NAMED

Parameters
bool$getIf false then only a count of the records is returned
string$searchA simple string to search for
bool$confirmedA switch to allow/disallow unconfirmed users
array$exceptionsA list of IDs to ignore, eg 2,4,5,8,9,10
string$sortA SQL snippet for the sorting criteria to use
string$firstinitialUsers whose first name starts with $firstinitial
string$lastinitialUsers whose last name starts with $lastinitial
string$pageThe page or records to return
string$recordsperpageThe number of records to return per page
string$fieldsA comma separated list of fields to be returned from the chosen table.
Return values
array|int|bool$USER records unless get is false in which case the integer count of the records found is returned. False is returned if an error is encountered.

◆ get_users_confirmed()

object get_users_confirmed ( )

Full list of users that have confirmed their accounts.

Return values
arrayof unconfirmed users

◆ get_users_listing()

get_users_listing ( $sort = 'lastaccess',
$dir = 'ASC',
$page = 0,
$recordsperpage = 0,
$search = '',
$firstinitial = '',
$lastinitial = '',
$extraselect = '',
array $extraparams = null,
$extracontext = null )

Return filtered (if provided) list of users in site, except guest and deleted users.

Parameters
string$sortAn SQL field to sort by
string$dirThe sort direction ASC|DESC
int$pageThe page or records to return
int$recordsperpageThe number of records to return per page
string$searchA simple string to search for
string$firstinitialUsers whose first name starts with $firstinitial
string$lastinitialUsers whose last name starts with $lastinitial
string$extraselectAn additional SQL select statement to append to the query
array$extraparamsAdditional parameters to use for the above $extraselect
stdClass$extracontextIf specified, will include user 'extra fields' as appropriate for current user and given context
Return values
arrayArray of $USER records

◆ increment_revision_number()

increment_revision_number ( $table,
$field,
$select,
array $params = null )

Increment standard revision field.

The revision are based on current time and are incrementing. There is a protection for runaway revisions, it may not go further than one hour into future.

The field has to be XMLDB_TYPE_INTEGER with size 10.

Parameters
string$table
string$fieldname of the field containing revision
string$selectuse empty string when updating all records
array$paramsoptional select parameters

◆ instance_is_visible()

object instance_is_visible ( $moduletype,
$module )

Determine whether a module instance is visible within a course.

Given a valid module object with info about the id and course, and the module's type (eg "forum") returns whether the object is visible or not according to the 'eye' icon only.

NOTE: This does NOT take into account visibility to a particular user. To get visibility access for a specific user, use get_fast_modinfo, get a cm_info object from this, and check the ->uservisible property; or use the core_availability\info_module\is_user_visible() static function.

Parameters
$moduletypeName of the module eg 'forum'
$moduleObject which is the instance of the module
Return values
boolSuccess

◆ print_object()

print_object ( $item,
array $expandclasses = ['/./'],
bool $textonly = false,
bool $return = false,
int $depth = 0,
array $done = [] )

GENERAL HELPFUL THINGS ///////////////////////////////////.

Dumps a given object's information for debugging purposes. (You can actually use this function to print any type of value such as arrays or simple strings, not just objects.)

When used in a web script, the object is dumped in a fancy-formatted div.

When used in a CLI script, the object's information is written to the standard error output stream.

When used in an AJAX script, the object's information is dumped to the server error log.

In text mode, private fields are shown with * and protected with +.

In web view, formatting is done with Bootstrap classes. You can hover over some items to see more information, such as value types or access controls, or full field names if the names get cut off.

By default, this will recurse to child objects, except where that would result in infinite recursion. To change that, set $expandclasses to an empty array (= do not recurse) or to a list of the class names that you would like to expand. You can also set values in this array to a regular expression beginning with / if you want to match a range of classes.

Parameters
mixed$itemObject, array, or other item to display
string[]$expandclassesOptional list of class patterns to recurse to
bool$textonlyIf true, outputs text-only (automatically set for CLI and AJAX)
bool$returnFor internal use - if true, returns value instead of echoing it
int$depthFor internal use - depth of recursion within print_object call
stdClass[]$doneFor internal use - array listing already-printed objects
Return values
stringHTML code (or text if CLI) to display, if $return is true, otherwise empty string

◆ search_users()

object search_users ( $courseid,
$groupid,
$searchtext,
$sort = '',
array $exceptions = null )

Search through course users.

If $coursid specifies the site course then this function searches through all undeleted and confirmed users

@uses SITEID @uses SQL_PARAMS_NAMED @uses CONTEXT_COURSE

Parameters
int$courseidThe course in question.
int$groupidThe group in question.
string$searchtextThe string to search for
string$sortA field to sort by
array$exceptionsA list of IDs to ignore, eg 2,4,5,8,9,10
Return values
array

◆ update_field_with_unique_index()

update_field_with_unique_index ( $table,
$field,
array $newvalues,
array $otherconditions,
$unusedvalue = -1 )

This method can update the values in mulitple database rows for a colum with a unique index, without violating that constraint.

Suppose we have a table with a unique index on (otherid, sortorder), and for a particular value of otherid, we want to change all the sort orders. You have to do this carefully or you will violate the unique index at some time. This method takes care of the details for you.

Note that, it is the responsibility of the caller to make sure that the requested rename is legal. For example, if you ask for [1 => 2, 2 => 2] then you will get a unique key violation error from the database.

Parameters
string$tableThe database table to modify.
string$fieldthe field that contains the values we are going to change.
array$newvaluesoldvalue => newvalue how to change the values. E.g. [1 => 4, 2 => 1, 3 => 3, 4 => 2].
array$otherconditionsarray fieldname => requestedvalue extra WHERE clause conditions to restrict which rows are affected. E.g. array('otherid' => 123).
int$unusedvalue(defaults to -1) a value that is never used in $ordercol.

◆ user_accesstime_log()

stdClass user_accesstime_log ( $courseid = 0)

Store user last access times - called when use enters a course or site.

$USER @global stdClass $CFG @global moodle_database $DB @uses LASTACCESS_UPDATE_SECS @uses SITEID

Parameters
int$courseidempty courseid means site
Return values
void

◆ user_can_create_courses()

object user_can_create_courses ( )

@uses CONTEXT_COURSECAT

Return values
booleanWhether the user can create courses in any category in the system.

◆ users_order_by_sql()

users_order_by_sql ( string $usertablealias = '',
string $search = null,
context $context = null,
array $customfieldmappings = [] )

This function generates the standard ORDER BY clause for use when generating lists of users.

If you don't have a reason to use a different order, then you should use this method to generate the order when displaying lists of users.

If the optional $search parameter is passed, then exact matches to the search will be sorted first. For example, suppose you have two users 'Al Zebra' and 'Alan Aardvark'. The default sort is Alan, then Al. If, however, you search for 'Al', then Al will be listed first. (With two users, this is not a big deal, but with thousands of users, it is essential.)

The list of fields scanned for exact matches are:

If named parameters are used (which is the default, and highly recommended), then the parameter names are like :usersortexactN, where N is an int.

The simplest possible example use is: list($sort, $params) = users_order_by_sql(); $sql = 'SELECT * FROM {users} ORDER BY ' . $sort;

A more complex example, showing that this sort can be combined with other sorts: list($sort, $sortparams) = users_order_by_sql('u'); $sql = "SELECT g.id AS groupid, gg.groupingid, u.id AS userid, u.firstname, u.lastname, u.idnumber, u.username FROM {groups} g LEFT JOIN {groupings_groups} gg ON g.id = gg.groupid LEFT JOIN {groups_members} gm ON g.id = gm.groupid LEFT JOIN {user} u ON gm.userid = u.id WHERE g.courseid = :courseid $groupwhere $groupingwhere ORDER BY g.name, $sort"; $params += $sortparams;

An example showing the use of $search: list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context()); $order = ' ORDER BY ' . $sort; $params += $sortparams; $availableusers = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage);

Parameters
string$usertablealias(optional) any table prefix for the {users} table. E.g. 'u'.
string$search(optional) a current search string. If given, any exact matches to this string will be sorted first.
context | null$contextthe context we are in. Used by core_user\fields\get_identity_fields. Defaults to $PAGE->context.
array$customfieldmappingsassociative array of mappings for custom fields returned by core_user\fields\get_sql.
Return values
arraywith two elements: string SQL fragment to use in the ORDER BY clause. For example, "firstname, lastname". array of parameters used in the SQL fragment. If $search is not given, this is guaranteed to be an empty array.

◆ users_search_sql()

users_search_sql ( string $search,
string $u = 'u',
int $searchtype = USER_SEARCH_STARTS_WITH,
array $extrafields = [],
array $exclude = null,
array $includeonly = null )

Returns SQL used to search through user table to find users (in a query which may also join and apply other conditions).

You can combine this SQL with an existing query by adding 'AND $sql' to the WHERE clause of your query (where $sql is the first element in the array returned by this function), and merging in the $params array to the parameters of your query (where $params is the second element). Your query should use named parameters such as :param, rather than the question mark style.

There are examples of basic usage in the unit test for this function.

Parameters
string$searchthe text to search for (empty string = find all)
string$uthe table alias for the user table in the query being built. May be ''.
int$searchtypeIf 0(default): searches at start, 1: searches in the middle of names 2: search exact match.
array$extrafieldsArray of extra user fields to include in search, must be prefixed with table alias if they are not in the user table.
array$excludeArray of user ids to exclude (empty = don't exclude)
array$includeonlyIf specified, only returns users that have ids incldued in this array (empty = don't restrict)
Return values
arrayan array with two elements, a fragment of SQL to go in the where clause the query, and an associative array containing any required parameters (using named placeholders).

◆ xmldb_debug()

xmldb_debug ( $message,
$object )

This function is the official hook inside XMLDB stuff to delegate its debug to one external function.

Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)

@uses DEBUG_DEVELOPER

Parameters
string$messagestring contains the error message
object$objectobject XMLDB object that fired the debug

Variable Documentation

◆ USER_SEARCH_STARTS_WITH

const USER_SEARCH_STARTS_WITH(!defined( 'LASTACCESS_UPDATE_SECS')) ( ! defined 'LASTACCESS_UPDATE_SECS') 0

Number of seconds to wait before updating lastaccess information in DB.

We allow overwrites from config.php, useful to ensure coherence in performance tests results.

Note: For web service requests in the external_tokens field, we use a different constant webservice\TOKEN_LASTACCESS_UPDATE_SECS. The constant value when we use the search option.