Merge branch 'MDL-75176' of https://github.com/call-learning/moodle
[moodle.git] / lib / datalib.php
blobee55a2ee337c56e9f04e7827d883050213a6faa0
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Library of functions for database manipulation.
20 * Other main libraries:
21 * - weblib.php - functions that produce web output
22 * - moodlelib.php - general-purpose Moodle functions
24 * @package core
25 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
31 /**
32 * The maximum courses in a category
33 * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
35 define('MAX_COURSES_IN_CATEGORY', 10000);
37 /**
38 * The maximum number of course categories
39 * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
41 define('MAX_COURSE_CATEGORIES', 10000);
43 /**
44 * Number of seconds to wait before updating lastaccess information in DB.
46 * We allow overwrites from config.php, useful to ensure coherence in performance
47 * tests results.
49 * Note: For web service requests in the external_tokens field, we use a different constant
50 * webservice::TOKEN_LASTACCESS_UPDATE_SECS.
52 if (!defined('LASTACCESS_UPDATE_SECS')) {
53 define('LASTACCESS_UPDATE_SECS', 60);
56 /**
57 * Returns $user object of the main admin user
59 * @static stdClass $mainadmin
60 * @return stdClass {@link $USER} record from DB, false if not found
62 function get_admin() {
63 global $CFG, $DB;
65 static $mainadmin = null;
66 static $prevadmins = null;
68 if (empty($CFG->siteadmins)) {
69 // Should not happen on an ordinary site.
70 // It does however happen during unit tests.
71 return false;
74 if (isset($mainadmin) and $prevadmins === $CFG->siteadmins) {
75 return clone($mainadmin);
78 $mainadmin = null;
80 foreach (explode(',', $CFG->siteadmins) as $id) {
81 if ($user = $DB->get_record('user', array('id'=>$id, 'deleted'=>0))) {
82 $mainadmin = $user;
83 break;
87 if ($mainadmin) {
88 $prevadmins = $CFG->siteadmins;
89 return clone($mainadmin);
90 } else {
91 // this should not happen
92 return false;
96 /**
97 * Returns list of all admins, using 1 DB query
99 * @return array
101 function get_admins() {
102 global $DB, $CFG;
104 if (empty($CFG->siteadmins)) { // Should not happen on an ordinary site
105 return array();
108 $sql = "SELECT u.*
109 FROM {user} u
110 WHERE u.deleted = 0 AND u.id IN ($CFG->siteadmins)";
112 // We want the same order as in $CFG->siteadmins.
113 $records = $DB->get_records_sql($sql);
114 $admins = array();
115 foreach (explode(',', $CFG->siteadmins) as $id) {
116 $id = (int)$id;
117 if (!isset($records[$id])) {
118 // User does not exist, this should not happen.
119 continue;
121 $admins[$records[$id]->id] = $records[$id];
124 return $admins;
128 * Search through course users
130 * If $coursid specifies the site course then this function searches
131 * through all undeleted and confirmed users
133 * @global object
134 * @uses SITEID
135 * @uses SQL_PARAMS_NAMED
136 * @uses CONTEXT_COURSE
137 * @param int $courseid The course in question.
138 * @param int $groupid The group in question.
139 * @param string $searchtext The string to search for
140 * @param string $sort A field to sort by
141 * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
142 * @return array
144 function search_users($courseid, $groupid, $searchtext, $sort='', array $exceptions=null) {
145 global $DB;
147 $fullname = $DB->sql_fullname('u.firstname', 'u.lastname');
149 if (!empty($exceptions)) {
150 list($exceptions, $params) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex', false);
151 $except = "AND u.id $exceptions";
152 } else {
153 $except = "";
154 $params = array();
157 if (!empty($sort)) {
158 $order = "ORDER BY $sort";
159 } else {
160 $order = "";
163 $select = "u.deleted = 0 AND u.confirmed = 1 AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('u.email', ':search2', false).")";
164 $params['search1'] = "%$searchtext%";
165 $params['search2'] = "%$searchtext%";
167 if (!$courseid or $courseid == SITEID) {
168 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
169 FROM {user} u
170 WHERE $select
171 $except
172 $order";
173 return $DB->get_records_sql($sql, $params);
175 } else {
176 if ($groupid) {
177 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
178 FROM {user} u
179 JOIN {groups_members} gm ON gm.userid = u.id
180 WHERE $select AND gm.groupid = :groupid
181 $except
182 $order";
183 $params['groupid'] = $groupid;
184 return $DB->get_records_sql($sql, $params);
186 } else {
187 $context = context_course::instance($courseid);
189 // We want to query both the current context and parent contexts.
190 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
192 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
193 FROM {user} u
194 JOIN {role_assignments} ra ON ra.userid = u.id
195 WHERE $select AND ra.contextid $relatedctxsql
196 $except
197 $order";
198 $params = array_merge($params, $relatedctxparams);
199 return $DB->get_records_sql($sql, $params);
205 * Returns SQL used to search through user table to find users (in a query
206 * which may also join and apply other conditions).
208 * You can combine this SQL with an existing query by adding 'AND $sql' to the
209 * WHERE clause of your query (where $sql is the first element in the array
210 * returned by this function), and merging in the $params array to the parameters
211 * of your query (where $params is the second element). Your query should use
212 * named parameters such as :param, rather than the question mark style.
214 * There are examples of basic usage in the unit test for this function.
216 * @param string $search the text to search for (empty string = find all)
217 * @param string $u the table alias for the user table in the query being
218 * built. May be ''.
219 * @param bool $searchanywhere If true (default), searches in the middle of
220 * names, otherwise only searches at start
221 * @param array $extrafields Array of extra user fields to include in search, must be prefixed with table alias if they are not in
222 * the user table.
223 * @param array $exclude Array of user ids to exclude (empty = don't exclude)
224 * @param array $includeonly If specified, only returns users that have ids
225 * incldued in this array (empty = don't restrict)
226 * @return array an array with two elements, a fragment of SQL to go in the
227 * where clause the query, and an associative array containing any required
228 * parameters (using named placeholders).
230 function users_search_sql(string $search, string $u = 'u', bool $searchanywhere = true, array $extrafields = [],
231 array $exclude = null, array $includeonly = null): array {
232 global $DB, $CFG;
233 $params = array();
234 $tests = array();
236 if ($u) {
237 $u .= '.';
240 // If we have a $search string, put a field LIKE '$search%' condition on each field.
241 if ($search) {
242 $conditions = array(
243 $DB->sql_fullname($u . 'firstname', $u . 'lastname'),
244 $conditions[] = $u . 'lastname'
246 foreach ($extrafields as $field) {
247 // Add the table alias for the user table if the field doesn't already have an alias.
248 $conditions[] = strpos($field, '.') !== false ? $field : $u . $field;
250 if ($searchanywhere) {
251 $searchparam = '%' . $search . '%';
252 } else {
253 $searchparam = $search . '%';
255 $i = 0;
256 foreach ($conditions as $key => $condition) {
257 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false, false);
258 $params["con{$i}00"] = $searchparam;
259 $i++;
261 $tests[] = '(' . implode(' OR ', $conditions) . ')';
264 // Add some additional sensible conditions.
265 $tests[] = $u . "id <> :guestid";
266 $params['guestid'] = $CFG->siteguest;
267 $tests[] = $u . 'deleted = 0';
268 $tests[] = $u . 'confirmed = 1';
270 // If we are being asked to exclude any users, do that.
271 if (!empty($exclude)) {
272 list($usertest, $userparams) = $DB->get_in_or_equal($exclude, SQL_PARAMS_NAMED, 'ex', false);
273 $tests[] = $u . 'id ' . $usertest;
274 $params = array_merge($params, $userparams);
277 // If we are validating a set list of userids, add an id IN (...) test.
278 if (!empty($includeonly)) {
279 list($usertest, $userparams) = $DB->get_in_or_equal($includeonly, SQL_PARAMS_NAMED, 'val');
280 $tests[] = $u . 'id ' . $usertest;
281 $params = array_merge($params, $userparams);
284 // In case there are no tests, add one result (this makes it easier to combine
285 // this with an existing query as you can always add AND $sql).
286 if (empty($tests)) {
287 $tests[] = '1 = 1';
290 // Combing the conditions and return.
291 return array(implode(' AND ', $tests), $params);
296 * This function generates the standard ORDER BY clause for use when generating
297 * lists of users. If you don't have a reason to use a different order, then
298 * you should use this method to generate the order when displaying lists of users.
300 * If the optional $search parameter is passed, then exact matches to the search
301 * will be sorted first. For example, suppose you have two users 'Al Zebra' and
302 * 'Alan Aardvark'. The default sort is Alan, then Al. If, however, you search for
303 * 'Al', then Al will be listed first. (With two users, this is not a big deal,
304 * but with thousands of users, it is essential.)
306 * The list of fields scanned for exact matches are:
307 * - firstname
308 * - lastname
309 * - $DB->sql_fullname
310 * - those returned by \core_user\fields::get_identity_fields or those included in $customfieldmappings
312 * If named parameters are used (which is the default, and highly recommended),
313 * then the parameter names are like :usersortexactN, where N is an int.
315 * The simplest possible example use is:
316 * list($sort, $params) = users_order_by_sql();
317 * $sql = 'SELECT * FROM {users} ORDER BY ' . $sort;
319 * A more complex example, showing that this sort can be combined with other sorts:
320 * list($sort, $sortparams) = users_order_by_sql('u');
321 * $sql = "SELECT g.id AS groupid, gg.groupingid, u.id AS userid, u.firstname, u.lastname, u.idnumber, u.username
322 * FROM {groups} g
323 * LEFT JOIN {groupings_groups} gg ON g.id = gg.groupid
324 * LEFT JOIN {groups_members} gm ON g.id = gm.groupid
325 * LEFT JOIN {user} u ON gm.userid = u.id
326 * WHERE g.courseid = :courseid $groupwhere $groupingwhere
327 * ORDER BY g.name, $sort";
328 * $params += $sortparams;
330 * An example showing the use of $search:
331 * list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
332 * $order = ' ORDER BY ' . $sort;
333 * $params += $sortparams;
334 * $availableusers = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage);
336 * @param string $usertablealias (optional) any table prefix for the {users} table. E.g. 'u'.
337 * @param string $search (optional) a current search string. If given,
338 * any exact matches to this string will be sorted first.
339 * @param context|null $context the context we are in. Used by \core_user\fields::get_identity_fields.
340 * Defaults to $PAGE->context.
341 * @param array $customfieldmappings associative array of mappings for custom fields returned by \core_user\fields::get_sql.
342 * @return array with two elements:
343 * string SQL fragment to use in the ORDER BY clause. For example, "firstname, lastname".
344 * array of parameters used in the SQL fragment. If $search is not given, this is guaranteed to be an empty array.
346 function users_order_by_sql(string $usertablealias = '', string $search = null, context $context = null,
347 array $customfieldmappings = []) {
348 global $DB, $PAGE;
350 if ($usertablealias) {
351 $tableprefix = $usertablealias . '.';
352 } else {
353 $tableprefix = '';
356 $sort = "{$tableprefix}lastname, {$tableprefix}firstname, {$tableprefix}id";
357 $params = array();
359 if (!$search) {
360 return array($sort, $params);
363 if (!$context) {
364 $context = $PAGE->context;
367 $exactconditions = array();
368 $paramkey = 'usersortexact1';
370 $exactconditions[] = $DB->sql_fullname($tableprefix . 'firstname', $tableprefix . 'lastname') .
371 ' = :' . $paramkey;
372 $params[$paramkey] = $search;
373 $paramkey++;
375 if ($customfieldmappings) {
376 $fieldstocheck = array_merge([$tableprefix . 'firstname', $tableprefix . 'lastname'], array_values($customfieldmappings));
377 } else {
378 $fieldstocheck = array_merge(['firstname', 'lastname'], \core_user\fields::get_identity_fields($context, false));
379 $fieldstocheck = array_map(function($field) use ($tableprefix) {
380 return $tableprefix . $field;
381 }, $fieldstocheck);
384 foreach ($fieldstocheck as $key => $field) {
385 $exactconditions[] = 'LOWER(' . $field . ') = LOWER(:' . $paramkey . ')';
386 $params[$paramkey] = $search;
387 $paramkey++;
390 $sort = 'CASE WHEN ' . implode(' OR ', $exactconditions) .
391 ' THEN 0 ELSE 1 END, ' . $sort;
393 return array($sort, $params);
397 * Returns a subset of users
399 * @global object
400 * @uses DEBUG_DEVELOPER
401 * @uses SQL_PARAMS_NAMED
402 * @param bool $get If false then only a count of the records is returned
403 * @param string $search A simple string to search for
404 * @param bool $confirmed A switch to allow/disallow unconfirmed users
405 * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
406 * @param string $sort A SQL snippet for the sorting criteria to use
407 * @param string $firstinitial Users whose first name starts with $firstinitial
408 * @param string $lastinitial Users whose last name starts with $lastinitial
409 * @param string $page The page or records to return
410 * @param string $recordsperpage The number of records to return per page
411 * @param string $fields A comma separated list of fields to be returned from the chosen table.
412 * @return array|int|bool {@link $USER} records unless get is false in which case the integer count of the records found is returned.
413 * False is returned if an error is encountered.
415 function get_users($get=true, $search='', $confirmed=false, array $exceptions=null, $sort='firstname ASC',
416 $firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields='*', $extraselect='', array $extraparams=null) {
417 global $DB, $CFG;
419 if ($get && !$recordsperpage) {
420 debugging('Call to get_users with $get = true no $recordsperpage limit. ' .
421 'On large installations, this will probably cause an out of memory error. ' .
422 'Please think again and change your code so that it does not try to ' .
423 'load so much data into memory.', DEBUG_DEVELOPER);
426 $fullname = $DB->sql_fullname();
428 $select = " id <> :guestid AND deleted = 0";
429 $params = array('guestid'=>$CFG->siteguest);
431 if (!empty($search)){
432 $search = trim($search);
433 $select .= " AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('email', ':search2', false)." OR username = :search3)";
434 $params['search1'] = "%$search%";
435 $params['search2'] = "%$search%";
436 $params['search3'] = "$search";
439 if ($confirmed) {
440 $select .= " AND confirmed = 1";
443 if ($exceptions) {
444 list($exceptions, $eparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex', false);
445 $params = $params + $eparams;
446 $select .= " AND id $exceptions";
449 if ($firstinitial) {
450 $select .= " AND ".$DB->sql_like('firstname', ':fni', false, false);
451 $params['fni'] = "$firstinitial%";
453 if ($lastinitial) {
454 $select .= " AND ".$DB->sql_like('lastname', ':lni', false, false);
455 $params['lni'] = "$lastinitial%";
458 if ($extraselect) {
459 $select .= " AND $extraselect";
460 $params = $params + (array)$extraparams;
463 if ($get) {
464 return $DB->get_records_select('user', $select, $params, $sort, $fields, $page, $recordsperpage);
465 } else {
466 return $DB->count_records_select('user', $select, $params);
472 * Return filtered (if provided) list of users in site, except guest and deleted users.
474 * @param string $sort An SQL field to sort by
475 * @param string $dir The sort direction ASC|DESC
476 * @param int $page The page or records to return
477 * @param int $recordsperpage The number of records to return per page
478 * @param string $search A simple string to search for
479 * @param string $firstinitial Users whose first name starts with $firstinitial
480 * @param string $lastinitial Users whose last name starts with $lastinitial
481 * @param string $extraselect An additional SQL select statement to append to the query
482 * @param array $extraparams Additional parameters to use for the above $extraselect
483 * @param stdClass $extracontext If specified, will include user 'extra fields'
484 * as appropriate for current user and given context
485 * @return array Array of {@link $USER} records
487 function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0,
488 $search='', $firstinitial='', $lastinitial='', $extraselect='',
489 array $extraparams=null, $extracontext = null) {
490 global $DB, $CFG;
492 $fullname = $DB->sql_fullname();
494 $select = "deleted <> 1 AND u.id <> :guestid";
495 $params = array('guestid' => $CFG->siteguest);
497 if (!empty($search)) {
498 $search = trim($search);
499 $select .= " AND (". $DB->sql_like($fullname, ':search1', false, false).
500 " OR ". $DB->sql_like('email', ':search2', false, false).
501 " OR username = :search3)";
502 $params['search1'] = "%$search%";
503 $params['search2'] = "%$search%";
504 $params['search3'] = "$search";
507 if ($firstinitial) {
508 $select .= " AND ". $DB->sql_like('firstname', ':fni', false, false);
509 $params['fni'] = "$firstinitial%";
511 if ($lastinitial) {
512 $select .= " AND ". $DB->sql_like('lastname', ':lni', false, false);
513 $params['lni'] = "$lastinitial%";
516 if ($extraselect) {
517 // The extra WHERE clause may refer to the 'id' column which can now be ambiguous because we
518 // changed the query to include joins, so replace any 'id' that is on its own (no alias)
519 // with 'u.id'.
520 $extraselect = preg_replace('~([ =]|^)id([ =]|$)~', '$1u.id$2', $extraselect);
521 $select .= " AND $extraselect";
522 $params = $params + (array)$extraparams;
525 // If a context is specified, get extra user fields that the current user
526 // is supposed to see, otherwise just get the name fields.
527 $userfields = \core_user\fields::for_name();
528 if ($extracontext) {
529 $userfields->with_identity($extracontext, true);
532 $userfields->excluding('id');
533 $userfields->including('username', 'email', 'city', 'country', 'lastaccess', 'confirmed', 'mnethostid', 'suspended');
534 ['selects' => $selects, 'joins' => $joins, 'params' => $joinparams, 'mappings' => $mappings] =
535 (array)$userfields->get_sql('u', true);
537 if ($sort) {
538 $orderbymap = $mappings;
539 $orderbymap['default'] = 'lastaccess';
540 $sort = get_safe_orderby($orderbymap, $sort, $dir);
543 // warning: will return UNCONFIRMED USERS
544 return $DB->get_records_sql("SELECT u.id $selects
545 FROM {user} u
546 $joins
547 WHERE $select
548 $sort", array_merge($params, $joinparams), $page, $recordsperpage);
554 * Full list of users that have confirmed their accounts.
556 * @global object
557 * @return array of unconfirmed users
559 function get_users_confirmed() {
560 global $DB, $CFG;
561 return $DB->get_records_sql("SELECT *
562 FROM {user}
563 WHERE confirmed = 1 AND deleted = 0 AND id <> ?", array($CFG->siteguest));
567 /// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
571 * Returns $course object of the top-level site.
573 * @return object A {@link $COURSE} object for the site, exception if not found
575 function get_site() {
576 global $SITE, $DB;
578 if (!empty($SITE->id)) { // We already have a global to use, so return that
579 return $SITE;
582 if ($course = $DB->get_record('course', array('category'=>0))) {
583 return $course;
584 } else {
585 // course table exists, but the site is not there,
586 // unfortunately there is no automatic way to recover
587 throw new moodle_exception('nosite', 'error');
592 * Gets a course object from database. If the course id corresponds to an
593 * already-loaded $COURSE or $SITE object, then the loaded object will be used,
594 * saving a database query.
596 * If it reuses an existing object, by default the object will be cloned. This
597 * means you can modify the object safely without affecting other code.
599 * @param int $courseid Course id
600 * @param bool $clone If true (default), makes a clone of the record
601 * @return stdClass A course object
602 * @throws dml_exception If not found in database
604 function get_course($courseid, $clone = true) {
605 global $DB, $COURSE, $SITE;
606 if (!empty($COURSE->id) && $COURSE->id == $courseid) {
607 return $clone ? clone($COURSE) : $COURSE;
608 } else if (!empty($SITE->id) && $SITE->id == $courseid) {
609 return $clone ? clone($SITE) : $SITE;
610 } else {
611 return $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
616 * Returns list of courses, for whole site, or category
618 * Returns list of courses, for whole site, or category
619 * Important: Using c.* for fields is extremely expensive because
620 * we are using distinct. You almost _NEVER_ need all the fields
621 * in such a large SELECT
623 * Consider using core_course_category::get_courses()
624 * or core_course_category::search_courses() instead since they use caching.
626 * @global object
627 * @global object
628 * @global object
629 * @uses CONTEXT_COURSE
630 * @param string|int $categoryid Either a category id or 'all' for everything
631 * @param string $sort A field and direction to sort by
632 * @param string $fields The additional fields to return (note that "id, category, visible" are always present)
633 * @return array Array of courses
635 function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
637 global $USER, $CFG, $DB;
639 $params = array();
641 if ($categoryid !== "all" && is_numeric($categoryid)) {
642 $categoryselect = "WHERE c.category = :catid";
643 $params['catid'] = $categoryid;
644 } else {
645 $categoryselect = "";
648 if (empty($sort)) {
649 $sortstatement = "";
650 } else {
651 $sortstatement = "ORDER BY $sort";
654 $visiblecourses = array();
656 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
657 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
658 $params['contextlevel'] = CONTEXT_COURSE;
660 // The fields "id, category, visible" are required in the subsequent loop and must always be present.
661 if ($fields !== 'c.*') {
662 $fieldarray = array_merge(
663 // Split fields on comma + zero or more whitespace, merge with required fields.
664 preg_split('/,\s*/', $fields), [
665 'c.id',
666 'c.category',
667 'c.visible',
670 $fields = implode(',', array_unique($fieldarray));
673 $sql = "SELECT $fields $ccselect
674 FROM {course} c
675 $ccjoin
676 $categoryselect
677 $sortstatement";
679 // pull out all course matching the cat
680 if ($courses = $DB->get_records_sql($sql, $params)) {
682 // loop throught them
683 foreach ($courses as $course) {
684 context_helper::preload_from_record($course);
685 if (core_course_category::can_view_course_info($course)) {
686 $visiblecourses [$course->id] = $course;
690 return $visiblecourses;
694 * A list of courses that match a search
696 * @global object
697 * @global object
698 * @param array $searchterms An array of search criteria
699 * @param string $sort A field and direction to sort by
700 * @param int $page The page number to get
701 * @param int $recordsperpage The number of records per page
702 * @param int $totalcount Passed in by reference.
703 * @param array $requiredcapabilities Extra list of capabilities used to filter courses
704 * @param array $searchcond additional search conditions, for example ['c.enablecompletion = :p1']
705 * @param array $params named parameters for additional search conditions, for example ['p1' => 1]
706 * @return stdClass[] {@link $COURSE} records
708 function get_courses_search($searchterms, $sort, $page, $recordsperpage, &$totalcount,
709 $requiredcapabilities = array(), $searchcond = [], $params = []) {
710 global $CFG, $DB;
712 if ($DB->sql_regex_supported()) {
713 $REGEXP = $DB->sql_regex(true);
714 $NOTREGEXP = $DB->sql_regex(false);
717 $i = 0;
719 // Thanks Oracle for your non-ansi concat and type limits in coalesce. MDL-29912
720 if ($DB->get_dbfamily() == 'oracle') {
721 $concat = "(c.summary|| ' ' || c.fullname || ' ' || c.idnumber || ' ' || c.shortname)";
722 } else {
723 $concat = $DB->sql_concat("COALESCE(c.summary, '')", "' '", 'c.fullname', "' '", 'c.idnumber', "' '", 'c.shortname');
726 foreach ($searchterms as $searchterm) {
727 $i++;
729 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
730 /// will use it to simulate the "-" operator with LIKE clause
732 /// Under Oracle and MSSQL, trim the + and - operators and perform
733 /// simpler LIKE (or NOT LIKE) queries
734 if (!$DB->sql_regex_supported()) {
735 if (substr($searchterm, 0, 1) == '-') {
736 $NOT = true;
738 $searchterm = trim($searchterm, '+-');
741 // TODO: +- may not work for non latin languages
743 if (substr($searchterm,0,1) == '+') {
744 $searchterm = trim($searchterm, '+-');
745 $searchterm = preg_quote($searchterm, '|');
746 $searchcond[] = "$concat $REGEXP :ss$i";
747 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
749 } else if ((substr($searchterm,0,1) == "-") && (core_text::strlen($searchterm) > 1)) {
750 $searchterm = trim($searchterm, '+-');
751 $searchterm = preg_quote($searchterm, '|');
752 $searchcond[] = "$concat $NOTREGEXP :ss$i";
753 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
755 } else {
756 $searchcond[] = $DB->sql_like($concat,":ss$i", false, true, $NOT);
757 $params['ss'.$i] = "%$searchterm%";
761 if (empty($searchcond)) {
762 $searchcond = array('1 = 1');
765 $searchcond = implode(" AND ", $searchcond);
767 $courses = array();
768 $c = 0; // counts how many visible courses we've seen
770 // Tiki pagination
771 $limitfrom = $page * $recordsperpage;
772 $limitto = $limitfrom + $recordsperpage;
774 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
775 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
776 $params['contextlevel'] = CONTEXT_COURSE;
778 $sql = "SELECT c.* $ccselect
779 FROM {course} c
780 $ccjoin
781 WHERE $searchcond AND c.id <> ".SITEID."
782 ORDER BY $sort";
784 $mycourses = enrol_get_my_courses();
785 $rs = $DB->get_recordset_sql($sql, $params);
786 foreach($rs as $course) {
787 // Preload contexts only for hidden courses or courses we need to return.
788 context_helper::preload_from_record($course);
789 $coursecontext = context_course::instance($course->id);
790 if (!array_key_exists($course->id, $mycourses) && !core_course_category::can_view_course_info($course)) {
791 continue;
793 if (!empty($requiredcapabilities)) {
794 if (!has_all_capabilities($requiredcapabilities, $coursecontext)) {
795 continue;
798 // Don't exit this loop till the end
799 // we need to count all the visible courses
800 // to update $totalcount
801 if ($c >= $limitfrom && $c < $limitto) {
802 $courses[$course->id] = $course;
804 $c++;
806 $rs->close();
808 // our caller expects 2 bits of data - our return
809 // array, and an updated $totalcount
810 $totalcount = $c;
811 return $courses;
815 * Fixes course category and course sortorder, also verifies category and course parents and paths.
816 * (circular references are not fixed)
818 * @global object
819 * @global object
820 * @uses MAX_COURSE_CATEGORIES
821 * @uses SITEID
822 * @uses CONTEXT_COURSE
823 * @return void
825 function fix_course_sortorder() {
826 global $DB, $SITE;
828 //WARNING: this is PHP5 only code!
830 // if there are any changes made to courses or categories we will trigger
831 // the cache events to purge all cached courses/categories data
832 $cacheevents = array();
834 if ($unsorted = $DB->get_records('course_categories', array('sortorder'=>0))) {
835 //move all categories that are not sorted yet to the end
836 $DB->set_field('course_categories', 'sortorder',
837 get_max_courses_in_category() * MAX_COURSE_CATEGORIES, array('sortorder' => 0));
838 $cacheevents['changesincoursecat'] = true;
841 $allcats = $DB->get_records('course_categories', null, 'sortorder, id', 'id, sortorder, parent, depth, path');
842 $topcats = array();
843 $brokencats = array();
844 foreach ($allcats as $cat) {
845 $sortorder = (int)$cat->sortorder;
846 if (!$cat->parent) {
847 while(isset($topcats[$sortorder])) {
848 $sortorder++;
850 $topcats[$sortorder] = $cat;
851 continue;
853 if (!isset($allcats[$cat->parent])) {
854 $brokencats[] = $cat;
855 continue;
857 if (!isset($allcats[$cat->parent]->children)) {
858 $allcats[$cat->parent]->children = array();
860 while(isset($allcats[$cat->parent]->children[$sortorder])) {
861 $sortorder++;
863 $allcats[$cat->parent]->children[$sortorder] = $cat;
865 unset($allcats);
867 // add broken cats to category tree
868 if ($brokencats) {
869 $defaultcat = reset($topcats);
870 foreach ($brokencats as $cat) {
871 $topcats[] = $cat;
875 // now walk recursively the tree and fix any problems found
876 $sortorder = 0;
877 $fixcontexts = array();
878 if (_fix_course_cats($topcats, $sortorder, 0, 0, '', $fixcontexts)) {
879 $cacheevents['changesincoursecat'] = true;
882 // detect if there are "multiple" frontpage courses and fix them if needed
883 $frontcourses = $DB->get_records('course', array('category'=>0), 'id');
884 if (count($frontcourses) > 1) {
885 if (isset($frontcourses[SITEID])) {
886 $frontcourse = $frontcourses[SITEID];
887 unset($frontcourses[SITEID]);
888 } else {
889 $frontcourse = array_shift($frontcourses);
891 $defaultcat = reset($topcats);
892 foreach ($frontcourses as $course) {
893 $DB->set_field('course', 'category', $defaultcat->id, array('id'=>$course->id));
894 $context = context_course::instance($course->id);
895 $fixcontexts[$context->id] = $context;
896 $cacheevents['changesincourse'] = true;
898 unset($frontcourses);
899 } else {
900 $frontcourse = reset($frontcourses);
903 // now fix the paths and depths in context table if needed
904 if ($fixcontexts) {
905 foreach ($fixcontexts as $fixcontext) {
906 $fixcontext->reset_paths(false);
908 context_helper::build_all_paths(false);
909 unset($fixcontexts);
910 $cacheevents['changesincourse'] = true;
911 $cacheevents['changesincoursecat'] = true;
914 // release memory
915 unset($topcats);
916 unset($brokencats);
917 unset($fixcontexts);
919 // fix frontpage course sortorder
920 if ($frontcourse->sortorder != 1) {
921 $DB->set_field('course', 'sortorder', 1, array('id'=>$frontcourse->id));
922 $cacheevents['changesincourse'] = true;
925 // now fix the course counts in category records if needed
926 $sql = "SELECT cc.id, cc.coursecount, COUNT(c.id) AS newcount
927 FROM {course_categories} cc
928 LEFT JOIN {course} c ON c.category = cc.id
929 GROUP BY cc.id, cc.coursecount
930 HAVING cc.coursecount <> COUNT(c.id)";
932 if ($updatecounts = $DB->get_records_sql($sql)) {
933 // categories with more courses than MAX_COURSES_IN_CATEGORY
934 $categories = array();
935 foreach ($updatecounts as $cat) {
936 $cat->coursecount = $cat->newcount;
937 if ($cat->coursecount >= get_max_courses_in_category()) {
938 $categories[] = $cat->id;
940 unset($cat->newcount);
941 $DB->update_record_raw('course_categories', $cat, true);
943 if (!empty($categories)) {
944 $str = implode(', ', $categories);
945 debugging("The number of courses (category id: $str) has reached max number of courses " .
946 "in a category (" . get_max_courses_in_category() . "). It will cause a sorting performance issue. " .
947 "Please set higher value for \$CFG->maxcoursesincategory in config.php. " .
948 "Please also make sure \$CFG->maxcoursesincategory * MAX_COURSE_CATEGORIES less than max integer. " .
949 "See tracker issues: MDL-25669 and MDL-69573", DEBUG_DEVELOPER);
951 $cacheevents['changesincoursecat'] = true;
954 // now make sure that sortorders in course table are withing the category sortorder ranges
955 $sql = "SELECT DISTINCT cc.id, cc.sortorder
956 FROM {course_categories} cc
957 JOIN {course} c ON c.category = cc.id
958 WHERE c.sortorder < cc.sortorder OR c.sortorder > cc.sortorder + " . get_max_courses_in_category();
960 if ($fixcategories = $DB->get_records_sql($sql)) {
961 //fix the course sortorder ranges
962 foreach ($fixcategories as $cat) {
963 $sql = "UPDATE {course}
964 SET sortorder = ".$DB->sql_modulo('sortorder', get_max_courses_in_category())." + ?
965 WHERE category = ?";
966 $DB->execute($sql, array($cat->sortorder, $cat->id));
968 $cacheevents['changesincoursecat'] = true;
970 unset($fixcategories);
972 // categories having courses with sortorder duplicates or having gaps in sortorder
973 $sql = "SELECT DISTINCT c1.category AS id , cc.sortorder
974 FROM {course} c1
975 JOIN {course} c2 ON c1.sortorder = c2.sortorder
976 JOIN {course_categories} cc ON (c1.category = cc.id)
977 WHERE c1.id <> c2.id";
978 $fixcategories = $DB->get_records_sql($sql);
980 $sql = "SELECT cc.id, cc.sortorder, cc.coursecount, MAX(c.sortorder) AS maxsort, MIN(c.sortorder) AS minsort
981 FROM {course_categories} cc
982 JOIN {course} c ON c.category = cc.id
983 GROUP BY cc.id, cc.sortorder, cc.coursecount
984 HAVING (MAX(c.sortorder) <> cc.sortorder + cc.coursecount) OR (MIN(c.sortorder) <> cc.sortorder + 1)";
985 $gapcategories = $DB->get_records_sql($sql);
987 foreach ($gapcategories as $cat) {
988 if (isset($fixcategories[$cat->id])) {
989 // duplicates detected already
991 } else if ($cat->minsort == $cat->sortorder and $cat->maxsort == $cat->sortorder + $cat->coursecount - 1) {
992 // easy - new course inserted with sortorder 0, the rest is ok
993 $sql = "UPDATE {course}
994 SET sortorder = sortorder + 1
995 WHERE category = ?";
996 $DB->execute($sql, array($cat->id));
998 } else {
999 // it needs full resorting
1000 $fixcategories[$cat->id] = $cat;
1002 $cacheevents['changesincourse'] = true;
1004 unset($gapcategories);
1006 // fix course sortorders in problematic categories only
1007 foreach ($fixcategories as $cat) {
1008 $i = 1;
1009 $courses = $DB->get_records('course', array('category'=>$cat->id), 'sortorder ASC, id DESC', 'id, sortorder');
1010 foreach ($courses as $course) {
1011 if ($course->sortorder != $cat->sortorder + $i) {
1012 $course->sortorder = $cat->sortorder + $i;
1013 $DB->update_record_raw('course', $course, true);
1014 $cacheevents['changesincourse'] = true;
1016 $i++;
1020 // advise all caches that need to be rebuilt
1021 foreach (array_keys($cacheevents) as $event) {
1022 cache_helper::purge_by_event($event);
1027 * Internal recursive category verification function, do not use directly!
1029 * @todo Document the arguments of this function better
1031 * @global object
1032 * @uses CONTEXT_COURSECAT
1033 * @param array $children
1034 * @param int $sortorder
1035 * @param string $parent
1036 * @param int $depth
1037 * @param string $path
1038 * @param array $fixcontexts
1039 * @return bool if changes were made
1041 function _fix_course_cats($children, &$sortorder, $parent, $depth, $path, &$fixcontexts) {
1042 global $DB;
1044 $depth++;
1045 $changesmade = false;
1047 foreach ($children as $cat) {
1048 $sortorder = $sortorder + get_max_courses_in_category();
1049 $update = false;
1050 if ($parent != $cat->parent or $depth != $cat->depth or $path.'/'.$cat->id != $cat->path) {
1051 $cat->parent = $parent;
1052 $cat->depth = $depth;
1053 $cat->path = $path.'/'.$cat->id;
1054 $update = true;
1056 // make sure context caches are rebuild and dirty contexts marked
1057 $context = context_coursecat::instance($cat->id);
1058 $fixcontexts[$context->id] = $context;
1060 if ($cat->sortorder != $sortorder) {
1061 $cat->sortorder = $sortorder;
1062 $update = true;
1064 if ($update) {
1065 $DB->update_record('course_categories', $cat, true);
1066 $changesmade = true;
1068 if (isset($cat->children)) {
1069 if (_fix_course_cats($cat->children, $sortorder, $cat->id, $cat->depth, $cat->path, $fixcontexts)) {
1070 $changesmade = true;
1074 return $changesmade;
1078 * List of remote courses that a user has access to via MNET.
1079 * Works only on the IDP
1081 * @global object
1082 * @global object
1083 * @param int @userid The user id to get remote courses for
1084 * @return array Array of {@link $COURSE} of course objects
1086 function get_my_remotecourses($userid=0) {
1087 global $DB, $USER;
1089 if (empty($userid)) {
1090 $userid = $USER->id;
1093 // we can not use SELECT DISTINCT + text field (summary) because of MS SQL and Oracle, subselect used therefore
1094 $sql = "SELECT c.id, c.remoteid, c.shortname, c.fullname,
1095 c.hostid, c.summary, c.summaryformat, c.categoryname AS cat_name,
1096 h.name AS hostname
1097 FROM {mnetservice_enrol_courses} c
1098 JOIN (SELECT DISTINCT hostid, remotecourseid
1099 FROM {mnetservice_enrol_enrolments}
1100 WHERE userid = ?
1101 ) e ON (e.hostid = c.hostid AND e.remotecourseid = c.remoteid)
1102 JOIN {mnet_host} h ON h.id = c.hostid";
1104 return $DB->get_records_sql($sql, array($userid));
1108 * List of remote hosts that a user has access to via MNET.
1109 * Works on the SP
1111 * @global object
1112 * @global object
1113 * @return array|bool Array of host objects or false
1115 function get_my_remotehosts() {
1116 global $CFG, $USER;
1118 if ($USER->mnethostid == $CFG->mnet_localhost_id) {
1119 return false; // Return nothing on the IDP
1121 if (!empty($USER->mnet_foreign_host_array) && is_array($USER->mnet_foreign_host_array)) {
1122 return $USER->mnet_foreign_host_array;
1124 return false;
1129 * Returns a menu of all available scales from the site as well as the given course
1131 * @global object
1132 * @param int $courseid The id of the course as found in the 'course' table.
1133 * @return array
1135 function get_scales_menu($courseid=0) {
1136 global $DB;
1138 $sql = "SELECT id, name, courseid
1139 FROM {scale}
1140 WHERE courseid = 0 or courseid = ?
1141 ORDER BY courseid ASC, name ASC";
1142 $params = array($courseid);
1143 $scales = array();
1144 $results = $DB->get_records_sql($sql, $params);
1145 foreach ($results as $index => $record) {
1146 $context = empty($record->courseid) ? context_system::instance() : context_course::instance($record->courseid);
1147 $scales[$index] = format_string($record->name, false, ["context" => $context]);
1149 // Format: [id => 'scale name'].
1150 return $scales;
1154 * Increment standard revision field.
1156 * The revision are based on current time and are incrementing.
1157 * There is a protection for runaway revisions, it may not go further than
1158 * one hour into future.
1160 * The field has to be XMLDB_TYPE_INTEGER with size 10.
1162 * @param string $table
1163 * @param string $field name of the field containing revision
1164 * @param string $select use empty string when updating all records
1165 * @param array $params optional select parameters
1167 function increment_revision_number($table, $field, $select, array $params = null) {
1168 global $DB;
1170 $now = time();
1171 $sql = "UPDATE {{$table}}
1172 SET $field = (CASE
1173 WHEN $field IS NULL THEN $now
1174 WHEN $field < $now THEN $now
1175 WHEN $field > $now + 3600 THEN $now
1176 ELSE $field + 1 END)";
1177 if ($select) {
1178 $sql = $sql . " WHERE $select";
1180 $DB->execute($sql, $params);
1184 /// MODULE FUNCTIONS /////////////////////////////////////////////////
1187 * Just gets a raw list of all modules in a course
1189 * @global object
1190 * @param int $courseid The id of the course as found in the 'course' table.
1191 * @return array
1193 function get_course_mods($courseid) {
1194 global $DB;
1196 if (empty($courseid)) {
1197 return false; // avoid warnings
1200 return $DB->get_records_sql("SELECT cm.*, m.name as modname
1201 FROM {modules} m, {course_modules} cm
1202 WHERE cm.course = ? AND cm.module = m.id AND m.visible = 1",
1203 array($courseid)); // no disabled mods
1208 * Given an id of a course module, finds the coursemodule description
1210 * Please note that this function performs 1-2 DB queries. When possible use cached
1211 * course modinfo. For example get_fast_modinfo($courseorid)->get_cm($cmid)
1212 * See also {@link cm_info::get_course_module_record()}
1214 * @global object
1215 * @param string $modulename name of module type, eg. resource, assignment,... (optional, slower and less safe if not specified)
1216 * @param int $cmid course module id (id in course_modules table)
1217 * @param int $courseid optional course id for extra validation
1218 * @param bool $sectionnum include relative section number (0,1,2 ...)
1219 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1220 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1221 * MUST_EXIST means throw exception if no record or multiple records found
1222 * @return stdClass
1224 function get_coursemodule_from_id($modulename, $cmid, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1225 global $DB;
1227 $params = array('cmid'=>$cmid);
1229 if (!$modulename) {
1230 if (!$modulename = $DB->get_field_sql("SELECT md.name
1231 FROM {modules} md
1232 JOIN {course_modules} cm ON cm.module = md.id
1233 WHERE cm.id = :cmid", $params, $strictness)) {
1234 return false;
1236 } else {
1237 if (!core_component::is_valid_plugin_name('mod', $modulename)) {
1238 throw new coding_exception('Invalid modulename parameter');
1242 $params['modulename'] = $modulename;
1244 $courseselect = "";
1245 $sectionfield = "";
1246 $sectionjoin = "";
1248 if ($courseid) {
1249 $courseselect = "AND cm.course = :courseid";
1250 $params['courseid'] = $courseid;
1253 if ($sectionnum) {
1254 $sectionfield = ", cw.section AS sectionnum";
1255 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1258 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1259 FROM {course_modules} cm
1260 JOIN {modules} md ON md.id = cm.module
1261 JOIN {".$modulename."} m ON m.id = cm.instance
1262 $sectionjoin
1263 WHERE cm.id = :cmid AND md.name = :modulename
1264 $courseselect";
1266 return $DB->get_record_sql($sql, $params, $strictness);
1270 * Given an instance number of a module, finds the coursemodule description
1272 * Please note that this function performs DB query. When possible use cached course
1273 * modinfo. For example get_fast_modinfo($courseorid)->instances[$modulename][$instance]
1274 * See also {@link cm_info::get_course_module_record()}
1276 * @global object
1277 * @param string $modulename name of module type, eg. resource, assignment,...
1278 * @param int $instance module instance number (id in resource, assignment etc. table)
1279 * @param int $courseid optional course id for extra validation
1280 * @param bool $sectionnum include relative section number (0,1,2 ...)
1281 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1282 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1283 * MUST_EXIST means throw exception if no record or multiple records found
1284 * @return stdClass
1286 function get_coursemodule_from_instance($modulename, $instance, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1287 global $DB;
1289 if (!core_component::is_valid_plugin_name('mod', $modulename)) {
1290 throw new coding_exception('Invalid modulename parameter');
1293 $params = array('instance'=>$instance, 'modulename'=>$modulename);
1295 $courseselect = "";
1296 $sectionfield = "";
1297 $sectionjoin = "";
1299 if ($courseid) {
1300 $courseselect = "AND cm.course = :courseid";
1301 $params['courseid'] = $courseid;
1304 if ($sectionnum) {
1305 $sectionfield = ", cw.section AS sectionnum";
1306 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1309 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1310 FROM {course_modules} cm
1311 JOIN {modules} md ON md.id = cm.module
1312 JOIN {".$modulename."} m ON m.id = cm.instance
1313 $sectionjoin
1314 WHERE m.id = :instance AND md.name = :modulename
1315 $courseselect";
1317 return $DB->get_record_sql($sql, $params, $strictness);
1321 * Returns all course modules of given activity in course
1323 * @param string $modulename The module name (forum, quiz, etc.)
1324 * @param int $courseid The course id to get modules for
1325 * @param string $extrafields extra fields starting with m.
1326 * @return array Array of results
1328 function get_coursemodules_in_course($modulename, $courseid, $extrafields='') {
1329 global $DB;
1331 if (!core_component::is_valid_plugin_name('mod', $modulename)) {
1332 throw new coding_exception('Invalid modulename parameter');
1335 if (!empty($extrafields)) {
1336 $extrafields = ", $extrafields";
1338 $params = array();
1339 $params['courseid'] = $courseid;
1340 $params['modulename'] = $modulename;
1343 return $DB->get_records_sql("SELECT cm.*, m.name, md.name as modname $extrafields
1344 FROM {course_modules} cm, {modules} md, {".$modulename."} m
1345 WHERE cm.course = :courseid AND
1346 cm.instance = m.id AND
1347 md.name = :modulename AND
1348 md.id = cm.module", $params);
1352 * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1354 * Returns an array of all the active instances of a particular
1355 * module in given courses, sorted in the order they are defined
1356 * in the course. Returns an empty array on any errors.
1358 * The returned objects includle the columns cw.section, cm.visible,
1359 * cm.groupmode, cm.groupingid and cm.lang and are indexed by cm.id.
1361 * @global object
1362 * @global object
1363 * @param string $modulename The name of the module to get instances for
1364 * @param array $courses an array of course objects.
1365 * @param int $userid
1366 * @param int $includeinvisible
1367 * @return array of module instance objects, including some extra fields from the course_modules
1368 * and course_sections tables, or an empty array if an error occurred.
1370 function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
1371 global $CFG, $DB;
1373 if (!core_component::is_valid_plugin_name('mod', $modulename)) {
1374 throw new coding_exception('Invalid modulename parameter');
1377 $outputarray = array();
1379 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1380 return $outputarray;
1383 list($coursessql, $params) = $DB->get_in_or_equal(array_keys($courses), SQL_PARAMS_NAMED, 'c0');
1384 $params['modulename'] = $modulename;
1386 if (!$rawmods = $DB->get_records_sql("SELECT cm.id AS coursemodule, m.*, cw.section, cm.visible AS visible,
1387 cm.groupmode, cm.groupingid, cm.lang
1388 FROM {course_modules} cm, {course_sections} cw, {modules} md,
1389 {".$modulename."} m
1390 WHERE cm.course $coursessql AND
1391 cm.instance = m.id AND
1392 cm.section = cw.id AND
1393 md.name = :modulename AND
1394 md.id = cm.module", $params)) {
1395 return $outputarray;
1398 foreach ($courses as $course) {
1399 $modinfo = get_fast_modinfo($course, $userid);
1401 if (empty($modinfo->instances[$modulename])) {
1402 continue;
1405 foreach ($modinfo->instances[$modulename] as $cm) {
1406 if (!$includeinvisible and !$cm->uservisible) {
1407 continue;
1409 if (!isset($rawmods[$cm->id])) {
1410 continue;
1412 $instance = $rawmods[$cm->id];
1413 if (!empty($cm->extra)) {
1414 $instance->extra = $cm->extra;
1416 $outputarray[] = $instance;
1420 return $outputarray;
1424 * Returns an array of all the active instances of a particular module in a given course,
1425 * sorted in the order they are defined.
1427 * Returns an array of all the active instances of a particular
1428 * module in a given course, sorted in the order they are defined
1429 * in the course. Returns an empty array on any errors.
1431 * The returned objects includle the columns cw.section, cm.visible,
1432 * cm.groupmode, and cm.groupingid, and are indexed by cm.id.
1434 * Simply calls {@link all_instances_in_courses()} with a single provided course
1436 * @param string $modulename The name of the module to get instances for
1437 * @param object $course The course obect.
1438 * @return array of module instance objects, including some extra fields from the course_modules
1439 * and course_sections tables, or an empty array if an error occurred.
1440 * @param int $userid
1441 * @param int $includeinvisible
1443 function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
1444 return get_all_instances_in_courses($modulename, array($course->id => $course), $userid, $includeinvisible);
1449 * Determine whether a module instance is visible within a course
1451 * Given a valid module object with info about the id and course,
1452 * and the module's type (eg "forum") returns whether the object
1453 * is visible or not according to the 'eye' icon only.
1455 * NOTE: This does NOT take into account visibility to a particular user.
1456 * To get visibility access for a specific user, use get_fast_modinfo, get a
1457 * cm_info object from this, and check the ->uservisible property; or use
1458 * the \core_availability\info_module::is_user_visible() static function.
1460 * @global object
1462 * @param $moduletype Name of the module eg 'forum'
1463 * @param $module Object which is the instance of the module
1464 * @return bool Success
1466 function instance_is_visible($moduletype, $module) {
1467 global $DB;
1469 if (!empty($module->id)) {
1470 $params = array('courseid'=>$module->course, 'moduletype'=>$moduletype, 'moduleid'=>$module->id);
1471 if ($records = $DB->get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.course
1472 FROM {course_modules} cm, {modules} m
1473 WHERE cm.course = :courseid AND
1474 cm.module = m.id AND
1475 m.name = :moduletype AND
1476 cm.instance = :moduleid", $params)) {
1478 foreach ($records as $record) { // there should only be one - use the first one
1479 return $record->visible;
1483 return true; // visible by default!
1487 /// LOG FUNCTIONS /////////////////////////////////////////////////////
1490 * Get instance of log manager.
1492 * @param bool $forcereload
1493 * @return \core\log\manager
1495 function get_log_manager($forcereload = false) {
1496 /** @var \core\log\manager $singleton */
1497 static $singleton = null;
1499 if ($forcereload and isset($singleton)) {
1500 $singleton->dispose();
1501 $singleton = null;
1504 if (isset($singleton)) {
1505 return $singleton;
1508 $classname = '\tool_log\log\manager';
1509 if (defined('LOG_MANAGER_CLASS')) {
1510 $classname = LOG_MANAGER_CLASS;
1513 if (!class_exists($classname)) {
1514 if (!empty($classname)) {
1515 debugging("Cannot find log manager class '$classname'.", DEBUG_DEVELOPER);
1517 $classname = '\core\log\dummy_manager';
1520 $singleton = new $classname();
1521 return $singleton;
1525 * Add an entry to the config log table.
1527 * These are "action" focussed rather than web server hits,
1528 * and provide a way to easily reconstruct changes to Moodle configuration.
1530 * @package core
1531 * @category log
1532 * @global moodle_database $DB
1533 * @global stdClass $USER
1534 * @param string $name The name of the configuration change action
1535 For example 'filter_active' when activating or deactivating a filter
1536 * @param string $oldvalue The config setting's previous value
1537 * @param string $value The config setting's new value
1538 * @param string $plugin Plugin name, for example a filter name when changing filter configuration
1539 * @return void
1541 function add_to_config_log($name, $oldvalue, $value, $plugin) {
1542 global $USER, $DB;
1544 $log = new stdClass();
1545 // Use 0 as user id during install.
1546 $log->userid = during_initial_install() ? 0 : $USER->id;
1547 $log->timemodified = time();
1548 $log->name = $name;
1549 $log->oldvalue = $oldvalue;
1550 $log->value = $value;
1551 $log->plugin = $plugin;
1553 $id = $DB->insert_record('config_log', $log);
1555 $event = core\event\config_log_created::create(array(
1556 'objectid' => $id,
1557 'userid' => $log->userid,
1558 'context' => \context_system::instance(),
1559 'other' => array(
1560 'name' => $log->name,
1561 'oldvalue' => $log->oldvalue,
1562 'value' => $log->value,
1563 'plugin' => $log->plugin
1566 $event->trigger();
1570 * Store user last access times - called when use enters a course or site
1572 * @package core
1573 * @category log
1574 * @global stdClass $USER
1575 * @global stdClass $CFG
1576 * @global moodle_database $DB
1577 * @uses LASTACCESS_UPDATE_SECS
1578 * @uses SITEID
1579 * @param int $courseid empty courseid means site
1580 * @return void
1582 function user_accesstime_log($courseid=0) {
1583 global $USER, $CFG, $DB;
1585 if (!isloggedin() or \core\session\manager::is_loggedinas()) {
1586 // no access tracking
1587 return;
1590 if (isguestuser()) {
1591 // Do not update guest access times/ips for performance.
1592 return;
1595 if (empty($courseid)) {
1596 $courseid = SITEID;
1599 $timenow = time();
1601 /// Store site lastaccess time for the current user
1602 if ($timenow - $USER->lastaccess > LASTACCESS_UPDATE_SECS) {
1603 /// Update $USER->lastaccess for next checks
1604 $USER->lastaccess = $timenow;
1606 $last = new stdClass();
1607 $last->id = $USER->id;
1608 $last->lastip = getremoteaddr();
1609 $last->lastaccess = $timenow;
1611 $DB->update_record_raw('user', $last);
1614 if ($courseid == SITEID) {
1615 /// no user_lastaccess for frontpage
1616 return;
1619 /// Store course lastaccess times for the current user
1620 if (empty($USER->currentcourseaccess[$courseid]) or ($timenow - $USER->currentcourseaccess[$courseid] > LASTACCESS_UPDATE_SECS)) {
1622 $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid'=>$USER->id, 'courseid'=>$courseid));
1624 if ($lastaccess === false) {
1625 // Update course lastaccess for next checks
1626 $USER->currentcourseaccess[$courseid] = $timenow;
1628 $last = new stdClass();
1629 $last->userid = $USER->id;
1630 $last->courseid = $courseid;
1631 $last->timeaccess = $timenow;
1632 try {
1633 $DB->insert_record_raw('user_lastaccess', $last, false);
1634 } catch (dml_write_exception $e) {
1635 // During a race condition we can fail to find the data, then it appears.
1636 // If we still can't find it, rethrow the exception.
1637 $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid' => $USER->id,
1638 'courseid' => $courseid));
1639 if ($lastaccess === false) {
1640 throw $e;
1642 // If we did find it, the race condition was true and another thread has inserted the time for us.
1643 // We can just continue without having to do anything.
1646 } else if ($timenow - $lastaccess < LASTACCESS_UPDATE_SECS) {
1647 // no need to update now, it was updated recently in concurrent login ;-)
1649 } else {
1650 // Update course lastaccess for next checks
1651 $USER->currentcourseaccess[$courseid] = $timenow;
1653 $DB->set_field('user_lastaccess', 'timeaccess', $timenow, array('userid'=>$USER->id, 'courseid'=>$courseid));
1658 /// GENERAL HELPFUL THINGS ///////////////////////////////////
1661 * Dumps a given object's information for debugging purposes
1663 * When used in a CLI script, the object's information is written to the standard
1664 * error output stream. When used in a web script, the object is dumped to a
1665 * pre-formatted block with the "notifytiny" CSS class.
1667 * @param mixed $object The data to be printed
1668 * @return void output is echo'd
1670 function print_object($object) {
1672 // we may need a lot of memory here
1673 raise_memory_limit(MEMORY_EXTRA);
1675 if (CLI_SCRIPT) {
1676 fwrite(STDERR, print_r($object, true));
1677 fwrite(STDERR, PHP_EOL);
1678 } else if (AJAX_SCRIPT) {
1679 foreach (explode("\n", print_r($object, true)) as $line) {
1680 error_log($line);
1682 } else {
1683 echo html_writer::tag('pre', s(print_r($object, true)), array('class' => 'notifytiny'));
1688 * This function is the official hook inside XMLDB stuff to delegate its debug to one
1689 * external function.
1691 * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
1692 * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
1694 * @uses DEBUG_DEVELOPER
1695 * @param string $message string contains the error message
1696 * @param object $object object XMLDB object that fired the debug
1698 function xmldb_debug($message, $object) {
1700 debugging($message, DEBUG_DEVELOPER);
1704 * @global object
1705 * @uses CONTEXT_COURSECAT
1706 * @return boolean Whether the user can create courses in any category in the system.
1708 function user_can_create_courses() {
1709 global $DB;
1710 $catsrs = $DB->get_recordset('course_categories');
1711 foreach ($catsrs as $cat) {
1712 if (has_capability('moodle/course:create', context_coursecat::instance($cat->id))) {
1713 $catsrs->close();
1714 return true;
1717 $catsrs->close();
1718 return false;
1722 * This method can update the values in mulitple database rows for a colum with
1723 * a unique index, without violating that constraint.
1725 * Suppose we have a table with a unique index on (otherid, sortorder), and
1726 * for a particular value of otherid, we want to change all the sort orders.
1727 * You have to do this carefully or you will violate the unique index at some time.
1728 * This method takes care of the details for you.
1730 * Note that, it is the responsibility of the caller to make sure that the
1731 * requested rename is legal. For example, if you ask for [1 => 2, 2 => 2]
1732 * then you will get a unique key violation error from the database.
1734 * @param string $table The database table to modify.
1735 * @param string $field the field that contains the values we are going to change.
1736 * @param array $newvalues oldvalue => newvalue how to change the values.
1737 * E.g. [1 => 4, 2 => 1, 3 => 3, 4 => 2].
1738 * @param array $otherconditions array fieldname => requestedvalue extra WHERE clause
1739 * conditions to restrict which rows are affected. E.g. array('otherid' => 123).
1740 * @param int $unusedvalue (defaults to -1) a value that is never used in $ordercol.
1742 function update_field_with_unique_index($table, $field, array $newvalues,
1743 array $otherconditions, $unusedvalue = -1) {
1744 global $DB;
1745 $safechanges = decompose_update_into_safe_changes($newvalues, $unusedvalue);
1747 $transaction = $DB->start_delegated_transaction();
1748 foreach ($safechanges as $change) {
1749 list($from, $to) = $change;
1750 $otherconditions[$field] = $from;
1751 $DB->set_field($table, $field, $to, $otherconditions);
1753 $transaction->allow_commit();
1757 * Helper used by {@link update_field_with_unique_index()}. Given a desired
1758 * set of changes, break them down into single udpates that can be done one at
1759 * a time without breaking any unique index constraints.
1761 * Suppose the input is array(1 => 2, 2 => 1) and -1. Then the output will be
1762 * array (array(1, -1), array(2, 1), array(-1, 2)). This function solves this
1763 * problem in the general case, not just for simple swaps. The unit tests give
1764 * more examples.
1766 * Note that, it is the responsibility of the caller to make sure that the
1767 * requested rename is legal. For example, if you ask for something impossible
1768 * like array(1 => 2, 2 => 2) then the results are undefined. (You will probably
1769 * get a unique key violation error from the database later.)
1771 * @param array $newvalues The desired re-ordering.
1772 * E.g. array(1 => 4, 2 => 1, 3 => 3, 4 => 2).
1773 * @param int $unusedvalue A value that is not currently used.
1774 * @return array A safe way to perform the re-order. An array of two-element
1775 * arrays array($from, $to).
1776 * E.g. array(array(1, -1), array(2, 1), array(4, 2), array(-1, 4)).
1778 function decompose_update_into_safe_changes(array $newvalues, $unusedvalue) {
1779 $nontrivialmap = array();
1780 foreach ($newvalues as $from => $to) {
1781 if ($from == $unusedvalue || $to == $unusedvalue) {
1782 throw new \coding_exception('Supposedly unused value ' . $unusedvalue . ' is actually used!');
1784 if ($from != $to) {
1785 $nontrivialmap[$from] = $to;
1789 if (empty($nontrivialmap)) {
1790 return array();
1793 // First we deal with all renames that are not part of cycles.
1794 // This bit is O(n^2) and it ought to be possible to do better,
1795 // but it does not seem worth the effort.
1796 $safechanges = array();
1797 $nontrivialmapchanged = true;
1798 while ($nontrivialmapchanged) {
1799 $nontrivialmapchanged = false;
1801 foreach ($nontrivialmap as $from => $to) {
1802 if (array_key_exists($to, $nontrivialmap)) {
1803 continue; // Cannot currenly do this rename.
1805 // Is safe to do this rename now.
1806 $safechanges[] = array($from, $to);
1807 unset($nontrivialmap[$from]);
1808 $nontrivialmapchanged = true;
1812 // Are we done?
1813 if (empty($nontrivialmap)) {
1814 return $safechanges;
1817 // Now what is left in $nontrivialmap must be a permutation,
1818 // which must be a combination of disjoint cycles. We need to break them.
1819 while (!empty($nontrivialmap)) {
1820 // Extract the first cycle.
1821 reset($nontrivialmap);
1822 $current = $cyclestart = key($nontrivialmap);
1823 $cycle = array();
1824 do {
1825 $cycle[] = $current;
1826 $next = $nontrivialmap[$current];
1827 unset($nontrivialmap[$current]);
1828 $current = $next;
1829 } while ($current != $cyclestart);
1831 // Now convert it to a sequence of safe renames by using a temp.
1832 $safechanges[] = array($cyclestart, $unusedvalue);
1833 $cycle[0] = $unusedvalue;
1834 $to = $cyclestart;
1835 while ($from = array_pop($cycle)) {
1836 $safechanges[] = array($from, $to);
1837 $to = $from;
1841 return $safechanges;
1845 * Return maximum number of courses in a category
1847 * @uses MAX_COURSES_IN_CATEGORY
1848 * @return int number of courses
1850 function get_max_courses_in_category() {
1851 global $CFG;
1852 // Use default MAX_COURSES_IN_CATEGORY if $CFG->maxcoursesincategory is not set or invalid.
1853 if (!isset($CFG->maxcoursesincategory) || clean_param($CFG->maxcoursesincategory, PARAM_INT) == 0) {
1854 return MAX_COURSES_IN_CATEGORY;
1855 } else {
1856 return $CFG->maxcoursesincategory;
1861 * Prepare a safe ORDER BY statement from user interactable requests.
1863 * This allows safe user specified sorting (ORDER BY), by abstracting the SQL from the value being requested by the user.
1864 * A standard string (and optional direction) can be specified, which will be mapped to a predefined allow list of SQL ordering.
1865 * The mapping can optionally include a 'default', which will be used if the key provided is invalid.
1867 * Example usage:
1868 * -If $orderbymap = [
1869 * 'courseid' => 'c.id',
1870 * 'somecustomvalue'=> 'c.startdate, c.shortname',
1871 * 'default' => 'c.fullname',
1873 * -A value from the map array's keys can be passed in by a user interaction (eg web service) along with an optional direction.
1874 * -get_safe_orderby($orderbymap, 'courseid', 'DESC') would return: ORDER BY c.id DESC
1875 * -get_safe_orderby($orderbymap, 'somecustomvalue') would return: ORDER BY c.startdate, c.shortname
1876 * -get_safe_orderby($orderbymap, 'invalidblah', 'DESC') would return: ORDER BY c.fullname DESC
1877 * -If no default key was specified in $orderbymap, the invalidblah example above would return empty string.
1879 * @param array $orderbymap An array in the format [keystring => sqlstring]. A default fallback can be set with the key 'default'.
1880 * @param string $orderbykey A string to be mapped to a key in $orderbymap.
1881 * @param string $direction Optional ORDER BY direction (ASC/DESC, case insensitive).
1882 * @param bool $useprefix Whether ORDER BY is prefixed to the output (true by default). This should not be modified in most cases.
1883 * It is included to enable get_safe_orderby_multiple() to use this function multiple times.
1884 * @return string The ORDER BY statement, or empty string if $orderbykey is invalid and no default is mapped.
1886 function get_safe_orderby(array $orderbymap, string $orderbykey, string $direction = '', bool $useprefix = true): string {
1887 $orderby = $useprefix ? ' ORDER BY ' : '';
1888 $output = '';
1890 // Only include an order direction if ASC/DESC is explicitly specified (case insensitive).
1891 $direction = strtoupper($direction);
1892 if (!in_array($direction, ['ASC', 'DESC'], true)) {
1893 $direction = '';
1894 } else {
1895 $direction = " {$direction}";
1898 // Prepare the statement if the key maps to a defined sort parameter.
1899 if (isset($orderbymap[$orderbykey])) {
1900 $output = "{$orderby}{$orderbymap[$orderbykey]}{$direction}";
1901 } else if (array_key_exists('default', $orderbymap)) {
1902 // Fall back to use the default if one is specified.
1903 $output = "{$orderby}{$orderbymap['default']}{$direction}";
1906 return $output;
1910 * Prepare a safe ORDER BY statement from user interactable requests using multiple values.
1912 * This allows safe user specified sorting (ORDER BY) similar to get_safe_orderby(), but supports multiple keys and directions.
1913 * This is useful in cases where combinations of columns are needed and/or each item requires a specified direction (ASC/DESC).
1914 * The mapping can optionally include a 'default', which will be used if the key provided is invalid.
1916 * Example usage:
1917 * -If $orderbymap = [
1918 * 'courseid' => 'c.id',
1919 * 'fullname'=> 'c.fullname',
1920 * 'default' => 'c.startdate',
1922 * -An array of values from the map's keys can be passed in by a user interaction (eg web service), with optional directions.
1923 * -get_safe_orderby($orderbymap, ['courseid', 'fullname'], ['DESC', 'ASC']) would return: ORDER BY c.id DESC, c.fullname ASC
1924 * -get_safe_orderby($orderbymap, ['courseid', 'invalidblah'], ['aaa', 'DESC']) would return: ORDER BY c.id, c.startdate DESC
1925 * -If no default key was specified in $orderbymap, the invalidblah example above would return: ORDER BY c.id
1927 * @param array $orderbymap An array in the format [keystring => sqlstring]. A default fallback can be set with the key 'default'.
1928 * @param array $orderbykeys An array of strings to be mapped to keys in $orderbymap.
1929 * @param array $directions Optional array of ORDER BY direction (ASC/DESC, case insensitive).
1930 * The array keys should match array keys in $orderbykeys.
1931 * @return string The ORDER BY statement, or empty string if $orderbykeys contains no valid items and no default is mapped.
1933 function get_safe_orderby_multiple(array $orderbymap, array $orderbykeys, array $directions = []): string {
1934 $output = '';
1936 // Check each key for a valid mapping and add to the ORDER BY statement (invalid entries will be empty strings).
1937 foreach ($orderbykeys as $index => $orderbykey) {
1938 $direction = $directions[$index] ?? '';
1939 $safeorderby = get_safe_orderby($orderbymap, $orderbykey, $direction, false);
1941 if (!empty($safeorderby)) {
1942 $output .= ", {$safeorderby}";
1946 // Prefix with ORDER BY if any valid ordering is specified (and remove comma from the start).
1947 if (!empty($output)) {
1948 $output = ' ORDER BY' . ltrim($output, ',');
1951 return $output;