MDL-69115 course: More course management accessibility fixes
[moodle.git] / lib / datalib.php
blob2ca8e54d80c1a6ffe5c1e4306c4bc1c9f66fffc4
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
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) {
231 global $DB, $CFG;
232 $params = array();
233 $tests = array();
235 if ($u) {
236 $u .= '.';
239 // If we have a $search string, put a field LIKE '$search%' condition on each field.
240 if ($search) {
241 $conditions = array(
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 . '%';
250 } else {
251 $searchparam = $search . '%';
253 $i = 0;
254 foreach ($conditions as $key => $condition) {
255 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false, false);
256 $params["con{$i}00"] = $searchparam;
257 $i++;
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).
284 if (empty($tests)) {
285 $tests[] = '1 = 1';
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:
305 * - firstname
306 * - lastname
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
320 * FROM {groups} g
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) {
344 global $DB, $PAGE;
346 if ($usertablealias) {
347 $tableprefix = $usertablealias . '.';
348 } else {
349 $tableprefix = '';
352 $sort = "{$tableprefix}lastname, {$tableprefix}firstname, {$tableprefix}id";
353 $params = array();
355 if (!$search) {
356 return array($sort, $params);
359 if (!$context) {
360 $context = $PAGE->context;
363 $exactconditions = array();
364 $paramkey = 'usersortexact1';
366 $exactconditions[] = $DB->sql_fullname($tableprefix . 'firstname', $tableprefix . 'lastname') .
367 ' = :' . $paramkey;
368 $params[$paramkey] = $search;
369 $paramkey++;
371 $fieldstocheck = array_merge(array('firstname', 'lastname'), get_extra_user_fields($context));
372 foreach ($fieldstocheck as $key => $field) {
373 $exactconditions[] = 'LOWER(' . $tableprefix . $field . ') = LOWER(:' . $paramkey . ')';
374 $params[$paramkey] = $search;
375 $paramkey++;
378 $sort = 'CASE WHEN ' . implode(' OR ', $exactconditions) .
379 ' THEN 0 ELSE 1 END, ' . $sort;
381 return array($sort, $params);
385 * Returns a subset of users
387 * @global object
388 * @uses DEBUG_DEVELOPER
389 * @uses SQL_PARAMS_NAMED
390 * @param bool $get If false then only a count of the records is returned
391 * @param string $search A simple string to search for
392 * @param bool $confirmed A switch to allow/disallow unconfirmed users
393 * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
394 * @param string $sort A SQL snippet for the sorting criteria to use
395 * @param string $firstinitial Users whose first name starts with $firstinitial
396 * @param string $lastinitial Users whose last name starts with $lastinitial
397 * @param string $page The page or records to return
398 * @param string $recordsperpage The number of records to return per page
399 * @param string $fields A comma separated list of fields to be returned from the chosen table.
400 * @return array|int|bool {@link $USER} records unless get is false in which case the integer count of the records found is returned.
401 * False is returned if an error is encountered.
403 function get_users($get=true, $search='', $confirmed=false, array $exceptions=null, $sort='firstname ASC',
404 $firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields='*', $extraselect='', array $extraparams=null) {
405 global $DB, $CFG;
407 if ($get && !$recordsperpage) {
408 debugging('Call to get_users with $get = true no $recordsperpage limit. ' .
409 'On large installations, this will probably cause an out of memory error. ' .
410 'Please think again and change your code so that it does not try to ' .
411 'load so much data into memory.', DEBUG_DEVELOPER);
414 $fullname = $DB->sql_fullname();
416 $select = " id <> :guestid AND deleted = 0";
417 $params = array('guestid'=>$CFG->siteguest);
419 if (!empty($search)){
420 $search = trim($search);
421 $select .= " AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('email', ':search2', false)." OR username = :search3)";
422 $params['search1'] = "%$search%";
423 $params['search2'] = "%$search%";
424 $params['search3'] = "$search";
427 if ($confirmed) {
428 $select .= " AND confirmed = 1";
431 if ($exceptions) {
432 list($exceptions, $eparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex', false);
433 $params = $params + $eparams;
434 $select .= " AND id $exceptions";
437 if ($firstinitial) {
438 $select .= " AND ".$DB->sql_like('firstname', ':fni', false, false);
439 $params['fni'] = "$firstinitial%";
441 if ($lastinitial) {
442 $select .= " AND ".$DB->sql_like('lastname', ':lni', false, false);
443 $params['lni'] = "$lastinitial%";
446 if ($extraselect) {
447 $select .= " AND $extraselect";
448 $params = $params + (array)$extraparams;
451 if ($get) {
452 return $DB->get_records_select('user', $select, $params, $sort, $fields, $page, $recordsperpage);
453 } else {
454 return $DB->count_records_select('user', $select, $params);
460 * Return filtered (if provided) list of users in site, except guest and deleted users.
462 * @param string $sort An SQL field to sort by
463 * @param string $dir The sort direction ASC|DESC
464 * @param int $page The page or records to return
465 * @param int $recordsperpage The number of records to return per page
466 * @param string $search A simple string to search for
467 * @param string $firstinitial Users whose first name starts with $firstinitial
468 * @param string $lastinitial Users whose last name starts with $lastinitial
469 * @param string $extraselect An additional SQL select statement to append to the query
470 * @param array $extraparams Additional parameters to use for the above $extraselect
471 * @param stdClass $extracontext If specified, will include user 'extra fields'
472 * as appropriate for current user and given context
473 * @return array Array of {@link $USER} records
475 function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0,
476 $search='', $firstinitial='', $lastinitial='', $extraselect='',
477 array $extraparams=null, $extracontext = null) {
478 global $DB, $CFG;
480 $fullname = $DB->sql_fullname();
482 $select = "deleted <> 1 AND id <> :guestid";
483 $params = array('guestid' => $CFG->siteguest);
485 if (!empty($search)) {
486 $search = trim($search);
487 $select .= " AND (". $DB->sql_like($fullname, ':search1', false, false).
488 " OR ". $DB->sql_like('email', ':search2', false, false).
489 " OR username = :search3)";
490 $params['search1'] = "%$search%";
491 $params['search2'] = "%$search%";
492 $params['search3'] = "$search";
495 if ($firstinitial) {
496 $select .= " AND ". $DB->sql_like('firstname', ':fni', false, false);
497 $params['fni'] = "$firstinitial%";
499 if ($lastinitial) {
500 $select .= " AND ". $DB->sql_like('lastname', ':lni', false, false);
501 $params['lni'] = "$lastinitial%";
504 if ($extraselect) {
505 $select .= " AND $extraselect";
506 $params = $params + (array)$extraparams;
509 if ($sort) {
510 $sort = " ORDER BY $sort $dir";
513 // If a context is specified, get extra user fields that the current user
514 // is supposed to see.
515 $extrafields = '';
516 if ($extracontext) {
517 $extrafields = get_extra_user_fields_sql($extracontext, '', '',
518 array('id', 'username', 'email', 'firstname', 'lastname', 'city', 'country',
519 'lastaccess', 'confirmed', 'mnethostid'));
521 $namefields = get_all_user_name_fields(true);
522 $extrafields = "$extrafields, $namefields";
524 // warning: will return UNCONFIRMED USERS
525 return $DB->get_records_sql("SELECT id, username, email, city, country, lastaccess, confirmed, mnethostid, suspended $extrafields
526 FROM {user}
527 WHERE $select
528 $sort", $params, $page, $recordsperpage);
534 * Full list of users that have confirmed their accounts.
536 * @global object
537 * @return array of unconfirmed users
539 function get_users_confirmed() {
540 global $DB, $CFG;
541 return $DB->get_records_sql("SELECT *
542 FROM {user}
543 WHERE confirmed = 1 AND deleted = 0 AND id <> ?", array($CFG->siteguest));
547 /// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
551 * Returns $course object of the top-level site.
553 * @return object A {@link $COURSE} object for the site, exception if not found
555 function get_site() {
556 global $SITE, $DB;
558 if (!empty($SITE->id)) { // We already have a global to use, so return that
559 return $SITE;
562 if ($course = $DB->get_record('course', array('category'=>0))) {
563 return $course;
564 } else {
565 // course table exists, but the site is not there,
566 // unfortunately there is no automatic way to recover
567 throw new moodle_exception('nosite', 'error');
572 * Gets a course object from database. If the course id corresponds to an
573 * already-loaded $COURSE or $SITE object, then the loaded object will be used,
574 * saving a database query.
576 * If it reuses an existing object, by default the object will be cloned. This
577 * means you can modify the object safely without affecting other code.
579 * @param int $courseid Course id
580 * @param bool $clone If true (default), makes a clone of the record
581 * @return stdClass A course object
582 * @throws dml_exception If not found in database
584 function get_course($courseid, $clone = true) {
585 global $DB, $COURSE, $SITE;
586 if (!empty($COURSE->id) && $COURSE->id == $courseid) {
587 return $clone ? clone($COURSE) : $COURSE;
588 } else if (!empty($SITE->id) && $SITE->id == $courseid) {
589 return $clone ? clone($SITE) : $SITE;
590 } else {
591 return $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
596 * Returns list of courses, for whole site, or category
598 * Returns list of courses, for whole site, or category
599 * Important: Using c.* for fields is extremely expensive because
600 * we are using distinct. You almost _NEVER_ need all the fields
601 * in such a large SELECT
603 * Consider using core_course_category::get_courses()
604 * or core_course_category::search_courses() instead since they use caching.
606 * @global object
607 * @global object
608 * @global object
609 * @uses CONTEXT_COURSE
610 * @param string|int $categoryid Either a category id or 'all' for everything
611 * @param string $sort A field and direction to sort by
612 * @param string $fields The additional fields to return
613 * @return array Array of courses
615 function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
617 global $USER, $CFG, $DB;
619 $params = array();
621 if ($categoryid !== "all" && is_numeric($categoryid)) {
622 $categoryselect = "WHERE c.category = :catid";
623 $params['catid'] = $categoryid;
624 } else {
625 $categoryselect = "";
628 if (empty($sort)) {
629 $sortstatement = "";
630 } else {
631 $sortstatement = "ORDER BY $sort";
634 $visiblecourses = array();
636 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
637 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
638 $params['contextlevel'] = CONTEXT_COURSE;
640 $sql = "SELECT $fields $ccselect
641 FROM {course} c
642 $ccjoin
643 $categoryselect
644 $sortstatement";
646 // pull out all course matching the cat
647 if ($courses = $DB->get_records_sql($sql, $params)) {
649 // loop throught them
650 foreach ($courses as $course) {
651 context_helper::preload_from_record($course);
652 if (core_course_category::can_view_course_info($course)) {
653 $visiblecourses [$course->id] = $course;
657 return $visiblecourses;
661 * A list of courses that match a search
663 * @global object
664 * @global object
665 * @param array $searchterms An array of search criteria
666 * @param string $sort A field and direction to sort by
667 * @param int $page The page number to get
668 * @param int $recordsperpage The number of records per page
669 * @param int $totalcount Passed in by reference.
670 * @param array $requiredcapabilities Extra list of capabilities used to filter courses
671 * @param array $searchcond additional search conditions, for example ['c.enablecompletion = :p1']
672 * @param array $params named parameters for additional search conditions, for example ['p1' => 1]
673 * @return stdClass[] {@link $COURSE} records
675 function get_courses_search($searchterms, $sort, $page, $recordsperpage, &$totalcount,
676 $requiredcapabilities = array(), $searchcond = [], $params = []) {
677 global $CFG, $DB;
679 if ($DB->sql_regex_supported()) {
680 $REGEXP = $DB->sql_regex(true);
681 $NOTREGEXP = $DB->sql_regex(false);
684 $i = 0;
686 // Thanks Oracle for your non-ansi concat and type limits in coalesce. MDL-29912
687 if ($DB->get_dbfamily() == 'oracle') {
688 $concat = "(c.summary|| ' ' || c.fullname || ' ' || c.idnumber || ' ' || c.shortname)";
689 } else {
690 $concat = $DB->sql_concat("COALESCE(c.summary, '')", "' '", 'c.fullname', "' '", 'c.idnumber', "' '", 'c.shortname');
693 foreach ($searchterms as $searchterm) {
694 $i++;
696 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
697 /// will use it to simulate the "-" operator with LIKE clause
699 /// Under Oracle and MSSQL, trim the + and - operators and perform
700 /// simpler LIKE (or NOT LIKE) queries
701 if (!$DB->sql_regex_supported()) {
702 if (substr($searchterm, 0, 1) == '-') {
703 $NOT = true;
705 $searchterm = trim($searchterm, '+-');
708 // TODO: +- may not work for non latin languages
710 if (substr($searchterm,0,1) == '+') {
711 $searchterm = trim($searchterm, '+-');
712 $searchterm = preg_quote($searchterm, '|');
713 $searchcond[] = "$concat $REGEXP :ss$i";
714 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
716 } else if ((substr($searchterm,0,1) == "-") && (core_text::strlen($searchterm) > 1)) {
717 $searchterm = trim($searchterm, '+-');
718 $searchterm = preg_quote($searchterm, '|');
719 $searchcond[] = "$concat $NOTREGEXP :ss$i";
720 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
722 } else {
723 $searchcond[] = $DB->sql_like($concat,":ss$i", false, true, $NOT);
724 $params['ss'.$i] = "%$searchterm%";
728 if (empty($searchcond)) {
729 $searchcond = array('1 = 1');
732 $searchcond = implode(" AND ", $searchcond);
734 $courses = array();
735 $c = 0; // counts how many visible courses we've seen
737 // Tiki pagination
738 $limitfrom = $page * $recordsperpage;
739 $limitto = $limitfrom + $recordsperpage;
741 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
742 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
743 $params['contextlevel'] = CONTEXT_COURSE;
745 $sql = "SELECT c.* $ccselect
746 FROM {course} c
747 $ccjoin
748 WHERE $searchcond AND c.id <> ".SITEID."
749 ORDER BY $sort";
751 $mycourses = enrol_get_my_courses();
752 $rs = $DB->get_recordset_sql($sql, $params);
753 foreach($rs as $course) {
754 // Preload contexts only for hidden courses or courses we need to return.
755 context_helper::preload_from_record($course);
756 $coursecontext = context_course::instance($course->id);
757 if (!array_key_exists($course->id, $mycourses) && !core_course_category::can_view_course_info($course)) {
758 continue;
760 if (!empty($requiredcapabilities)) {
761 if (!has_all_capabilities($requiredcapabilities, $coursecontext)) {
762 continue;
765 // Don't exit this loop till the end
766 // we need to count all the visible courses
767 // to update $totalcount
768 if ($c >= $limitfrom && $c < $limitto) {
769 $courses[$course->id] = $course;
771 $c++;
773 $rs->close();
775 // our caller expects 2 bits of data - our return
776 // array, and an updated $totalcount
777 $totalcount = $c;
778 return $courses;
782 * Fixes course category and course sortorder, also verifies category and course parents and paths.
783 * (circular references are not fixed)
785 * @global object
786 * @global object
787 * @uses MAX_COURSES_IN_CATEGORY
788 * @uses MAX_COURSE_CATEGORIES
789 * @uses SITEID
790 * @uses CONTEXT_COURSE
791 * @return void
793 function fix_course_sortorder() {
794 global $DB, $SITE;
796 //WARNING: this is PHP5 only code!
798 // if there are any changes made to courses or categories we will trigger
799 // the cache events to purge all cached courses/categories data
800 $cacheevents = array();
802 if ($unsorted = $DB->get_records('course_categories', array('sortorder'=>0))) {
803 //move all categories that are not sorted yet to the end
804 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('sortorder'=>0));
805 $cacheevents['changesincoursecat'] = true;
808 $allcats = $DB->get_records('course_categories', null, 'sortorder, id', 'id, sortorder, parent, depth, path');
809 $topcats = array();
810 $brokencats = array();
811 foreach ($allcats as $cat) {
812 $sortorder = (int)$cat->sortorder;
813 if (!$cat->parent) {
814 while(isset($topcats[$sortorder])) {
815 $sortorder++;
817 $topcats[$sortorder] = $cat;
818 continue;
820 if (!isset($allcats[$cat->parent])) {
821 $brokencats[] = $cat;
822 continue;
824 if (!isset($allcats[$cat->parent]->children)) {
825 $allcats[$cat->parent]->children = array();
827 while(isset($allcats[$cat->parent]->children[$sortorder])) {
828 $sortorder++;
830 $allcats[$cat->parent]->children[$sortorder] = $cat;
832 unset($allcats);
834 // add broken cats to category tree
835 if ($brokencats) {
836 $defaultcat = reset($topcats);
837 foreach ($brokencats as $cat) {
838 $topcats[] = $cat;
842 // now walk recursively the tree and fix any problems found
843 $sortorder = 0;
844 $fixcontexts = array();
845 if (_fix_course_cats($topcats, $sortorder, 0, 0, '', $fixcontexts)) {
846 $cacheevents['changesincoursecat'] = true;
849 // detect if there are "multiple" frontpage courses and fix them if needed
850 $frontcourses = $DB->get_records('course', array('category'=>0), 'id');
851 if (count($frontcourses) > 1) {
852 if (isset($frontcourses[SITEID])) {
853 $frontcourse = $frontcourses[SITEID];
854 unset($frontcourses[SITEID]);
855 } else {
856 $frontcourse = array_shift($frontcourses);
858 $defaultcat = reset($topcats);
859 foreach ($frontcourses as $course) {
860 $DB->set_field('course', 'category', $defaultcat->id, array('id'=>$course->id));
861 $context = context_course::instance($course->id);
862 $fixcontexts[$context->id] = $context;
863 $cacheevents['changesincourse'] = true;
865 unset($frontcourses);
866 } else {
867 $frontcourse = reset($frontcourses);
870 // now fix the paths and depths in context table if needed
871 if ($fixcontexts) {
872 foreach ($fixcontexts as $fixcontext) {
873 $fixcontext->reset_paths(false);
875 context_helper::build_all_paths(false);
876 unset($fixcontexts);
877 $cacheevents['changesincourse'] = true;
878 $cacheevents['changesincoursecat'] = true;
881 // release memory
882 unset($topcats);
883 unset($brokencats);
884 unset($fixcontexts);
886 // fix frontpage course sortorder
887 if ($frontcourse->sortorder != 1) {
888 $DB->set_field('course', 'sortorder', 1, array('id'=>$frontcourse->id));
889 $cacheevents['changesincourse'] = true;
892 // now fix the course counts in category records if needed
893 $sql = "SELECT cc.id, cc.coursecount, COUNT(c.id) AS newcount
894 FROM {course_categories} cc
895 LEFT JOIN {course} c ON c.category = cc.id
896 GROUP BY cc.id, cc.coursecount
897 HAVING cc.coursecount <> COUNT(c.id)";
899 if ($updatecounts = $DB->get_records_sql($sql)) {
900 // categories with more courses than MAX_COURSES_IN_CATEGORY
901 $categories = array();
902 foreach ($updatecounts as $cat) {
903 $cat->coursecount = $cat->newcount;
904 if ($cat->coursecount >= MAX_COURSES_IN_CATEGORY) {
905 $categories[] = $cat->id;
907 unset($cat->newcount);
908 $DB->update_record_raw('course_categories', $cat, true);
910 if (!empty($categories)) {
911 $str = implode(', ', $categories);
912 debugging("The number of courses (category id: $str) has reached MAX_COURSES_IN_CATEGORY (" . MAX_COURSES_IN_CATEGORY . "), it will cause a sorting performance issue, please increase the value of MAX_COURSES_IN_CATEGORY in lib/datalib.php file. See tracker issue: MDL-25669", DEBUG_DEVELOPER);
914 $cacheevents['changesincoursecat'] = true;
917 // now make sure that sortorders in course table are withing the category sortorder ranges
918 $sql = "SELECT DISTINCT cc.id, cc.sortorder
919 FROM {course_categories} cc
920 JOIN {course} c ON c.category = cc.id
921 WHERE c.sortorder < cc.sortorder OR c.sortorder > cc.sortorder + ".MAX_COURSES_IN_CATEGORY;
923 if ($fixcategories = $DB->get_records_sql($sql)) {
924 //fix the course sortorder ranges
925 foreach ($fixcategories as $cat) {
926 $sql = "UPDATE {course}
927 SET sortorder = ".$DB->sql_modulo('sortorder', MAX_COURSES_IN_CATEGORY)." + ?
928 WHERE category = ?";
929 $DB->execute($sql, array($cat->sortorder, $cat->id));
931 $cacheevents['changesincoursecat'] = true;
933 unset($fixcategories);
935 // categories having courses with sortorder duplicates or having gaps in sortorder
936 $sql = "SELECT DISTINCT c1.category AS id , cc.sortorder
937 FROM {course} c1
938 JOIN {course} c2 ON c1.sortorder = c2.sortorder
939 JOIN {course_categories} cc ON (c1.category = cc.id)
940 WHERE c1.id <> c2.id";
941 $fixcategories = $DB->get_records_sql($sql);
943 $sql = "SELECT cc.id, cc.sortorder, cc.coursecount, MAX(c.sortorder) AS maxsort, MIN(c.sortorder) AS minsort
944 FROM {course_categories} cc
945 JOIN {course} c ON c.category = cc.id
946 GROUP BY cc.id, cc.sortorder, cc.coursecount
947 HAVING (MAX(c.sortorder) <> cc.sortorder + cc.coursecount) OR (MIN(c.sortorder) <> cc.sortorder + 1)";
948 $gapcategories = $DB->get_records_sql($sql);
950 foreach ($gapcategories as $cat) {
951 if (isset($fixcategories[$cat->id])) {
952 // duplicates detected already
954 } else if ($cat->minsort == $cat->sortorder and $cat->maxsort == $cat->sortorder + $cat->coursecount - 1) {
955 // easy - new course inserted with sortorder 0, the rest is ok
956 $sql = "UPDATE {course}
957 SET sortorder = sortorder + 1
958 WHERE category = ?";
959 $DB->execute($sql, array($cat->id));
961 } else {
962 // it needs full resorting
963 $fixcategories[$cat->id] = $cat;
965 $cacheevents['changesincourse'] = true;
967 unset($gapcategories);
969 // fix course sortorders in problematic categories only
970 foreach ($fixcategories as $cat) {
971 $i = 1;
972 $courses = $DB->get_records('course', array('category'=>$cat->id), 'sortorder ASC, id DESC', 'id, sortorder');
973 foreach ($courses as $course) {
974 if ($course->sortorder != $cat->sortorder + $i) {
975 $course->sortorder = $cat->sortorder + $i;
976 $DB->update_record_raw('course', $course, true);
977 $cacheevents['changesincourse'] = true;
979 $i++;
983 // advise all caches that need to be rebuilt
984 foreach (array_keys($cacheevents) as $event) {
985 cache_helper::purge_by_event($event);
990 * Internal recursive category verification function, do not use directly!
992 * @todo Document the arguments of this function better
994 * @global object
995 * @uses MAX_COURSES_IN_CATEGORY
996 * @uses CONTEXT_COURSECAT
997 * @param array $children
998 * @param int $sortorder
999 * @param string $parent
1000 * @param int $depth
1001 * @param string $path
1002 * @param array $fixcontexts
1003 * @return bool if changes were made
1005 function _fix_course_cats($children, &$sortorder, $parent, $depth, $path, &$fixcontexts) {
1006 global $DB;
1008 $depth++;
1009 $changesmade = false;
1011 foreach ($children as $cat) {
1012 $sortorder = $sortorder + MAX_COURSES_IN_CATEGORY;
1013 $update = false;
1014 if ($parent != $cat->parent or $depth != $cat->depth or $path.'/'.$cat->id != $cat->path) {
1015 $cat->parent = $parent;
1016 $cat->depth = $depth;
1017 $cat->path = $path.'/'.$cat->id;
1018 $update = true;
1020 // make sure context caches are rebuild and dirty contexts marked
1021 $context = context_coursecat::instance($cat->id);
1022 $fixcontexts[$context->id] = $context;
1024 if ($cat->sortorder != $sortorder) {
1025 $cat->sortorder = $sortorder;
1026 $update = true;
1028 if ($update) {
1029 $DB->update_record('course_categories', $cat, true);
1030 $changesmade = true;
1032 if (isset($cat->children)) {
1033 if (_fix_course_cats($cat->children, $sortorder, $cat->id, $cat->depth, $cat->path, $fixcontexts)) {
1034 $changesmade = true;
1038 return $changesmade;
1042 * List of remote courses that a user has access to via MNET.
1043 * Works only on the IDP
1045 * @global object
1046 * @global object
1047 * @param int @userid The user id to get remote courses for
1048 * @return array Array of {@link $COURSE} of course objects
1050 function get_my_remotecourses($userid=0) {
1051 global $DB, $USER;
1053 if (empty($userid)) {
1054 $userid = $USER->id;
1057 // we can not use SELECT DISTINCT + text field (summary) because of MS SQL and Oracle, subselect used therefore
1058 $sql = "SELECT c.id, c.remoteid, c.shortname, c.fullname,
1059 c.hostid, c.summary, c.summaryformat, c.categoryname AS cat_name,
1060 h.name AS hostname
1061 FROM {mnetservice_enrol_courses} c
1062 JOIN (SELECT DISTINCT hostid, remotecourseid
1063 FROM {mnetservice_enrol_enrolments}
1064 WHERE userid = ?
1065 ) e ON (e.hostid = c.hostid AND e.remotecourseid = c.remoteid)
1066 JOIN {mnet_host} h ON h.id = c.hostid";
1068 return $DB->get_records_sql($sql, array($userid));
1072 * List of remote hosts that a user has access to via MNET.
1073 * Works on the SP
1075 * @global object
1076 * @global object
1077 * @return array|bool Array of host objects or false
1079 function get_my_remotehosts() {
1080 global $CFG, $USER;
1082 if ($USER->mnethostid == $CFG->mnet_localhost_id) {
1083 return false; // Return nothing on the IDP
1085 if (!empty($USER->mnet_foreign_host_array) && is_array($USER->mnet_foreign_host_array)) {
1086 return $USER->mnet_foreign_host_array;
1088 return false;
1093 * Returns a menu of all available scales from the site as well as the given course
1095 * @global object
1096 * @param int $courseid The id of the course as found in the 'course' table.
1097 * @return array
1099 function get_scales_menu($courseid=0) {
1100 global $DB;
1102 $sql = "SELECT id, name, courseid
1103 FROM {scale}
1104 WHERE courseid = 0 or courseid = ?
1105 ORDER BY courseid ASC, name ASC";
1106 $params = array($courseid);
1107 $scales = array();
1108 $results = $DB->get_records_sql($sql, $params);
1109 foreach ($results as $index => $record) {
1110 $context = empty($record->courseid) ? context_system::instance() : context_course::instance($record->courseid);
1111 $scales[$index] = format_string($record->name, false, ["context" => $context]);
1113 // Format: [id => 'scale name'].
1114 return $scales;
1118 * Increment standard revision field.
1120 * The revision are based on current time and are incrementing.
1121 * There is a protection for runaway revisions, it may not go further than
1122 * one hour into future.
1124 * The field has to be XMLDB_TYPE_INTEGER with size 10.
1126 * @param string $table
1127 * @param string $field name of the field containing revision
1128 * @param string $select use empty string when updating all records
1129 * @param array $params optional select parameters
1131 function increment_revision_number($table, $field, $select, array $params = null) {
1132 global $DB;
1134 $now = time();
1135 $sql = "UPDATE {{$table}}
1136 SET $field = (CASE
1137 WHEN $field IS NULL THEN $now
1138 WHEN $field < $now THEN $now
1139 WHEN $field > $now + 3600 THEN $now
1140 ELSE $field + 1 END)";
1141 if ($select) {
1142 $sql = $sql . " WHERE $select";
1144 $DB->execute($sql, $params);
1148 /// MODULE FUNCTIONS /////////////////////////////////////////////////
1151 * Just gets a raw list of all modules in a course
1153 * @global object
1154 * @param int $courseid The id of the course as found in the 'course' table.
1155 * @return array
1157 function get_course_mods($courseid) {
1158 global $DB;
1160 if (empty($courseid)) {
1161 return false; // avoid warnings
1164 return $DB->get_records_sql("SELECT cm.*, m.name as modname
1165 FROM {modules} m, {course_modules} cm
1166 WHERE cm.course = ? AND cm.module = m.id AND m.visible = 1",
1167 array($courseid)); // no disabled mods
1172 * Given an id of a course module, finds the coursemodule description
1174 * Please note that this function performs 1-2 DB queries. When possible use cached
1175 * course modinfo. For example get_fast_modinfo($courseorid)->get_cm($cmid)
1176 * See also {@link cm_info::get_course_module_record()}
1178 * @global object
1179 * @param string $modulename name of module type, eg. resource, assignment,... (optional, slower and less safe if not specified)
1180 * @param int $cmid course module id (id in course_modules table)
1181 * @param int $courseid optional course id for extra validation
1182 * @param bool $sectionnum include relative section number (0,1,2 ...)
1183 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1184 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1185 * MUST_EXIST means throw exception if no record or multiple records found
1186 * @return stdClass
1188 function get_coursemodule_from_id($modulename, $cmid, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1189 global $DB;
1191 $params = array('cmid'=>$cmid);
1193 if (!$modulename) {
1194 if (!$modulename = $DB->get_field_sql("SELECT md.name
1195 FROM {modules} md
1196 JOIN {course_modules} cm ON cm.module = md.id
1197 WHERE cm.id = :cmid", $params, $strictness)) {
1198 return false;
1200 } else {
1201 if (!core_component::is_valid_plugin_name('mod', $modulename)) {
1202 throw new coding_exception('Invalid modulename parameter');
1206 $params['modulename'] = $modulename;
1208 $courseselect = "";
1209 $sectionfield = "";
1210 $sectionjoin = "";
1212 if ($courseid) {
1213 $courseselect = "AND cm.course = :courseid";
1214 $params['courseid'] = $courseid;
1217 if ($sectionnum) {
1218 $sectionfield = ", cw.section AS sectionnum";
1219 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1222 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1223 FROM {course_modules} cm
1224 JOIN {modules} md ON md.id = cm.module
1225 JOIN {".$modulename."} m ON m.id = cm.instance
1226 $sectionjoin
1227 WHERE cm.id = :cmid AND md.name = :modulename
1228 $courseselect";
1230 return $DB->get_record_sql($sql, $params, $strictness);
1234 * Given an instance number of a module, finds the coursemodule description
1236 * Please note that this function performs DB query. When possible use cached course
1237 * modinfo. For example get_fast_modinfo($courseorid)->instances[$modulename][$instance]
1238 * See also {@link cm_info::get_course_module_record()}
1240 * @global object
1241 * @param string $modulename name of module type, eg. resource, assignment,...
1242 * @param int $instance module instance number (id in resource, assignment etc. table)
1243 * @param int $courseid optional course id for extra validation
1244 * @param bool $sectionnum include relative section number (0,1,2 ...)
1245 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1246 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1247 * MUST_EXIST means throw exception if no record or multiple records found
1248 * @return stdClass
1250 function get_coursemodule_from_instance($modulename, $instance, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1251 global $DB;
1253 if (!core_component::is_valid_plugin_name('mod', $modulename)) {
1254 throw new coding_exception('Invalid modulename parameter');
1257 $params = array('instance'=>$instance, 'modulename'=>$modulename);
1259 $courseselect = "";
1260 $sectionfield = "";
1261 $sectionjoin = "";
1263 if ($courseid) {
1264 $courseselect = "AND cm.course = :courseid";
1265 $params['courseid'] = $courseid;
1268 if ($sectionnum) {
1269 $sectionfield = ", cw.section AS sectionnum";
1270 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1273 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1274 FROM {course_modules} cm
1275 JOIN {modules} md ON md.id = cm.module
1276 JOIN {".$modulename."} m ON m.id = cm.instance
1277 $sectionjoin
1278 WHERE m.id = :instance AND md.name = :modulename
1279 $courseselect";
1281 return $DB->get_record_sql($sql, $params, $strictness);
1285 * Returns all course modules of given activity in course
1287 * @param string $modulename The module name (forum, quiz, etc.)
1288 * @param int $courseid The course id to get modules for
1289 * @param string $extrafields extra fields starting with m.
1290 * @return array Array of results
1292 function get_coursemodules_in_course($modulename, $courseid, $extrafields='') {
1293 global $DB;
1295 if (!core_component::is_valid_plugin_name('mod', $modulename)) {
1296 throw new coding_exception('Invalid modulename parameter');
1299 if (!empty($extrafields)) {
1300 $extrafields = ", $extrafields";
1302 $params = array();
1303 $params['courseid'] = $courseid;
1304 $params['modulename'] = $modulename;
1307 return $DB->get_records_sql("SELECT cm.*, m.name, md.name as modname $extrafields
1308 FROM {course_modules} cm, {modules} md, {".$modulename."} m
1309 WHERE cm.course = :courseid AND
1310 cm.instance = m.id AND
1311 md.name = :modulename AND
1312 md.id = cm.module", $params);
1316 * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1318 * Returns an array of all the active instances of a particular
1319 * module in given courses, sorted in the order they are defined
1320 * in the course. Returns an empty array on any errors.
1322 * The returned objects includle the columns cw.section, cm.visible,
1323 * cm.groupmode, and cm.groupingid, and are indexed by cm.id.
1325 * @global object
1326 * @global object
1327 * @param string $modulename The name of the module to get instances for
1328 * @param array $courses an array of course objects.
1329 * @param int $userid
1330 * @param int $includeinvisible
1331 * @return array of module instance objects, including some extra fields from the course_modules
1332 * and course_sections tables, or an empty array if an error occurred.
1334 function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
1335 global $CFG, $DB;
1337 if (!core_component::is_valid_plugin_name('mod', $modulename)) {
1338 throw new coding_exception('Invalid modulename parameter');
1341 $outputarray = array();
1343 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1344 return $outputarray;
1347 list($coursessql, $params) = $DB->get_in_or_equal(array_keys($courses), SQL_PARAMS_NAMED, 'c0');
1348 $params['modulename'] = $modulename;
1350 if (!$rawmods = $DB->get_records_sql("SELECT cm.id AS coursemodule, m.*, cw.section, cm.visible AS visible,
1351 cm.groupmode, cm.groupingid
1352 FROM {course_modules} cm, {course_sections} cw, {modules} md,
1353 {".$modulename."} m
1354 WHERE cm.course $coursessql AND
1355 cm.instance = m.id AND
1356 cm.section = cw.id AND
1357 md.name = :modulename AND
1358 md.id = cm.module", $params)) {
1359 return $outputarray;
1362 foreach ($courses as $course) {
1363 $modinfo = get_fast_modinfo($course, $userid);
1365 if (empty($modinfo->instances[$modulename])) {
1366 continue;
1369 foreach ($modinfo->instances[$modulename] as $cm) {
1370 if (!$includeinvisible and !$cm->uservisible) {
1371 continue;
1373 if (!isset($rawmods[$cm->id])) {
1374 continue;
1376 $instance = $rawmods[$cm->id];
1377 if (!empty($cm->extra)) {
1378 $instance->extra = $cm->extra;
1380 $outputarray[] = $instance;
1384 return $outputarray;
1388 * Returns an array of all the active instances of a particular module in a given course,
1389 * sorted in the order they are defined.
1391 * Returns an array of all the active instances of a particular
1392 * module in a given course, sorted in the order they are defined
1393 * in the course. Returns an empty array on any errors.
1395 * The returned objects includle the columns cw.section, cm.visible,
1396 * cm.groupmode, and cm.groupingid, and are indexed by cm.id.
1398 * Simply calls {@link all_instances_in_courses()} with a single provided course
1400 * @param string $modulename The name of the module to get instances for
1401 * @param object $course The course obect.
1402 * @return array of module instance objects, including some extra fields from the course_modules
1403 * and course_sections tables, or an empty array if an error occurred.
1404 * @param int $userid
1405 * @param int $includeinvisible
1407 function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
1408 return get_all_instances_in_courses($modulename, array($course->id => $course), $userid, $includeinvisible);
1413 * Determine whether a module instance is visible within a course
1415 * Given a valid module object with info about the id and course,
1416 * and the module's type (eg "forum") returns whether the object
1417 * is visible or not according to the 'eye' icon only.
1419 * NOTE: This does NOT take into account visibility to a particular user.
1420 * To get visibility access for a specific user, use get_fast_modinfo, get a
1421 * cm_info object from this, and check the ->uservisible property; or use
1422 * the \core_availability\info_module::is_user_visible() static function.
1424 * @global object
1426 * @param $moduletype Name of the module eg 'forum'
1427 * @param $module Object which is the instance of the module
1428 * @return bool Success
1430 function instance_is_visible($moduletype, $module) {
1431 global $DB;
1433 if (!empty($module->id)) {
1434 $params = array('courseid'=>$module->course, 'moduletype'=>$moduletype, 'moduleid'=>$module->id);
1435 if ($records = $DB->get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.course
1436 FROM {course_modules} cm, {modules} m
1437 WHERE cm.course = :courseid AND
1438 cm.module = m.id AND
1439 m.name = :moduletype AND
1440 cm.instance = :moduleid", $params)) {
1442 foreach ($records as $record) { // there should only be one - use the first one
1443 return $record->visible;
1447 return true; // visible by default!
1451 /// LOG FUNCTIONS /////////////////////////////////////////////////////
1454 * Get instance of log manager.
1456 * @param bool $forcereload
1457 * @return \core\log\manager
1459 function get_log_manager($forcereload = false) {
1460 /** @var \core\log\manager $singleton */
1461 static $singleton = null;
1463 if ($forcereload and isset($singleton)) {
1464 $singleton->dispose();
1465 $singleton = null;
1468 if (isset($singleton)) {
1469 return $singleton;
1472 $classname = '\tool_log\log\manager';
1473 if (defined('LOG_MANAGER_CLASS')) {
1474 $classname = LOG_MANAGER_CLASS;
1477 if (!class_exists($classname)) {
1478 if (!empty($classname)) {
1479 debugging("Cannot find log manager class '$classname'.", DEBUG_DEVELOPER);
1481 $classname = '\core\log\dummy_manager';
1484 $singleton = new $classname();
1485 return $singleton;
1489 * Add an entry to the config log table.
1491 * These are "action" focussed rather than web server hits,
1492 * and provide a way to easily reconstruct changes to Moodle configuration.
1494 * @package core
1495 * @category log
1496 * @global moodle_database $DB
1497 * @global stdClass $USER
1498 * @param string $name The name of the configuration change action
1499 For example 'filter_active' when activating or deactivating a filter
1500 * @param string $oldvalue The config setting's previous value
1501 * @param string $value The config setting's new value
1502 * @param string $plugin Plugin name, for example a filter name when changing filter configuration
1503 * @return void
1505 function add_to_config_log($name, $oldvalue, $value, $plugin) {
1506 global $USER, $DB;
1508 $log = new stdClass();
1509 // Use 0 as user id during install.
1510 $log->userid = during_initial_install() ? 0 : $USER->id;
1511 $log->timemodified = time();
1512 $log->name = $name;
1513 $log->oldvalue = $oldvalue;
1514 $log->value = $value;
1515 $log->plugin = $plugin;
1517 $id = $DB->insert_record('config_log', $log);
1519 $event = core\event\config_log_created::create(array(
1520 'objectid' => $id,
1521 'userid' => $log->userid,
1522 'context' => \context_system::instance(),
1523 'other' => array(
1524 'name' => $log->name,
1525 'oldvalue' => $log->oldvalue,
1526 'value' => $log->value,
1527 'plugin' => $log->plugin
1530 $event->trigger();
1534 * Store user last access times - called when use enters a course or site
1536 * @package core
1537 * @category log
1538 * @global stdClass $USER
1539 * @global stdClass $CFG
1540 * @global moodle_database $DB
1541 * @uses LASTACCESS_UPDATE_SECS
1542 * @uses SITEID
1543 * @param int $courseid empty courseid means site
1544 * @return void
1546 function user_accesstime_log($courseid=0) {
1547 global $USER, $CFG, $DB;
1549 if (!isloggedin() or \core\session\manager::is_loggedinas()) {
1550 // no access tracking
1551 return;
1554 if (isguestuser()) {
1555 // Do not update guest access times/ips for performance.
1556 return;
1559 if (empty($courseid)) {
1560 $courseid = SITEID;
1563 $timenow = time();
1565 /// Store site lastaccess time for the current user
1566 if ($timenow - $USER->lastaccess > LASTACCESS_UPDATE_SECS) {
1567 /// Update $USER->lastaccess for next checks
1568 $USER->lastaccess = $timenow;
1570 $last = new stdClass();
1571 $last->id = $USER->id;
1572 $last->lastip = getremoteaddr();
1573 $last->lastaccess = $timenow;
1575 $DB->update_record_raw('user', $last);
1578 if ($courseid == SITEID) {
1579 /// no user_lastaccess for frontpage
1580 return;
1583 /// Store course lastaccess times for the current user
1584 if (empty($USER->currentcourseaccess[$courseid]) or ($timenow - $USER->currentcourseaccess[$courseid] > LASTACCESS_UPDATE_SECS)) {
1586 $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid'=>$USER->id, 'courseid'=>$courseid));
1588 if ($lastaccess === false) {
1589 // Update course lastaccess for next checks
1590 $USER->currentcourseaccess[$courseid] = $timenow;
1592 $last = new stdClass();
1593 $last->userid = $USER->id;
1594 $last->courseid = $courseid;
1595 $last->timeaccess = $timenow;
1596 try {
1597 $DB->insert_record_raw('user_lastaccess', $last, false);
1598 } catch (dml_write_exception $e) {
1599 // During a race condition we can fail to find the data, then it appears.
1600 // If we still can't find it, rethrow the exception.
1601 $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid' => $USER->id,
1602 'courseid' => $courseid));
1603 if ($lastaccess === false) {
1604 throw $e;
1606 // If we did find it, the race condition was true and another thread has inserted the time for us.
1607 // We can just continue without having to do anything.
1610 } else if ($timenow - $lastaccess < LASTACCESS_UPDATE_SECS) {
1611 // no need to update now, it was updated recently in concurrent login ;-)
1613 } else {
1614 // Update course lastaccess for next checks
1615 $USER->currentcourseaccess[$courseid] = $timenow;
1617 $DB->set_field('user_lastaccess', 'timeaccess', $timenow, array('userid'=>$USER->id, 'courseid'=>$courseid));
1622 /// GENERAL HELPFUL THINGS ///////////////////////////////////
1625 * Dumps a given object's information for debugging purposes
1627 * When used in a CLI script, the object's information is written to the standard
1628 * error output stream. When used in a web script, the object is dumped to a
1629 * pre-formatted block with the "notifytiny" CSS class.
1631 * @param mixed $object The data to be printed
1632 * @return void output is echo'd
1634 function print_object($object) {
1636 // we may need a lot of memory here
1637 raise_memory_limit(MEMORY_EXTRA);
1639 if (CLI_SCRIPT) {
1640 fwrite(STDERR, print_r($object, true));
1641 fwrite(STDERR, PHP_EOL);
1642 } else if (AJAX_SCRIPT) {
1643 foreach (explode("\n", print_r($object, true)) as $line) {
1644 error_log($line);
1646 } else {
1647 echo html_writer::tag('pre', s(print_r($object, true)), array('class' => 'notifytiny'));
1652 * This function is the official hook inside XMLDB stuff to delegate its debug to one
1653 * external function.
1655 * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
1656 * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
1658 * @uses DEBUG_DEVELOPER
1659 * @param string $message string contains the error message
1660 * @param object $object object XMLDB object that fired the debug
1662 function xmldb_debug($message, $object) {
1664 debugging($message, DEBUG_DEVELOPER);
1668 * @global object
1669 * @uses CONTEXT_COURSECAT
1670 * @return boolean Whether the user can create courses in any category in the system.
1672 function user_can_create_courses() {
1673 global $DB;
1674 $catsrs = $DB->get_recordset('course_categories');
1675 foreach ($catsrs as $cat) {
1676 if (has_capability('moodle/course:create', context_coursecat::instance($cat->id))) {
1677 $catsrs->close();
1678 return true;
1681 $catsrs->close();
1682 return false;
1686 * This method can update the values in mulitple database rows for a colum with
1687 * a unique index, without violating that constraint.
1689 * Suppose we have a table with a unique index on (otherid, sortorder), and
1690 * for a particular value of otherid, we want to change all the sort orders.
1691 * You have to do this carefully or you will violate the unique index at some time.
1692 * This method takes care of the details for you.
1694 * Note that, it is the responsibility of the caller to make sure that the
1695 * requested rename is legal. For example, if you ask for [1 => 2, 2 => 2]
1696 * then you will get a unique key violation error from the database.
1698 * @param string $table The database table to modify.
1699 * @param string $field the field that contains the values we are going to change.
1700 * @param array $newvalues oldvalue => newvalue how to change the values.
1701 * E.g. [1 => 4, 2 => 1, 3 => 3, 4 => 2].
1702 * @param array $otherconditions array fieldname => requestedvalue extra WHERE clause
1703 * conditions to restrict which rows are affected. E.g. array('otherid' => 123).
1704 * @param int $unusedvalue (defaults to -1) a value that is never used in $ordercol.
1706 function update_field_with_unique_index($table, $field, array $newvalues,
1707 array $otherconditions, $unusedvalue = -1) {
1708 global $DB;
1709 $safechanges = decompose_update_into_safe_changes($newvalues, $unusedvalue);
1711 $transaction = $DB->start_delegated_transaction();
1712 foreach ($safechanges as $change) {
1713 list($from, $to) = $change;
1714 $otherconditions[$field] = $from;
1715 $DB->set_field($table, $field, $to, $otherconditions);
1717 $transaction->allow_commit();
1721 * Helper used by {@link update_field_with_unique_index()}. Given a desired
1722 * set of changes, break them down into single udpates that can be done one at
1723 * a time without breaking any unique index constraints.
1725 * Suppose the input is array(1 => 2, 2 => 1) and -1. Then the output will be
1726 * array (array(1, -1), array(2, 1), array(-1, 2)). This function solves this
1727 * problem in the general case, not just for simple swaps. The unit tests give
1728 * more examples.
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 something impossible
1732 * like array(1 => 2, 2 => 2) then the results are undefined. (You will probably
1733 * get a unique key violation error from the database later.)
1735 * @param array $newvalues The desired re-ordering.
1736 * E.g. array(1 => 4, 2 => 1, 3 => 3, 4 => 2).
1737 * @param int $unusedvalue A value that is not currently used.
1738 * @return array A safe way to perform the re-order. An array of two-element
1739 * arrays array($from, $to).
1740 * E.g. array(array(1, -1), array(2, 1), array(4, 2), array(-1, 4)).
1742 function decompose_update_into_safe_changes(array $newvalues, $unusedvalue) {
1743 $nontrivialmap = array();
1744 foreach ($newvalues as $from => $to) {
1745 if ($from == $unusedvalue || $to == $unusedvalue) {
1746 throw new \coding_exception('Supposedly unused value ' . $unusedvalue . ' is actually used!');
1748 if ($from != $to) {
1749 $nontrivialmap[$from] = $to;
1753 if (empty($nontrivialmap)) {
1754 return array();
1757 // First we deal with all renames that are not part of cycles.
1758 // This bit is O(n^2) and it ought to be possible to do better,
1759 // but it does not seem worth the effort.
1760 $safechanges = array();
1761 $nontrivialmapchanged = true;
1762 while ($nontrivialmapchanged) {
1763 $nontrivialmapchanged = false;
1765 foreach ($nontrivialmap as $from => $to) {
1766 if (array_key_exists($to, $nontrivialmap)) {
1767 continue; // Cannot currenly do this rename.
1769 // Is safe to do this rename now.
1770 $safechanges[] = array($from, $to);
1771 unset($nontrivialmap[$from]);
1772 $nontrivialmapchanged = true;
1776 // Are we done?
1777 if (empty($nontrivialmap)) {
1778 return $safechanges;
1781 // Now what is left in $nontrivialmap must be a permutation,
1782 // which must be a combination of disjoint cycles. We need to break them.
1783 while (!empty($nontrivialmap)) {
1784 // Extract the first cycle.
1785 reset($nontrivialmap);
1786 $current = $cyclestart = key($nontrivialmap);
1787 $cycle = array();
1788 do {
1789 $cycle[] = $current;
1790 $next = $nontrivialmap[$current];
1791 unset($nontrivialmap[$current]);
1792 $current = $next;
1793 } while ($current != $cyclestart);
1795 // Now convert it to a sequence of safe renames by using a temp.
1796 $safechanges[] = array($cyclestart, $unusedvalue);
1797 $cycle[0] = $unusedvalue;
1798 $to = $cyclestart;
1799 while ($from = array_pop($cycle)) {
1800 $safechanges[] = array($from, $to);
1801 $to = $from;
1805 return $safechanges;