2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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
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();
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);
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);
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
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);
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() {
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.
74 if (isset($mainadmin) and $prevadmins === $CFG->siteadmins
) {
75 return clone($mainadmin);
80 foreach (explode(',', $CFG->siteadmins
) as $id) {
81 if ($user = $DB->get_record('user', array('id'=>$id, 'deleted'=>0))) {
88 $prevadmins = $CFG->siteadmins
;
89 return clone($mainadmin);
91 // this should not happen
97 * Returns list of all admins, using 1 DB query
101 function get_admins() {
104 if (empty($CFG->siteadmins
)) { // Should not happen on an ordinary site
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);
115 foreach (explode(',', $CFG->siteadmins
) as $id) {
117 if (!isset($records[$id])) {
118 // User does not exist, this should not happen.
121 $admins[$records[$id]->id
] = $records[$id];
128 * Search through course users
130 * If $coursid specifies the site course then this function searches
131 * through all undeleted and confirmed users
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
144 function search_users($courseid, $groupid, $searchtext, $sort='', array $exceptions=null) {
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";
158 $order = "ORDER BY $sort";
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
173 return $DB->get_records_sql($sql, $params);
177 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
179 JOIN {groups_members} gm ON gm.userid = u.id
180 WHERE $select AND gm.groupid = :groupid
183 $params['groupid'] = $groupid;
184 return $DB->get_records_sql($sql, $params);
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
194 JOIN {role_assignments} ra ON ra.userid = u.id
195 WHERE $select AND ra.contextid $relatedctxsql
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
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
222 * @param array $exclude Array of user ids to exclude (empty = don't exclude)
223 * @param array $includeonly If specified, only returns users that have ids
224 * incldued in this array (empty = don't restrict)
225 * @return array an array with two elements, a fragment of SQL to go in the
226 * where clause the query, and an associative array containing any required
227 * parameters (using named placeholders).
229 function users_search_sql($search, $u = 'u', $searchanywhere = true, array $extrafields = array(),
230 array $exclude = null, array $includeonly = null) {
239 // If we have a $search string, put a field LIKE '$search%' condition on each field.
242 $DB->sql_fullname($u . 'firstname', $u . 'lastname'),
243 $conditions[] = $u . 'lastname'
245 foreach ($extrafields as $field) {
246 $conditions[] = $u . $field;
248 if ($searchanywhere) {
249 $searchparam = '%' . $search . '%';
251 $searchparam = $search . '%';
254 foreach ($conditions as $key => $condition) {
255 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false, false);
256 $params["con{$i}00"] = $searchparam;
259 $tests[] = '(' . implode(' OR ', $conditions) . ')';
262 // Add some additional sensible conditions.
263 $tests[] = $u . "id <> :guestid";
264 $params['guestid'] = $CFG->siteguest
;
265 $tests[] = $u . 'deleted = 0';
266 $tests[] = $u . 'confirmed = 1';
268 // If we are being asked to exclude any users, do that.
269 if (!empty($exclude)) {
270 list($usertest, $userparams) = $DB->get_in_or_equal($exclude, SQL_PARAMS_NAMED
, 'ex', false);
271 $tests[] = $u . 'id ' . $usertest;
272 $params = array_merge($params, $userparams);
275 // If we are validating a set list of userids, add an id IN (...) test.
276 if (!empty($includeonly)) {
277 list($usertest, $userparams) = $DB->get_in_or_equal($includeonly, SQL_PARAMS_NAMED
, 'val');
278 $tests[] = $u . 'id ' . $usertest;
279 $params = array_merge($params, $userparams);
282 // In case there are no tests, add one result (this makes it easier to combine
283 // this with an existing query as you can always add AND $sql).
288 // Combing the conditions and return.
289 return array(implode(' AND ', $tests), $params);
294 * This function generates the standard ORDER BY clause for use when generating
295 * lists of users. If you don't have a reason to use a different order, then
296 * you should use this method to generate the order when displaying lists of users.
298 * If the optional $search parameter is passed, then exact matches to the search
299 * will be sorted first. For example, suppose you have two users 'Al Zebra' and
300 * 'Alan Aardvark'. The default sort is Alan, then Al. If, however, you search for
301 * 'Al', then Al will be listed first. (With two users, this is not a big deal,
302 * but with thousands of users, it is essential.)
304 * The list of fields scanned for exact matches are:
307 * - $DB->sql_fullname
308 * - those returned by get_extra_user_fields
310 * If named parameters are used (which is the default, and highly recommended),
311 * then the parameter names are like :usersortexactN, where N is an int.
313 * The simplest possible example use is:
314 * list($sort, $params) = users_order_by_sql();
315 * $sql = 'SELECT * FROM {users} ORDER BY ' . $sort;
317 * A more complex example, showing that this sort can be combined with other sorts:
318 * list($sort, $sortparams) = users_order_by_sql('u');
319 * $sql = "SELECT g.id AS groupid, gg.groupingid, u.id AS userid, u.firstname, u.lastname, u.idnumber, u.username
321 * LEFT JOIN {groupings_groups} gg ON g.id = gg.groupid
322 * LEFT JOIN {groups_members} gm ON g.id = gm.groupid
323 * LEFT JOIN {user} u ON gm.userid = u.id
324 * WHERE g.courseid = :courseid $groupwhere $groupingwhere
325 * ORDER BY g.name, $sort";
326 * $params += $sortparams;
328 * An example showing the use of $search:
329 * list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
330 * $order = ' ORDER BY ' . $sort;
331 * $params += $sortparams;
332 * $availableusers = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage);
334 * @param string $usertablealias (optional) any table prefix for the {users} table. E.g. 'u'.
335 * @param string $search (optional) a current search string. If given,
336 * any exact matches to this string will be sorted first.
337 * @param context $context the context we are in. Use by get_extra_user_fields.
338 * Defaults to $PAGE->context.
339 * @return array with two elements:
340 * string SQL fragment to use in the ORDER BY clause. For example, "firstname, lastname".
341 * array of parameters used in the SQL fragment.
343 function users_order_by_sql($usertablealias = '', $search = null, context
$context = null) {
346 if ($usertablealias) {
347 $tableprefix = $usertablealias . '.';
352 $sort = "{$tableprefix}lastname, {$tableprefix}firstname, {$tableprefix}id";
356 return array($sort, $params);
360 $context = $PAGE->context
;
363 $exactconditions = array();
364 $paramkey = 'usersortexact1';
366 $exactconditions[] = $DB->sql_fullname($tableprefix . 'firstname', $tableprefix . 'lastname') .
368 $params[$paramkey] = $search;
371 // TODO Does not support custom user profile fields (MDL-70456).
372 $fieldstocheck = array_merge(array('firstname', 'lastname'), \core_user\fields
::get_identity_fields($context, false));
373 foreach ($fieldstocheck as $key => $field) {
374 $exactconditions[] = 'LOWER(' . $tableprefix . $field . ') = LOWER(:' . $paramkey . ')';
375 $params[$paramkey] = $search;
379 $sort = 'CASE WHEN ' . implode(' OR ', $exactconditions) .
380 ' THEN 0 ELSE 1 END, ' . $sort;
382 return array($sort, $params);
386 * Returns a subset of users
389 * @uses DEBUG_DEVELOPER
390 * @uses SQL_PARAMS_NAMED
391 * @param bool $get If false then only a count of the records is returned
392 * @param string $search A simple string to search for
393 * @param bool $confirmed A switch to allow/disallow unconfirmed users
394 * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
395 * @param string $sort A SQL snippet for the sorting criteria to use
396 * @param string $firstinitial Users whose first name starts with $firstinitial
397 * @param string $lastinitial Users whose last name starts with $lastinitial
398 * @param string $page The page or records to return
399 * @param string $recordsperpage The number of records to return per page
400 * @param string $fields A comma separated list of fields to be returned from the chosen table.
401 * @return array|int|bool {@link $USER} records unless get is false in which case the integer count of the records found is returned.
402 * False is returned if an error is encountered.
404 function get_users($get=true, $search='', $confirmed=false, array $exceptions=null, $sort='firstname ASC',
405 $firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields='*', $extraselect='', array $extraparams=null) {
408 if ($get && !$recordsperpage) {
409 debugging('Call to get_users with $get = true no $recordsperpage limit. ' .
410 'On large installations, this will probably cause an out of memory error. ' .
411 'Please think again and change your code so that it does not try to ' .
412 'load so much data into memory.', DEBUG_DEVELOPER
);
415 $fullname = $DB->sql_fullname();
417 $select = " id <> :guestid AND deleted = 0";
418 $params = array('guestid'=>$CFG->siteguest
);
420 if (!empty($search)){
421 $search = trim($search);
422 $select .= " AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('email', ':search2', false)." OR username = :search3)";
423 $params['search1'] = "%$search%";
424 $params['search2'] = "%$search%";
425 $params['search3'] = "$search";
429 $select .= " AND confirmed = 1";
433 list($exceptions, $eparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED
, 'ex', false);
434 $params = $params +
$eparams;
435 $select .= " AND id $exceptions";
439 $select .= " AND ".$DB->sql_like('firstname', ':fni', false, false);
440 $params['fni'] = "$firstinitial%";
443 $select .= " AND ".$DB->sql_like('lastname', ':lni', false, false);
444 $params['lni'] = "$lastinitial%";
448 $select .= " AND $extraselect";
449 $params = $params +
(array)$extraparams;
453 return $DB->get_records_select('user', $select, $params, $sort, $fields, $page, $recordsperpage);
455 return $DB->count_records_select('user', $select, $params);
461 * Return filtered (if provided) list of users in site, except guest and deleted users.
463 * @param string $sort An SQL field to sort by
464 * @param string $dir The sort direction ASC|DESC
465 * @param int $page The page or records to return
466 * @param int $recordsperpage The number of records to return per page
467 * @param string $search A simple string to search for
468 * @param string $firstinitial Users whose first name starts with $firstinitial
469 * @param string $lastinitial Users whose last name starts with $lastinitial
470 * @param string $extraselect An additional SQL select statement to append to the query
471 * @param array $extraparams Additional parameters to use for the above $extraselect
472 * @param stdClass $extracontext If specified, will include user 'extra fields'
473 * as appropriate for current user and given context
474 * @return array Array of {@link $USER} records
476 function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0,
477 $search='', $firstinitial='', $lastinitial='', $extraselect='',
478 array $extraparams=null, $extracontext = null) {
481 $fullname = $DB->sql_fullname();
483 $select = "deleted <> 1 AND u.id <> :guestid";
484 $params = array('guestid' => $CFG->siteguest
);
486 if (!empty($search)) {
487 $search = trim($search);
488 $select .= " AND (". $DB->sql_like($fullname, ':search1', false, false).
489 " OR ". $DB->sql_like('email', ':search2', false, false).
490 " OR username = :search3)";
491 $params['search1'] = "%$search%";
492 $params['search2'] = "%$search%";
493 $params['search3'] = "$search";
497 $select .= " AND ". $DB->sql_like('firstname', ':fni', false, false);
498 $params['fni'] = "$firstinitial%";
501 $select .= " AND ". $DB->sql_like('lastname', ':lni', false, false);
502 $params['lni'] = "$lastinitial%";
506 // The extra WHERE clause may refer to the 'id' column which can now be ambiguous because we
507 // changed the query to include joins, so replace any 'id' that is on its own (no alias)
509 $extraselect = preg_replace('~([ =]|^)id([ =]|$)~', '$1u.id$2', $extraselect);
510 $select .= " AND $extraselect";
511 $params = $params +
(array)$extraparams;
515 $sort = " ORDER BY $sort $dir";
518 // If a context is specified, get extra user fields that the current user
519 // is supposed to see, otherwise just get the name fields.
520 $userfields = \core_user\fields
::for_name();
522 $userfields->with_identity($extracontext, true);
524 $userfields->excluding('id', 'username', 'email', 'city', 'country', 'lastaccess', 'confirmed', 'mnethostid');
525 ['selects' => $selects, 'joins' => $joins, 'params' => $joinparams] =
526 (array)$userfields->get_sql('u', true);
528 // warning: will return UNCONFIRMED USERS
529 return $DB->get_records_sql("SELECT u.id, username, email, city, country, lastaccess, confirmed, mnethostid, suspended $selects
533 $sort", array_merge($params, $joinparams), $page, $recordsperpage);
539 * Full list of users that have confirmed their accounts.
542 * @return array of unconfirmed users
544 function get_users_confirmed() {
546 return $DB->get_records_sql("SELECT *
548 WHERE confirmed = 1 AND deleted = 0 AND id <> ?", array($CFG->siteguest
));
552 /// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
556 * Returns $course object of the top-level site.
558 * @return object A {@link $COURSE} object for the site, exception if not found
560 function get_site() {
563 if (!empty($SITE->id
)) { // We already have a global to use, so return that
567 if ($course = $DB->get_record('course', array('category'=>0))) {
570 // course table exists, but the site is not there,
571 // unfortunately there is no automatic way to recover
572 throw new moodle_exception('nosite', 'error');
577 * Gets a course object from database. If the course id corresponds to an
578 * already-loaded $COURSE or $SITE object, then the loaded object will be used,
579 * saving a database query.
581 * If it reuses an existing object, by default the object will be cloned. This
582 * means you can modify the object safely without affecting other code.
584 * @param int $courseid Course id
585 * @param bool $clone If true (default), makes a clone of the record
586 * @return stdClass A course object
587 * @throws dml_exception If not found in database
589 function get_course($courseid, $clone = true) {
590 global $DB, $COURSE, $SITE;
591 if (!empty($COURSE->id
) && $COURSE->id
== $courseid) {
592 return $clone ?
clone($COURSE) : $COURSE;
593 } else if (!empty($SITE->id
) && $SITE->id
== $courseid) {
594 return $clone ?
clone($SITE) : $SITE;
596 return $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST
);
601 * Returns list of courses, for whole site, or category
603 * Returns list of courses, for whole site, or category
604 * Important: Using c.* for fields is extremely expensive because
605 * we are using distinct. You almost _NEVER_ need all the fields
606 * in such a large SELECT
608 * Consider using core_course_category::get_courses()
609 * or core_course_category::search_courses() instead since they use caching.
614 * @uses CONTEXT_COURSE
615 * @param string|int $categoryid Either a category id or 'all' for everything
616 * @param string $sort A field and direction to sort by
617 * @param string $fields The additional fields to return (note that "id, category, visible" are always present)
618 * @return array Array of courses
620 function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
622 global $USER, $CFG, $DB;
626 if ($categoryid !== "all" && is_numeric($categoryid)) {
627 $categoryselect = "WHERE c.category = :catid";
628 $params['catid'] = $categoryid;
630 $categoryselect = "";
636 $sortstatement = "ORDER BY $sort";
639 $visiblecourses = array();
641 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
642 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
643 $params['contextlevel'] = CONTEXT_COURSE
;
645 // The fields "id, category, visible" are required in the subsequent loop and must always be present.
646 if ($fields !== 'c.*') {
647 $fieldarray = array_merge(
648 // Split fields on comma + zero or more whitespace, merge with required fields.
649 preg_split('/,\s*/', $fields), [
655 $fields = implode(',', array_unique($fieldarray));
658 $sql = "SELECT $fields $ccselect
664 // pull out all course matching the cat
665 if ($courses = $DB->get_records_sql($sql, $params)) {
667 // loop throught them
668 foreach ($courses as $course) {
669 context_helper
::preload_from_record($course);
670 if (core_course_category
::can_view_course_info($course)) {
671 $visiblecourses [$course->id
] = $course;
675 return $visiblecourses;
679 * A list of courses that match a search
683 * @param array $searchterms An array of search criteria
684 * @param string $sort A field and direction to sort by
685 * @param int $page The page number to get
686 * @param int $recordsperpage The number of records per page
687 * @param int $totalcount Passed in by reference.
688 * @param array $requiredcapabilities Extra list of capabilities used to filter courses
689 * @param array $searchcond additional search conditions, for example ['c.enablecompletion = :p1']
690 * @param array $params named parameters for additional search conditions, for example ['p1' => 1]
691 * @return stdClass[] {@link $COURSE} records
693 function get_courses_search($searchterms, $sort, $page, $recordsperpage, &$totalcount,
694 $requiredcapabilities = array(), $searchcond = [], $params = []) {
697 if ($DB->sql_regex_supported()) {
698 $REGEXP = $DB->sql_regex(true);
699 $NOTREGEXP = $DB->sql_regex(false);
704 // Thanks Oracle for your non-ansi concat and type limits in coalesce. MDL-29912
705 if ($DB->get_dbfamily() == 'oracle') {
706 $concat = "(c.summary|| ' ' || c.fullname || ' ' || c.idnumber || ' ' || c.shortname)";
708 $concat = $DB->sql_concat("COALESCE(c.summary, '')", "' '", 'c.fullname', "' '", 'c.idnumber', "' '", 'c.shortname');
711 foreach ($searchterms as $searchterm) {
714 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
715 /// will use it to simulate the "-" operator with LIKE clause
717 /// Under Oracle and MSSQL, trim the + and - operators and perform
718 /// simpler LIKE (or NOT LIKE) queries
719 if (!$DB->sql_regex_supported()) {
720 if (substr($searchterm, 0, 1) == '-') {
723 $searchterm = trim($searchterm, '+-');
726 // TODO: +- may not work for non latin languages
728 if (substr($searchterm,0,1) == '+') {
729 $searchterm = trim($searchterm, '+-');
730 $searchterm = preg_quote($searchterm, '|');
731 $searchcond[] = "$concat $REGEXP :ss$i";
732 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
734 } else if ((substr($searchterm,0,1) == "-") && (core_text
::strlen($searchterm) > 1)) {
735 $searchterm = trim($searchterm, '+-');
736 $searchterm = preg_quote($searchterm, '|');
737 $searchcond[] = "$concat $NOTREGEXP :ss$i";
738 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
741 $searchcond[] = $DB->sql_like($concat,":ss$i", false, true, $NOT);
742 $params['ss'.$i] = "%$searchterm%";
746 if (empty($searchcond)) {
747 $searchcond = array('1 = 1');
750 $searchcond = implode(" AND ", $searchcond);
753 $c = 0; // counts how many visible courses we've seen
756 $limitfrom = $page * $recordsperpage;
757 $limitto = $limitfrom +
$recordsperpage;
759 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
760 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
761 $params['contextlevel'] = CONTEXT_COURSE
;
763 $sql = "SELECT c.* $ccselect
766 WHERE $searchcond AND c.id <> ".SITEID
."
769 $mycourses = enrol_get_my_courses();
770 $rs = $DB->get_recordset_sql($sql, $params);
771 foreach($rs as $course) {
772 // Preload contexts only for hidden courses or courses we need to return.
773 context_helper
::preload_from_record($course);
774 $coursecontext = context_course
::instance($course->id
);
775 if (!array_key_exists($course->id
, $mycourses) && !core_course_category
::can_view_course_info($course)) {
778 if (!empty($requiredcapabilities)) {
779 if (!has_all_capabilities($requiredcapabilities, $coursecontext)) {
783 // Don't exit this loop till the end
784 // we need to count all the visible courses
785 // to update $totalcount
786 if ($c >= $limitfrom && $c < $limitto) {
787 $courses[$course->id
] = $course;
793 // our caller expects 2 bits of data - our return
794 // array, and an updated $totalcount
800 * Fixes course category and course sortorder, also verifies category and course parents and paths.
801 * (circular references are not fixed)
805 * @uses MAX_COURSE_CATEGORIES
807 * @uses CONTEXT_COURSE
810 function fix_course_sortorder() {
813 //WARNING: this is PHP5 only code!
815 // if there are any changes made to courses or categories we will trigger
816 // the cache events to purge all cached courses/categories data
817 $cacheevents = array();
819 if ($unsorted = $DB->get_records('course_categories', array('sortorder'=>0))) {
820 //move all categories that are not sorted yet to the end
821 $DB->set_field('course_categories', 'sortorder',
822 get_max_courses_in_category() * MAX_COURSE_CATEGORIES
, array('sortorder' => 0));
823 $cacheevents['changesincoursecat'] = true;
826 $allcats = $DB->get_records('course_categories', null, 'sortorder, id', 'id, sortorder, parent, depth, path');
828 $brokencats = array();
829 foreach ($allcats as $cat) {
830 $sortorder = (int)$cat->sortorder
;
832 while(isset($topcats[$sortorder])) {
835 $topcats[$sortorder] = $cat;
838 if (!isset($allcats[$cat->parent
])) {
839 $brokencats[] = $cat;
842 if (!isset($allcats[$cat->parent
]->children
)) {
843 $allcats[$cat->parent
]->children
= array();
845 while(isset($allcats[$cat->parent
]->children
[$sortorder])) {
848 $allcats[$cat->parent
]->children
[$sortorder] = $cat;
852 // add broken cats to category tree
854 $defaultcat = reset($topcats);
855 foreach ($brokencats as $cat) {
860 // now walk recursively the tree and fix any problems found
862 $fixcontexts = array();
863 if (_fix_course_cats($topcats, $sortorder, 0, 0, '', $fixcontexts)) {
864 $cacheevents['changesincoursecat'] = true;
867 // detect if there are "multiple" frontpage courses and fix them if needed
868 $frontcourses = $DB->get_records('course', array('category'=>0), 'id');
869 if (count($frontcourses) > 1) {
870 if (isset($frontcourses[SITEID
])) {
871 $frontcourse = $frontcourses[SITEID
];
872 unset($frontcourses[SITEID
]);
874 $frontcourse = array_shift($frontcourses);
876 $defaultcat = reset($topcats);
877 foreach ($frontcourses as $course) {
878 $DB->set_field('course', 'category', $defaultcat->id
, array('id'=>$course->id
));
879 $context = context_course
::instance($course->id
);
880 $fixcontexts[$context->id
] = $context;
881 $cacheevents['changesincourse'] = true;
883 unset($frontcourses);
885 $frontcourse = reset($frontcourses);
888 // now fix the paths and depths in context table if needed
890 foreach ($fixcontexts as $fixcontext) {
891 $fixcontext->reset_paths(false);
893 context_helper
::build_all_paths(false);
895 $cacheevents['changesincourse'] = true;
896 $cacheevents['changesincoursecat'] = true;
904 // fix frontpage course sortorder
905 if ($frontcourse->sortorder
!= 1) {
906 $DB->set_field('course', 'sortorder', 1, array('id'=>$frontcourse->id
));
907 $cacheevents['changesincourse'] = true;
910 // now fix the course counts in category records if needed
911 $sql = "SELECT cc.id, cc.coursecount, COUNT(c.id) AS newcount
912 FROM {course_categories} cc
913 LEFT JOIN {course} c ON c.category = cc.id
914 GROUP BY cc.id, cc.coursecount
915 HAVING cc.coursecount <> COUNT(c.id)";
917 if ($updatecounts = $DB->get_records_sql($sql)) {
918 // categories with more courses than MAX_COURSES_IN_CATEGORY
919 $categories = array();
920 foreach ($updatecounts as $cat) {
921 $cat->coursecount
= $cat->newcount
;
922 if ($cat->coursecount
>= get_max_courses_in_category()) {
923 $categories[] = $cat->id
;
925 unset($cat->newcount
);
926 $DB->update_record_raw('course_categories', $cat, true);
928 if (!empty($categories)) {
929 $str = implode(', ', $categories);
930 debugging("The number of courses (category id: $str) has reached max number of courses " .
931 "in a category (" . get_max_courses_in_category() . "). It will cause a sorting performance issue. " .
932 "Please set higher value for \$CFG->maxcoursesincategory in config.php. " .
933 "Please also make sure \$CFG->maxcoursesincategory * MAX_COURSE_CATEGORIES less than max integer. " .
934 "See tracker issues: MDL-25669 and MDL-69573", DEBUG_DEVELOPER
);
936 $cacheevents['changesincoursecat'] = true;
939 // now make sure that sortorders in course table are withing the category sortorder ranges
940 $sql = "SELECT DISTINCT cc.id, cc.sortorder
941 FROM {course_categories} cc
942 JOIN {course} c ON c.category = cc.id
943 WHERE c.sortorder < cc.sortorder OR c.sortorder > cc.sortorder + " . get_max_courses_in_category();
945 if ($fixcategories = $DB->get_records_sql($sql)) {
946 //fix the course sortorder ranges
947 foreach ($fixcategories as $cat) {
948 $sql = "UPDATE {course}
949 SET sortorder = ".$DB->sql_modulo('sortorder', get_max_courses_in_category())." + ?
951 $DB->execute($sql, array($cat->sortorder
, $cat->id
));
953 $cacheevents['changesincoursecat'] = true;
955 unset($fixcategories);
957 // categories having courses with sortorder duplicates or having gaps in sortorder
958 $sql = "SELECT DISTINCT c1.category AS id , cc.sortorder
960 JOIN {course} c2 ON c1.sortorder = c2.sortorder
961 JOIN {course_categories} cc ON (c1.category = cc.id)
962 WHERE c1.id <> c2.id";
963 $fixcategories = $DB->get_records_sql($sql);
965 $sql = "SELECT cc.id, cc.sortorder, cc.coursecount, MAX(c.sortorder) AS maxsort, MIN(c.sortorder) AS minsort
966 FROM {course_categories} cc
967 JOIN {course} c ON c.category = cc.id
968 GROUP BY cc.id, cc.sortorder, cc.coursecount
969 HAVING (MAX(c.sortorder) <> cc.sortorder + cc.coursecount) OR (MIN(c.sortorder) <> cc.sortorder + 1)";
970 $gapcategories = $DB->get_records_sql($sql);
972 foreach ($gapcategories as $cat) {
973 if (isset($fixcategories[$cat->id
])) {
974 // duplicates detected already
976 } else if ($cat->minsort
== $cat->sortorder
and $cat->maxsort
== $cat->sortorder +
$cat->coursecount
- 1) {
977 // easy - new course inserted with sortorder 0, the rest is ok
978 $sql = "UPDATE {course}
979 SET sortorder = sortorder + 1
981 $DB->execute($sql, array($cat->id
));
984 // it needs full resorting
985 $fixcategories[$cat->id
] = $cat;
987 $cacheevents['changesincourse'] = true;
989 unset($gapcategories);
991 // fix course sortorders in problematic categories only
992 foreach ($fixcategories as $cat) {
994 $courses = $DB->get_records('course', array('category'=>$cat->id
), 'sortorder ASC, id DESC', 'id, sortorder');
995 foreach ($courses as $course) {
996 if ($course->sortorder
!= $cat->sortorder +
$i) {
997 $course->sortorder
= $cat->sortorder +
$i;
998 $DB->update_record_raw('course', $course, true);
999 $cacheevents['changesincourse'] = true;
1005 // advise all caches that need to be rebuilt
1006 foreach (array_keys($cacheevents) as $event) {
1007 cache_helper
::purge_by_event($event);
1012 * Internal recursive category verification function, do not use directly!
1014 * @todo Document the arguments of this function better
1017 * @uses CONTEXT_COURSECAT
1018 * @param array $children
1019 * @param int $sortorder
1020 * @param string $parent
1022 * @param string $path
1023 * @param array $fixcontexts
1024 * @return bool if changes were made
1026 function _fix_course_cats($children, &$sortorder, $parent, $depth, $path, &$fixcontexts) {
1030 $changesmade = false;
1032 foreach ($children as $cat) {
1033 $sortorder = $sortorder +
get_max_courses_in_category();
1035 if ($parent != $cat->parent
or $depth != $cat->depth
or $path.'/'.$cat->id
!= $cat->path
) {
1036 $cat->parent
= $parent;
1037 $cat->depth
= $depth;
1038 $cat->path
= $path.'/'.$cat->id
;
1041 // make sure context caches are rebuild and dirty contexts marked
1042 $context = context_coursecat
::instance($cat->id
);
1043 $fixcontexts[$context->id
] = $context;
1045 if ($cat->sortorder
!= $sortorder) {
1046 $cat->sortorder
= $sortorder;
1050 $DB->update_record('course_categories', $cat, true);
1051 $changesmade = true;
1053 if (isset($cat->children
)) {
1054 if (_fix_course_cats($cat->children
, $sortorder, $cat->id
, $cat->depth
, $cat->path
, $fixcontexts)) {
1055 $changesmade = true;
1059 return $changesmade;
1063 * List of remote courses that a user has access to via MNET.
1064 * Works only on the IDP
1068 * @param int @userid The user id to get remote courses for
1069 * @return array Array of {@link $COURSE} of course objects
1071 function get_my_remotecourses($userid=0) {
1074 if (empty($userid)) {
1075 $userid = $USER->id
;
1078 // we can not use SELECT DISTINCT + text field (summary) because of MS SQL and Oracle, subselect used therefore
1079 $sql = "SELECT c.id, c.remoteid, c.shortname, c.fullname,
1080 c.hostid, c.summary, c.summaryformat, c.categoryname AS cat_name,
1082 FROM {mnetservice_enrol_courses} c
1083 JOIN (SELECT DISTINCT hostid, remotecourseid
1084 FROM {mnetservice_enrol_enrolments}
1086 ) e ON (e.hostid = c.hostid AND e.remotecourseid = c.remoteid)
1087 JOIN {mnet_host} h ON h.id = c.hostid";
1089 return $DB->get_records_sql($sql, array($userid));
1093 * List of remote hosts that a user has access to via MNET.
1098 * @return array|bool Array of host objects or false
1100 function get_my_remotehosts() {
1103 if ($USER->mnethostid
== $CFG->mnet_localhost_id
) {
1104 return false; // Return nothing on the IDP
1106 if (!empty($USER->mnet_foreign_host_array
) && is_array($USER->mnet_foreign_host_array
)) {
1107 return $USER->mnet_foreign_host_array
;
1114 * Returns a menu of all available scales from the site as well as the given course
1117 * @param int $courseid The id of the course as found in the 'course' table.
1120 function get_scales_menu($courseid=0) {
1123 $sql = "SELECT id, name, courseid
1125 WHERE courseid = 0 or courseid = ?
1126 ORDER BY courseid ASC, name ASC";
1127 $params = array($courseid);
1129 $results = $DB->get_records_sql($sql, $params);
1130 foreach ($results as $index => $record) {
1131 $context = empty($record->courseid
) ? context_system
::instance() : context_course
::instance($record->courseid
);
1132 $scales[$index] = format_string($record->name
, false, ["context" => $context]);
1134 // Format: [id => 'scale name'].
1139 * Increment standard revision field.
1141 * The revision are based on current time and are incrementing.
1142 * There is a protection for runaway revisions, it may not go further than
1143 * one hour into future.
1145 * The field has to be XMLDB_TYPE_INTEGER with size 10.
1147 * @param string $table
1148 * @param string $field name of the field containing revision
1149 * @param string $select use empty string when updating all records
1150 * @param array $params optional select parameters
1152 function increment_revision_number($table, $field, $select, array $params = null) {
1156 $sql = "UPDATE {{$table}}
1158 WHEN $field IS NULL THEN $now
1159 WHEN $field < $now THEN $now
1160 WHEN $field > $now + 3600 THEN $now
1161 ELSE $field + 1 END)";
1163 $sql = $sql . " WHERE $select";
1165 $DB->execute($sql, $params);
1169 /// MODULE FUNCTIONS /////////////////////////////////////////////////
1172 * Just gets a raw list of all modules in a course
1175 * @param int $courseid The id of the course as found in the 'course' table.
1178 function get_course_mods($courseid) {
1181 if (empty($courseid)) {
1182 return false; // avoid warnings
1185 return $DB->get_records_sql("SELECT cm.*, m.name as modname
1186 FROM {modules} m, {course_modules} cm
1187 WHERE cm.course = ? AND cm.module = m.id AND m.visible = 1",
1188 array($courseid)); // no disabled mods
1193 * Given an id of a course module, finds the coursemodule description
1195 * Please note that this function performs 1-2 DB queries. When possible use cached
1196 * course modinfo. For example get_fast_modinfo($courseorid)->get_cm($cmid)
1197 * See also {@link cm_info::get_course_module_record()}
1200 * @param string $modulename name of module type, eg. resource, assignment,... (optional, slower and less safe if not specified)
1201 * @param int $cmid course module id (id in course_modules table)
1202 * @param int $courseid optional course id for extra validation
1203 * @param bool $sectionnum include relative section number (0,1,2 ...)
1204 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1205 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1206 * MUST_EXIST means throw exception if no record or multiple records found
1209 function get_coursemodule_from_id($modulename, $cmid, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING
) {
1212 $params = array('cmid'=>$cmid);
1215 if (!$modulename = $DB->get_field_sql("SELECT md.name
1217 JOIN {course_modules} cm ON cm.module = md.id
1218 WHERE cm.id = :cmid", $params, $strictness)) {
1222 if (!core_component
::is_valid_plugin_name('mod', $modulename)) {
1223 throw new coding_exception('Invalid modulename parameter');
1227 $params['modulename'] = $modulename;
1234 $courseselect = "AND cm.course = :courseid";
1235 $params['courseid'] = $courseid;
1239 $sectionfield = ", cw.section AS sectionnum";
1240 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1243 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1244 FROM {course_modules} cm
1245 JOIN {modules} md ON md.id = cm.module
1246 JOIN {".$modulename."} m ON m.id = cm.instance
1248 WHERE cm.id = :cmid AND md.name = :modulename
1251 return $DB->get_record_sql($sql, $params, $strictness);
1255 * Given an instance number of a module, finds the coursemodule description
1257 * Please note that this function performs DB query. When possible use cached course
1258 * modinfo. For example get_fast_modinfo($courseorid)->instances[$modulename][$instance]
1259 * See also {@link cm_info::get_course_module_record()}
1262 * @param string $modulename name of module type, eg. resource, assignment,...
1263 * @param int $instance module instance number (id in resource, assignment etc. table)
1264 * @param int $courseid optional course id for extra validation
1265 * @param bool $sectionnum include relative section number (0,1,2 ...)
1266 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1267 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1268 * MUST_EXIST means throw exception if no record or multiple records found
1271 function get_coursemodule_from_instance($modulename, $instance, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING
) {
1274 if (!core_component
::is_valid_plugin_name('mod', $modulename)) {
1275 throw new coding_exception('Invalid modulename parameter');
1278 $params = array('instance'=>$instance, 'modulename'=>$modulename);
1285 $courseselect = "AND cm.course = :courseid";
1286 $params['courseid'] = $courseid;
1290 $sectionfield = ", cw.section AS sectionnum";
1291 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1294 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1295 FROM {course_modules} cm
1296 JOIN {modules} md ON md.id = cm.module
1297 JOIN {".$modulename."} m ON m.id = cm.instance
1299 WHERE m.id = :instance AND md.name = :modulename
1302 return $DB->get_record_sql($sql, $params, $strictness);
1306 * Returns all course modules of given activity in course
1308 * @param string $modulename The module name (forum, quiz, etc.)
1309 * @param int $courseid The course id to get modules for
1310 * @param string $extrafields extra fields starting with m.
1311 * @return array Array of results
1313 function get_coursemodules_in_course($modulename, $courseid, $extrafields='') {
1316 if (!core_component
::is_valid_plugin_name('mod', $modulename)) {
1317 throw new coding_exception('Invalid modulename parameter');
1320 if (!empty($extrafields)) {
1321 $extrafields = ", $extrafields";
1324 $params['courseid'] = $courseid;
1325 $params['modulename'] = $modulename;
1328 return $DB->get_records_sql("SELECT cm.*, m.name, md.name as modname $extrafields
1329 FROM {course_modules} cm, {modules} md, {".$modulename."} m
1330 WHERE cm.course = :courseid AND
1331 cm.instance = m.id AND
1332 md.name = :modulename AND
1333 md.id = cm.module", $params);
1337 * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1339 * Returns an array of all the active instances of a particular
1340 * module in given courses, sorted in the order they are defined
1341 * in the course. Returns an empty array on any errors.
1343 * The returned objects includle the columns cw.section, cm.visible,
1344 * cm.groupmode, and cm.groupingid, and are indexed by cm.id.
1348 * @param string $modulename The name of the module to get instances for
1349 * @param array $courses an array of course objects.
1350 * @param int $userid
1351 * @param int $includeinvisible
1352 * @return array of module instance objects, including some extra fields from the course_modules
1353 * and course_sections tables, or an empty array if an error occurred.
1355 function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
1358 if (!core_component
::is_valid_plugin_name('mod', $modulename)) {
1359 throw new coding_exception('Invalid modulename parameter');
1362 $outputarray = array();
1364 if (empty($courses) ||
!is_array($courses) ||
count($courses) == 0) {
1365 return $outputarray;
1368 list($coursessql, $params) = $DB->get_in_or_equal(array_keys($courses), SQL_PARAMS_NAMED
, 'c0');
1369 $params['modulename'] = $modulename;
1371 if (!$rawmods = $DB->get_records_sql("SELECT cm.id AS coursemodule, m.*, cw.section, cm.visible AS visible,
1372 cm.groupmode, cm.groupingid
1373 FROM {course_modules} cm, {course_sections} cw, {modules} md,
1375 WHERE cm.course $coursessql AND
1376 cm.instance = m.id AND
1377 cm.section = cw.id AND
1378 md.name = :modulename AND
1379 md.id = cm.module", $params)) {
1380 return $outputarray;
1383 foreach ($courses as $course) {
1384 $modinfo = get_fast_modinfo($course, $userid);
1386 if (empty($modinfo->instances
[$modulename])) {
1390 foreach ($modinfo->instances
[$modulename] as $cm) {
1391 if (!$includeinvisible and !$cm->uservisible
) {
1394 if (!isset($rawmods[$cm->id
])) {
1397 $instance = $rawmods[$cm->id
];
1398 if (!empty($cm->extra
)) {
1399 $instance->extra
= $cm->extra
;
1401 $outputarray[] = $instance;
1405 return $outputarray;
1409 * Returns an array of all the active instances of a particular module in a given course,
1410 * sorted in the order they are defined.
1412 * Returns an array of all the active instances of a particular
1413 * module in a given course, sorted in the order they are defined
1414 * in the course. Returns an empty array on any errors.
1416 * The returned objects includle the columns cw.section, cm.visible,
1417 * cm.groupmode, and cm.groupingid, and are indexed by cm.id.
1419 * Simply calls {@link all_instances_in_courses()} with a single provided course
1421 * @param string $modulename The name of the module to get instances for
1422 * @param object $course The course obect.
1423 * @return array of module instance objects, including some extra fields from the course_modules
1424 * and course_sections tables, or an empty array if an error occurred.
1425 * @param int $userid
1426 * @param int $includeinvisible
1428 function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
1429 return get_all_instances_in_courses($modulename, array($course->id
=> $course), $userid, $includeinvisible);
1434 * Determine whether a module instance is visible within a course
1436 * Given a valid module object with info about the id and course,
1437 * and the module's type (eg "forum") returns whether the object
1438 * is visible or not according to the 'eye' icon only.
1440 * NOTE: This does NOT take into account visibility to a particular user.
1441 * To get visibility access for a specific user, use get_fast_modinfo, get a
1442 * cm_info object from this, and check the ->uservisible property; or use
1443 * the \core_availability\info_module::is_user_visible() static function.
1447 * @param $moduletype Name of the module eg 'forum'
1448 * @param $module Object which is the instance of the module
1449 * @return bool Success
1451 function instance_is_visible($moduletype, $module) {
1454 if (!empty($module->id
)) {
1455 $params = array('courseid'=>$module->course
, 'moduletype'=>$moduletype, 'moduleid'=>$module->id
);
1456 if ($records = $DB->get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.course
1457 FROM {course_modules} cm, {modules} m
1458 WHERE cm.course = :courseid AND
1459 cm.module = m.id AND
1460 m.name = :moduletype AND
1461 cm.instance = :moduleid", $params)) {
1463 foreach ($records as $record) { // there should only be one - use the first one
1464 return $record->visible
;
1468 return true; // visible by default!
1472 /// LOG FUNCTIONS /////////////////////////////////////////////////////
1475 * Get instance of log manager.
1477 * @param bool $forcereload
1478 * @return \core\log\manager
1480 function get_log_manager($forcereload = false) {
1481 /** @var \core\log\manager $singleton */
1482 static $singleton = null;
1484 if ($forcereload and isset($singleton)) {
1485 $singleton->dispose();
1489 if (isset($singleton)) {
1493 $classname = '\tool_log\log\manager';
1494 if (defined('LOG_MANAGER_CLASS')) {
1495 $classname = LOG_MANAGER_CLASS
;
1498 if (!class_exists($classname)) {
1499 if (!empty($classname)) {
1500 debugging("Cannot find log manager class '$classname'.", DEBUG_DEVELOPER
);
1502 $classname = '\core\log\dummy_manager';
1505 $singleton = new $classname();
1510 * Add an entry to the config log table.
1512 * These are "action" focussed rather than web server hits,
1513 * and provide a way to easily reconstruct changes to Moodle configuration.
1517 * @global moodle_database $DB
1518 * @global stdClass $USER
1519 * @param string $name The name of the configuration change action
1520 For example 'filter_active' when activating or deactivating a filter
1521 * @param string $oldvalue The config setting's previous value
1522 * @param string $value The config setting's new value
1523 * @param string $plugin Plugin name, for example a filter name when changing filter configuration
1526 function add_to_config_log($name, $oldvalue, $value, $plugin) {
1529 $log = new stdClass();
1530 // Use 0 as user id during install.
1531 $log->userid
= during_initial_install() ?
0 : $USER->id
;
1532 $log->timemodified
= time();
1534 $log->oldvalue
= $oldvalue;
1535 $log->value
= $value;
1536 $log->plugin
= $plugin;
1538 $id = $DB->insert_record('config_log', $log);
1540 $event = core\event\config_log_created
::create(array(
1542 'userid' => $log->userid
,
1543 'context' => \context_system
::instance(),
1545 'name' => $log->name
,
1546 'oldvalue' => $log->oldvalue
,
1547 'value' => $log->value
,
1548 'plugin' => $log->plugin
1555 * Store user last access times - called when use enters a course or site
1559 * @global stdClass $USER
1560 * @global stdClass $CFG
1561 * @global moodle_database $DB
1562 * @uses LASTACCESS_UPDATE_SECS
1564 * @param int $courseid empty courseid means site
1567 function user_accesstime_log($courseid=0) {
1568 global $USER, $CFG, $DB;
1570 if (!isloggedin() or \core\session\manager
::is_loggedinas()) {
1571 // no access tracking
1575 if (isguestuser()) {
1576 // Do not update guest access times/ips for performance.
1580 if (empty($courseid)) {
1586 /// Store site lastaccess time for the current user
1587 if ($timenow - $USER->lastaccess
> LASTACCESS_UPDATE_SECS
) {
1588 /// Update $USER->lastaccess for next checks
1589 $USER->lastaccess
= $timenow;
1591 $last = new stdClass();
1592 $last->id
= $USER->id
;
1593 $last->lastip
= getremoteaddr();
1594 $last->lastaccess
= $timenow;
1596 $DB->update_record_raw('user', $last);
1599 if ($courseid == SITEID
) {
1600 /// no user_lastaccess for frontpage
1604 /// Store course lastaccess times for the current user
1605 if (empty($USER->currentcourseaccess
[$courseid]) or ($timenow - $USER->currentcourseaccess
[$courseid] > LASTACCESS_UPDATE_SECS
)) {
1607 $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid'=>$USER->id
, 'courseid'=>$courseid));
1609 if ($lastaccess === false) {
1610 // Update course lastaccess for next checks
1611 $USER->currentcourseaccess
[$courseid] = $timenow;
1613 $last = new stdClass();
1614 $last->userid
= $USER->id
;
1615 $last->courseid
= $courseid;
1616 $last->timeaccess
= $timenow;
1618 $DB->insert_record_raw('user_lastaccess', $last, false);
1619 } catch (dml_write_exception
$e) {
1620 // During a race condition we can fail to find the data, then it appears.
1621 // If we still can't find it, rethrow the exception.
1622 $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid' => $USER->id
,
1623 'courseid' => $courseid));
1624 if ($lastaccess === false) {
1627 // If we did find it, the race condition was true and another thread has inserted the time for us.
1628 // We can just continue without having to do anything.
1631 } else if ($timenow - $lastaccess < LASTACCESS_UPDATE_SECS
) {
1632 // no need to update now, it was updated recently in concurrent login ;-)
1635 // Update course lastaccess for next checks
1636 $USER->currentcourseaccess
[$courseid] = $timenow;
1638 $DB->set_field('user_lastaccess', 'timeaccess', $timenow, array('userid'=>$USER->id
, 'courseid'=>$courseid));
1643 /// GENERAL HELPFUL THINGS ///////////////////////////////////
1646 * Dumps a given object's information for debugging purposes
1648 * When used in a CLI script, the object's information is written to the standard
1649 * error output stream. When used in a web script, the object is dumped to a
1650 * pre-formatted block with the "notifytiny" CSS class.
1652 * @param mixed $object The data to be printed
1653 * @return void output is echo'd
1655 function print_object($object) {
1657 // we may need a lot of memory here
1658 raise_memory_limit(MEMORY_EXTRA
);
1661 fwrite(STDERR
, print_r($object, true));
1662 fwrite(STDERR
, PHP_EOL
);
1663 } else if (AJAX_SCRIPT
) {
1664 foreach (explode("\n", print_r($object, true)) as $line) {
1668 echo html_writer
::tag('pre', s(print_r($object, true)), array('class' => 'notifytiny'));
1673 * This function is the official hook inside XMLDB stuff to delegate its debug to one
1674 * external function.
1676 * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
1677 * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
1679 * @uses DEBUG_DEVELOPER
1680 * @param string $message string contains the error message
1681 * @param object $object object XMLDB object that fired the debug
1683 function xmldb_debug($message, $object) {
1685 debugging($message, DEBUG_DEVELOPER
);
1690 * @uses CONTEXT_COURSECAT
1691 * @return boolean Whether the user can create courses in any category in the system.
1693 function user_can_create_courses() {
1695 $catsrs = $DB->get_recordset('course_categories');
1696 foreach ($catsrs as $cat) {
1697 if (has_capability('moodle/course:create', context_coursecat
::instance($cat->id
))) {
1707 * This method can update the values in mulitple database rows for a colum with
1708 * a unique index, without violating that constraint.
1710 * Suppose we have a table with a unique index on (otherid, sortorder), and
1711 * for a particular value of otherid, we want to change all the sort orders.
1712 * You have to do this carefully or you will violate the unique index at some time.
1713 * This method takes care of the details for you.
1715 * Note that, it is the responsibility of the caller to make sure that the
1716 * requested rename is legal. For example, if you ask for [1 => 2, 2 => 2]
1717 * then you will get a unique key violation error from the database.
1719 * @param string $table The database table to modify.
1720 * @param string $field the field that contains the values we are going to change.
1721 * @param array $newvalues oldvalue => newvalue how to change the values.
1722 * E.g. [1 => 4, 2 => 1, 3 => 3, 4 => 2].
1723 * @param array $otherconditions array fieldname => requestedvalue extra WHERE clause
1724 * conditions to restrict which rows are affected. E.g. array('otherid' => 123).
1725 * @param int $unusedvalue (defaults to -1) a value that is never used in $ordercol.
1727 function update_field_with_unique_index($table, $field, array $newvalues,
1728 array $otherconditions, $unusedvalue = -1) {
1730 $safechanges = decompose_update_into_safe_changes($newvalues, $unusedvalue);
1732 $transaction = $DB->start_delegated_transaction();
1733 foreach ($safechanges as $change) {
1734 list($from, $to) = $change;
1735 $otherconditions[$field] = $from;
1736 $DB->set_field($table, $field, $to, $otherconditions);
1738 $transaction->allow_commit();
1742 * Helper used by {@link update_field_with_unique_index()}. Given a desired
1743 * set of changes, break them down into single udpates that can be done one at
1744 * a time without breaking any unique index constraints.
1746 * Suppose the input is array(1 => 2, 2 => 1) and -1. Then the output will be
1747 * array (array(1, -1), array(2, 1), array(-1, 2)). This function solves this
1748 * problem in the general case, not just for simple swaps. The unit tests give
1751 * Note that, it is the responsibility of the caller to make sure that the
1752 * requested rename is legal. For example, if you ask for something impossible
1753 * like array(1 => 2, 2 => 2) then the results are undefined. (You will probably
1754 * get a unique key violation error from the database later.)
1756 * @param array $newvalues The desired re-ordering.
1757 * E.g. array(1 => 4, 2 => 1, 3 => 3, 4 => 2).
1758 * @param int $unusedvalue A value that is not currently used.
1759 * @return array A safe way to perform the re-order. An array of two-element
1760 * arrays array($from, $to).
1761 * E.g. array(array(1, -1), array(2, 1), array(4, 2), array(-1, 4)).
1763 function decompose_update_into_safe_changes(array $newvalues, $unusedvalue) {
1764 $nontrivialmap = array();
1765 foreach ($newvalues as $from => $to) {
1766 if ($from == $unusedvalue ||
$to == $unusedvalue) {
1767 throw new \
coding_exception('Supposedly unused value ' . $unusedvalue . ' is actually used!');
1770 $nontrivialmap[$from] = $to;
1774 if (empty($nontrivialmap)) {
1778 // First we deal with all renames that are not part of cycles.
1779 // This bit is O(n^2) and it ought to be possible to do better,
1780 // but it does not seem worth the effort.
1781 $safechanges = array();
1782 $nontrivialmapchanged = true;
1783 while ($nontrivialmapchanged) {
1784 $nontrivialmapchanged = false;
1786 foreach ($nontrivialmap as $from => $to) {
1787 if (array_key_exists($to, $nontrivialmap)) {
1788 continue; // Cannot currenly do this rename.
1790 // Is safe to do this rename now.
1791 $safechanges[] = array($from, $to);
1792 unset($nontrivialmap[$from]);
1793 $nontrivialmapchanged = true;
1798 if (empty($nontrivialmap)) {
1799 return $safechanges;
1802 // Now what is left in $nontrivialmap must be a permutation,
1803 // which must be a combination of disjoint cycles. We need to break them.
1804 while (!empty($nontrivialmap)) {
1805 // Extract the first cycle.
1806 reset($nontrivialmap);
1807 $current = $cyclestart = key($nontrivialmap);
1810 $cycle[] = $current;
1811 $next = $nontrivialmap[$current];
1812 unset($nontrivialmap[$current]);
1814 } while ($current != $cyclestart);
1816 // Now convert it to a sequence of safe renames by using a temp.
1817 $safechanges[] = array($cyclestart, $unusedvalue);
1818 $cycle[0] = $unusedvalue;
1820 while ($from = array_pop($cycle)) {
1821 $safechanges[] = array($from, $to);
1826 return $safechanges;
1830 * Return maximum number of courses in a category
1832 * @uses MAX_COURSES_IN_CATEGORY
1833 * @return int number of courses
1835 function get_max_courses_in_category() {
1837 // Use default MAX_COURSES_IN_CATEGORY if $CFG->maxcoursesincategory is not set or invalid.
1838 if (!isset($CFG->maxcoursesincategory
) ||
clean_param($CFG->maxcoursesincategory
, PARAM_INT
) == 0) {
1839 return MAX_COURSES_IN_CATEGORY
;
1841 return $CFG->maxcoursesincategory
;