Moodle APIs 4.3
Moodle 4.3.6 (Build: 20240812)
|
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. | |
object _fix_course_cats | ( | $children, | |
& | $sortorder, | ||
$parent, | |||
$depth, | |||
$path, | |||
& | $fixcontexts ) |
Internal recursive category verification function, do not use directly!
@uses CONTEXT_COURSECAT
array | $children | |
int | $sortorder | |
string | $parent | |
int | $depth | |
string | $path | |
array | $fixcontexts |
bool | if changes were made |
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
string | $name | The name of the configuration change action For example 'filter_active' when activating or deactivating a filter |
string | $oldvalue | The config setting's previous value |
string | $value | The config setting's new value |
string | $plugin | Plugin name, for example a filter name when changing filter configuration |
void |
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.)
array | $newvalues | The desired re-ordering. E.g. array(1 => 4, 2 => 1, 3 => 3, 4 => 2). |
int | $unusedvalue | A value that is not currently used. |
array | A 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)). |
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
void |
|
static |
Returns $user object of the main admin user.
stdClass $mainadmin
stdClass | $USER record from DB, false if not found |
get_admins | ( | ) |
Returns list of all admins, using 1 DB query.
array |
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
string | $modulename | The name of the module to get instances for |
object | $course | The course obect. |
array | of module instance objects, including some extra fields from the course_modules and course_sections tables, or an empty array if an error occurred. |
int | $userid | |
int | $includeinvisible |
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
string | $modulename | The name of the module to get instances for |
array | $courses | an array of course objects. |
int | $userid | |
int | $includeinvisible |
array | of 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 | ( | $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.
int | $courseid | Course id |
bool | $clone | If true (default), makes a clone of the record |
stdClass | A course object |
dml_exception | If not found in database |
object get_course_mods | ( | $courseid | ) |
MODULE FUNCTIONS /////////////////////////////////////////////////.
Just gets a raw list of all modules in a course
int | $courseid | The id of the course as found in the 'course' table. |
array |
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()
string | $modulename | name of module type, eg. resource, assignment,... (optional, slower and less safe if not specified) |
int | $cmid | course module id (id in course_modules table) |
int | $courseid | optional course id for extra validation |
bool | $sectionnum | include relative section number (0,1,2 ...) |
int | $strictness | IGNORE_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 |
stdClass |
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()
string | $modulename | name of module type, eg. resource, assignment,... |
int | $instance | module instance number (id in resource, assignment etc. table) |
int | $courseid | optional course id for extra validation |
bool | $sectionnum | include relative section number (0,1,2 ...) |
int | $strictness | IGNORE_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 |
stdClass |
get_coursemodules_in_course | ( | $modulename, | |
$courseid, | |||
$extrafields = '' ) |
Returns all course modules of given activity in course.
string | $modulename | The module name (forum, quiz, etc.) |
int | $courseid | The course id to get modules for |
string | $extrafields | extra fields starting with m. |
array | Array of results |
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
string | int | $categoryid | Either a category id or 'all' for everything |
string | $sort | A field and direction to sort by |
string | $fields | The additional fields to return (note that "id, category, visible" are always present) |
array | Array of courses |
object get_courses_search | ( | $searchterms, | |
$sort, | |||
$page, | |||
$recordsperpage, | |||
& | $totalcount, | ||
$requiredcapabilities = array(), | |||
$searchcond = [], | |||
$params = [] ) |
A list of courses that match a search.
@global object
array | $searchterms | An array of search criteria |
string | $sort | A field and direction to sort by |
int | $page | The page number to get |
int | $recordsperpage | The number of records per page |
int | $totalcount | Passed in by reference. |
array | $requiredcapabilities | Extra list of capabilities used to filter courses |
array | $searchcond | additional search conditions, for example ['c.enablecompletion = :p1'] |
array | $params | named parameters for additional search conditions, for example ['p1' => 1] |
stdClass[] | $COURSE records |
get_log_manager | ( | $forcereload = false | ) |
LOG FUNCTIONS /////////////////////////////////////////////////////.
Get instance of log manager.
bool | $forcereload |
core\log\manager |
get_max_courses_in_category | ( | ) |
Return maximum number of courses in a category.
@uses MAX_COURSES_IN_CATEGORY
int | number of courses |
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
int | @userid The user id to get remote courses for |
array | Array of $COURSE of course objects |
object get_my_remotehosts | ( | ) |
List of remote hosts that a user has access to via MNET.
Works on the SP
@global object
array|bool | Array of host objects or false |
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.
array | $orderbymap | An array in the format [keystring => sqlstring]. A default fallback can be set with the key 'default'. |
string | $orderbykey | A string to be mapped to a key in $orderbymap. |
string | $direction | Optional ORDER BY direction (ASC/DESC, case insensitive). |
bool | $useprefix | Whether 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. |
string | The ORDER BY statement, or empty string if $orderbykey is invalid and no default is mapped. |
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
array | $orderbymap | An array in the format [keystring => sqlstring]. A default fallback can be set with the key 'default'. |
array | $orderbykeys | An array of strings to be mapped to keys in $orderbymap. |
array | $directions | Optional array of ORDER BY direction (ASC/DESC, case insensitive). The array keys should match array keys in $orderbykeys. |
string | The ORDER BY statement, or empty string if $orderbykeys contains no valid items and no default is mapped. |
object get_scales_menu | ( | $courseid = 0 | ) |
Returns a menu of all available scales from the site as well as the given course.
int | $courseid | The id of the course as found in the 'course' table. |
array |
get_site | ( | ) |
OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////.
Returns $course object of the top-level site.
object | A $COURSE object for the site, exception if not found |
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
bool | $get | If false then only a count of the records is returned |
string | $search | A simple string to search for |
bool | $confirmed | A switch to allow/disallow unconfirmed users |
array | $exceptions | A list of IDs to ignore, eg 2,4,5,8,9,10 |
string | $sort | A SQL snippet for the sorting criteria to use |
string | $firstinitial | Users whose first name starts with $firstinitial |
string | $lastinitial | Users whose last name starts with $lastinitial |
string | $page | The page or records to return |
string | $recordsperpage | The number of records to return per page |
string | $fields | A comma separated list of fields to be returned from the chosen table. |
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. |
object get_users_confirmed | ( | ) |
Full list of users that have confirmed their accounts.
array | of unconfirmed users |
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.
string | $sort | An SQL field to sort by |
string | $dir | The sort direction ASC|DESC |
int | $page | The page or records to return |
int | $recordsperpage | The number of records to return per page |
string | $search | A simple string to search for |
string | $firstinitial | Users whose first name starts with $firstinitial |
string | $lastinitial | Users whose last name starts with $lastinitial |
string | $extraselect | An additional SQL select statement to append to the query |
array | $extraparams | Additional parameters to use for the above $extraselect |
stdClass | $extracontext | If specified, will include user 'extra fields' as appropriate for current user and given context |
array | Array of $USER records |
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.
string | $table | |
string | $field | name of the field containing revision |
string | $select | use empty string when updating all records |
array | $params | optional select parameters |
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.
$moduletype | Name of the module eg 'forum' |
$module | Object which is the instance of the module |
bool | Success |
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.
mixed | $item | Object, array, or other item to display |
string[] | $expandclasses | Optional list of class patterns to recurse to |
bool | $textonly | If true, outputs text-only (automatically set for CLI and AJAX) |
bool | $return | For internal use - if true, returns value instead of echoing it |
int | $depth | For internal use - depth of recursion within print_object call |
stdClass[] | $done | For internal use - array listing already-printed objects |
string | HTML code (or text if CLI) to display, if $return is true, otherwise empty string |
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
int | $courseid | The course in question. |
int | $groupid | The group in question. |
string | $searchtext | The string to search for |
string | $sort | A field to sort by |
array | $exceptions | A list of IDs to ignore, eg 2,4,5,8,9,10 |
array |
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.
string | $table | The database table to modify. |
string | $field | the field that contains the values we are going to change. |
array | $newvalues | oldvalue => newvalue how to change the values. E.g. [1 => 4, 2 => 1, 3 => 3, 4 => 2]. |
array | $otherconditions | array 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. |
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
int | $courseid | empty courseid means site |
void |
object user_can_create_courses | ( | ) |
@uses CONTEXT_COURSECAT
boolean | Whether the user can create courses in any category in the system. |
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);
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 | $context | the context we are in. Used by core_user\fields\get_identity_fields. Defaults to $PAGE->context. |
array | $customfieldmappings | associative array of mappings for custom fields returned by core_user\fields\get_sql. |
array | with 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 | ( | 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.
string | $search | the text to search for (empty string = find all) |
string | $u | the table alias for the user table in the query being built. May be ''. |
int | $searchtype | If 0(default): searches at start, 1: searches in the middle of names 2: search exact match. |
array | $extrafields | Array of extra user fields to include in search, must be prefixed with table alias if they are not in the user table. |
array | $exclude | Array of user ids to exclude (empty = don't exclude) |
array | $includeonly | If specified, only returns users that have ids incldued in this array (empty = don't restrict) |
array | an 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 | ( | $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
string | $message | string contains the error message |
object | $object | object XMLDB object that fired the debug |
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.