Merge branch 'm25_MDL-40200_Notices_When_Viewing_Profile_Invalid_UserId' of https...
[moodle.git] / lib / datalib.php
blob3f918e8f2843caa8ec15723726a46aa7ff2114a3
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 define('LASTACCESS_UPDATE_SECS', 60);
48 /**
49 * Returns $user object of the main admin user
51 * @static stdClass $mainadmin
52 * @return stdClass {@link $USER} record from DB, false if not found
54 function get_admin() {
55 global $CFG, $DB;
57 static $mainadmin = null;
58 static $prevadmins = null;
60 if (empty($CFG->siteadmins)) {
61 // Should not happen on an ordinary site.
62 // It does however happen during unit tests.
63 return false;
66 if (isset($mainadmin) and $prevadmins === $CFG->siteadmins) {
67 return clone($mainadmin);
70 $mainadmin = null;
72 foreach (explode(',', $CFG->siteadmins) as $id) {
73 if ($user = $DB->get_record('user', array('id'=>$id, 'deleted'=>0))) {
74 $mainadmin = $user;
75 break;
79 if ($mainadmin) {
80 $prevadmins = $CFG->siteadmins;
81 return clone($mainadmin);
82 } else {
83 // this should not happen
84 return false;
88 /**
89 * Returns list of all admins, using 1 DB query
91 * @return array
93 function get_admins() {
94 global $DB, $CFG;
96 if (empty($CFG->siteadmins)) { // Should not happen on an ordinary site
97 return array();
100 $sql = "SELECT u.*
101 FROM {user} u
102 WHERE u.deleted = 0 AND u.id IN ($CFG->siteadmins)";
104 // We want the same order as in $CFG->siteadmins.
105 $records = $DB->get_records_sql($sql);
106 $admins = array();
107 foreach (explode(',', $CFG->siteadmins) as $id) {
108 $id = (int)$id;
109 if (!isset($records[$id])) {
110 // User does not exist, this should not happen.
111 continue;
113 $admins[$records[$id]->id] = $records[$id];
116 return $admins;
120 * Search through course users
122 * If $coursid specifies the site course then this function searches
123 * through all undeleted and confirmed users
125 * @global object
126 * @uses SITEID
127 * @uses SQL_PARAMS_NAMED
128 * @uses CONTEXT_COURSE
129 * @param int $courseid The course in question.
130 * @param int $groupid The group in question.
131 * @param string $searchtext The string to search for
132 * @param string $sort A field to sort by
133 * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
134 * @return array
136 function search_users($courseid, $groupid, $searchtext, $sort='', array $exceptions=null) {
137 global $DB;
139 $fullname = $DB->sql_fullname('u.firstname', 'u.lastname');
141 if (!empty($exceptions)) {
142 list($exceptions, $params) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex', false);
143 $except = "AND u.id $exceptions";
144 } else {
145 $except = "";
146 $params = array();
149 if (!empty($sort)) {
150 $order = "ORDER BY $sort";
151 } else {
152 $order = "";
155 $select = "u.deleted = 0 AND u.confirmed = 1 AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('u.email', ':search2', false).")";
156 $params['search1'] = "%$searchtext%";
157 $params['search2'] = "%$searchtext%";
159 if (!$courseid or $courseid == SITEID) {
160 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
161 FROM {user} u
162 WHERE $select
163 $except
164 $order";
165 return $DB->get_records_sql($sql, $params);
167 } else {
168 if ($groupid) {
169 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
170 FROM {user} u
171 JOIN {groups_members} gm ON gm.userid = u.id
172 WHERE $select AND gm.groupid = :groupid
173 $except
174 $order";
175 $params['groupid'] = $groupid;
176 return $DB->get_records_sql($sql, $params);
178 } else {
179 $context = context_course::instance($courseid);
180 $contextlists = get_related_contexts_string($context);
182 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
183 FROM {user} u
184 JOIN {role_assignments} ra ON ra.userid = u.id
185 WHERE $select AND ra.contextid $contextlists
186 $except
187 $order";
188 return $DB->get_records_sql($sql, $params);
194 * Returns SQL used to search through user table to find users (in a query
195 * which may also join and apply other conditions).
197 * You can combine this SQL with an existing query by adding 'AND $sql' to the
198 * WHERE clause of your query (where $sql is the first element in the array
199 * returned by this function), and merging in the $params array to the parameters
200 * of your query (where $params is the second element). Your query should use
201 * named parameters such as :param, rather than the question mark style.
203 * There are examples of basic usage in the unit test for this function.
205 * @param string $search the text to search for (empty string = find all)
206 * @param string $u the table alias for the user table in the query being
207 * built. May be ''.
208 * @param bool $searchanywhere If true (default), searches in the middle of
209 * names, otherwise only searches at start
210 * @param array $extrafields Array of extra user fields to include in search
211 * @param array $exclude Array of user ids to exclude (empty = don't exclude)
212 * @param array $includeonly If specified, only returns users that have ids
213 * incldued in this array (empty = don't restrict)
214 * @return array an array with two elements, a fragment of SQL to go in the
215 * where clause the query, and an associative array containing any required
216 * parameters (using named placeholders).
218 function users_search_sql($search, $u = 'u', $searchanywhere = true, array $extrafields = array(),
219 array $exclude = null, array $includeonly = null) {
220 global $DB, $CFG;
221 $params = array();
222 $tests = array();
224 if ($u) {
225 $u .= '.';
228 // If we have a $search string, put a field LIKE '$search%' condition on each field.
229 if ($search) {
230 $conditions = array(
231 $DB->sql_fullname($u . 'firstname', $u . 'lastname'),
232 $conditions[] = $u . 'lastname'
234 foreach ($extrafields as $field) {
235 $conditions[] = $u . $field;
237 if ($searchanywhere) {
238 $searchparam = '%' . $search . '%';
239 } else {
240 $searchparam = $search . '%';
242 $i = 0;
243 foreach ($conditions as $key => $condition) {
244 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false, false);
245 $params["con{$i}00"] = $searchparam;
246 $i++;
248 $tests[] = '(' . implode(' OR ', $conditions) . ')';
251 // Add some additional sensible conditions.
252 $tests[] = $u . "id <> :guestid";
253 $params['guestid'] = $CFG->siteguest;
254 $tests[] = $u . 'deleted = 0';
255 $tests[] = $u . 'confirmed = 1';
257 // If we are being asked to exclude any users, do that.
258 if (!empty($exclude)) {
259 list($usertest, $userparams) = $DB->get_in_or_equal($exclude, SQL_PARAMS_NAMED, 'ex', false);
260 $tests[] = $u . 'id ' . $usertest;
261 $params = array_merge($params, $userparams);
264 // If we are validating a set list of userids, add an id IN (...) test.
265 if (!empty($includeonly)) {
266 list($usertest, $userparams) = $DB->get_in_or_equal($includeonly, SQL_PARAMS_NAMED, 'val');
267 $tests[] = $u . 'id ' . $usertest;
268 $params = array_merge($params, $userparams);
271 // In case there are no tests, add one result (this makes it easier to combine
272 // this with an existing query as you can always add AND $sql).
273 if (empty($tests)) {
274 $tests[] = '1 = 1';
277 // Combing the conditions and return.
278 return array(implode(' AND ', $tests), $params);
283 * This function generates the standard ORDER BY clause for use when generating
284 * lists of users. If you don't have a reason to use a different order, then
285 * you should use this method to generate the order when displaying lists of users.
287 * If the optional $search parameter is passed, then exact matches to the search
288 * will be sorted first. For example, suppose you have two users 'Al Zebra' and
289 * 'Alan Aardvark'. The default sort is Alan, then Al. If, however, you search for
290 * 'Al', then Al will be listed first. (With two users, this is not a big deal,
291 * but with thousands of users, it is essential.)
293 * The list of fields scanned for exact matches are:
294 * - firstname
295 * - lastname
296 * - $DB->sql_fullname
297 * - those returned by get_extra_user_fields
299 * If named parameters are used (which is the default, and highly recommended),
300 * then the parameter names are like :usersortexactN, where N is an int.
302 * The simplest possible example use is:
303 * list($sort, $params) = users_order_by_sql();
304 * $sql = 'SELECT * FROM {users} ORDER BY ' . $sort;
306 * A more complex example, showing that this sort can be combined with other sorts:
307 * list($sort, $sortparams) = users_order_by_sql('u');
308 * $sql = "SELECT g.id AS groupid, gg.groupingid, u.id AS userid, u.firstname, u.lastname, u.idnumber, u.username
309 * FROM {groups} g
310 * LEFT JOIN {groupings_groups} gg ON g.id = gg.groupid
311 * LEFT JOIN {groups_members} gm ON g.id = gm.groupid
312 * LEFT JOIN {user} u ON gm.userid = u.id
313 * WHERE g.courseid = :courseid $groupwhere $groupingwhere
314 * ORDER BY g.name, $sort";
315 * $params += $sortparams;
317 * An example showing the use of $search:
318 * list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
319 * $order = ' ORDER BY ' . $sort;
320 * $params += $sortparams;
321 * $availableusers = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage);
323 * @param string $usertablealias (optional) any table prefix for the {users} table. E.g. 'u'.
324 * @param string $search (optional) a current search string. If given,
325 * any exact matches to this string will be sorted first.
326 * @param context $context the context we are in. Use by get_extra_user_fields.
327 * Defaults to $PAGE->context.
328 * @return array with two elements:
329 * string SQL fragment to use in the ORDER BY clause. For example, "firstname, lastname".
330 * array of parameters used in the SQL fragment.
332 function users_order_by_sql($usertablealias = '', $search = null, context $context = null) {
333 global $DB, $PAGE;
335 if ($usertablealias) {
336 $tableprefix = $usertablealias . '.';
337 } else {
338 $tableprefix = '';
341 $sort = "{$tableprefix}lastname, {$tableprefix}firstname, {$tableprefix}id";
342 $params = array();
344 if (!$search) {
345 return array($sort, $params);
348 if (!$context) {
349 $context = $PAGE->context;
352 $exactconditions = array();
353 $paramkey = 'usersortexact1';
355 $exactconditions[] = $DB->sql_fullname($tableprefix . 'firstname', $tableprefix . 'lastname') .
356 ' = :' . $paramkey;
357 $params[$paramkey] = $search;
358 $paramkey++;
360 $fieldstocheck = array_merge(array('firstname', 'lastname'), get_extra_user_fields($context));
361 foreach ($fieldstocheck as $key => $field) {
362 $exactconditions[] = 'LOWER(' . $tableprefix . $field . ') = LOWER(:' . $paramkey . ')';
363 $params[$paramkey] = $search;
364 $paramkey++;
367 $sort = 'CASE WHEN ' . implode(' OR ', $exactconditions) .
368 ' THEN 0 ELSE 1 END, ' . $sort;
370 return array($sort, $params);
374 * Returns a subset of users
376 * @global object
377 * @uses DEBUG_DEVELOPER
378 * @uses SQL_PARAMS_NAMED
379 * @param bool $get If false then only a count of the records is returned
380 * @param string $search A simple string to search for
381 * @param bool $confirmed A switch to allow/disallow unconfirmed users
382 * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
383 * @param string $sort A SQL snippet for the sorting criteria to use
384 * @param string $firstinitial Users whose first name starts with $firstinitial
385 * @param string $lastinitial Users whose last name starts with $lastinitial
386 * @param string $page The page or records to return
387 * @param string $recordsperpage The number of records to return per page
388 * @param string $fields A comma separated list of fields to be returned from the chosen table.
389 * @return array|int|bool {@link $USER} records unless get is false in which case the integer count of the records found is returned.
390 * False is returned if an error is encountered.
392 function get_users($get=true, $search='', $confirmed=false, array $exceptions=null, $sort='firstname ASC',
393 $firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields='*', $extraselect='', array $extraparams=null) {
394 global $DB, $CFG;
396 if ($get && !$recordsperpage) {
397 debugging('Call to get_users with $get = true no $recordsperpage limit. ' .
398 'On large installations, this will probably cause an out of memory error. ' .
399 'Please think again and change your code so that it does not try to ' .
400 'load so much data into memory.', DEBUG_DEVELOPER);
403 $fullname = $DB->sql_fullname();
405 $select = " id <> :guestid AND deleted = 0";
406 $params = array('guestid'=>$CFG->siteguest);
408 if (!empty($search)){
409 $search = trim($search);
410 $select .= " AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('email', ':search2', false)." OR username = :search3)";
411 $params['search1'] = "%$search%";
412 $params['search2'] = "%$search%";
413 $params['search3'] = "$search";
416 if ($confirmed) {
417 $select .= " AND confirmed = 1";
420 if ($exceptions) {
421 list($exceptions, $eparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex', false);
422 $params = $params + $eparams;
423 $select .= " AND id $exceptions";
426 if ($firstinitial) {
427 $select .= " AND ".$DB->sql_like('firstname', ':fni', false, false);
428 $params['fni'] = "$firstinitial%";
430 if ($lastinitial) {
431 $select .= " AND ".$DB->sql_like('lastname', ':lni', false, false);
432 $params['lni'] = "$lastinitial%";
435 if ($extraselect) {
436 $select .= " AND $extraselect";
437 $params = $params + (array)$extraparams;
440 if ($get) {
441 return $DB->get_records_select('user', $select, $params, $sort, $fields, $page, $recordsperpage);
442 } else {
443 return $DB->count_records_select('user', $select, $params);
449 * Return filtered (if provided) list of users in site, except guest and deleted users.
451 * @param string $sort An SQL field to sort by
452 * @param string $dir The sort direction ASC|DESC
453 * @param int $page The page or records to return
454 * @param int $recordsperpage The number of records to return per page
455 * @param string $search A simple string to search for
456 * @param string $firstinitial Users whose first name starts with $firstinitial
457 * @param string $lastinitial Users whose last name starts with $lastinitial
458 * @param string $extraselect An additional SQL select statement to append to the query
459 * @param array $extraparams Additional parameters to use for the above $extraselect
460 * @param stdClass $extracontext If specified, will include user 'extra fields'
461 * as appropriate for current user and given context
462 * @return array Array of {@link $USER} records
464 function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0,
465 $search='', $firstinitial='', $lastinitial='', $extraselect='',
466 array $extraparams=null, $extracontext = null) {
467 global $DB, $CFG;
469 $fullname = $DB->sql_fullname();
471 $select = "deleted <> 1 AND id <> :guestid";
472 $params = array('guestid' => $CFG->siteguest);
474 if (!empty($search)) {
475 $search = trim($search);
476 $select .= " AND (". $DB->sql_like($fullname, ':search1', false, false).
477 " OR ". $DB->sql_like('email', ':search2', false, false).
478 " OR username = :search3)";
479 $params['search1'] = "%$search%";
480 $params['search2'] = "%$search%";
481 $params['search3'] = "$search";
484 if ($firstinitial) {
485 $select .= " AND ". $DB->sql_like('firstname', ':fni', false, false);
486 $params['fni'] = "$firstinitial%";
488 if ($lastinitial) {
489 $select .= " AND ". $DB->sql_like('lastname', ':lni', false, false);
490 $params['lni'] = "$lastinitial%";
493 if ($extraselect) {
494 $select .= " AND $extraselect";
495 $params = $params + (array)$extraparams;
498 if ($sort) {
499 $sort = " ORDER BY $sort $dir";
502 // If a context is specified, get extra user fields that the current user
503 // is supposed to see.
504 $extrafields = '';
505 if ($extracontext) {
506 $extrafields = get_extra_user_fields_sql($extracontext, '', '',
507 array('id', 'username', 'email', 'firstname', 'lastname', 'city', 'country',
508 'lastaccess', 'confirmed', 'mnethostid'));
511 // warning: will return UNCONFIRMED USERS
512 return $DB->get_records_sql("SELECT id, username, email, firstname, lastname, city, country,
513 lastaccess, confirmed, mnethostid, suspended $extrafields
514 FROM {user}
515 WHERE $select
516 $sort", $params, $page, $recordsperpage);
522 * Full list of users that have confirmed their accounts.
524 * @global object
525 * @return array of unconfirmed users
527 function get_users_confirmed() {
528 global $DB, $CFG;
529 return $DB->get_records_sql("SELECT *
530 FROM {user}
531 WHERE confirmed = 1 AND deleted = 0 AND id <> ?", array($CFG->siteguest));
535 /// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
539 * Returns $course object of the top-level site.
541 * @return object A {@link $COURSE} object for the site, exception if not found
543 function get_site() {
544 global $SITE, $DB;
546 if (!empty($SITE->id)) { // We already have a global to use, so return that
547 return $SITE;
550 if ($course = $DB->get_record('course', array('category'=>0))) {
551 return $course;
552 } else {
553 // course table exists, but the site is not there,
554 // unfortunately there is no automatic way to recover
555 throw new moodle_exception('nosite', 'error');
560 * Gets a course object from database. If the course id corresponds to an
561 * already-loaded $COURSE or $SITE object, then the loaded object will be used,
562 * saving a database query.
564 * If it reuses an existing object, by default the object will be cloned. This
565 * means you can modify the object safely without affecting other code.
567 * @param int $courseid Course id
568 * @param bool $clone If true (default), makes a clone of the record
569 * @return stdClass A course object
570 * @throws dml_exception If not found in database
572 function get_course($courseid, $clone = true) {
573 global $DB, $COURSE, $SITE;
574 if (!empty($COURSE->id) && $COURSE->id == $courseid) {
575 return $clone ? clone($COURSE) : $COURSE;
576 } else if (!empty($SITE->id) && $SITE->id == $courseid) {
577 return $clone ? clone($SITE) : $SITE;
578 } else {
579 return $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
584 * Returns list of courses, for whole site, or category
586 * Returns list of courses, for whole site, or category
587 * Important: Using c.* for fields is extremely expensive because
588 * we are using distinct. You almost _NEVER_ need all the fields
589 * in such a large SELECT
591 * @global object
592 * @global object
593 * @global object
594 * @uses CONTEXT_COURSE
595 * @param string|int $categoryid Either a category id or 'all' for everything
596 * @param string $sort A field and direction to sort by
597 * @param string $fields The additional fields to return
598 * @return array Array of courses
600 function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
602 global $USER, $CFG, $DB;
604 $params = array();
606 if ($categoryid !== "all" && is_numeric($categoryid)) {
607 $categoryselect = "WHERE c.category = :catid";
608 $params['catid'] = $categoryid;
609 } else {
610 $categoryselect = "";
613 if (empty($sort)) {
614 $sortstatement = "";
615 } else {
616 $sortstatement = "ORDER BY $sort";
619 $visiblecourses = array();
621 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
623 $sql = "SELECT $fields $ccselect
624 FROM {course} c
625 $ccjoin
626 $categoryselect
627 $sortstatement";
629 // pull out all course matching the cat
630 if ($courses = $DB->get_records_sql($sql, $params)) {
632 // loop throught them
633 foreach ($courses as $course) {
634 context_instance_preload($course);
635 if (isset($course->visible) && $course->visible <= 0) {
636 // for hidden courses, require visibility check
637 if (has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
638 $visiblecourses [$course->id] = $course;
640 } else {
641 $visiblecourses [$course->id] = $course;
645 return $visiblecourses;
650 * Returns list of courses, for whole site, or category
652 * Similar to get_courses, but allows paging
653 * Important: Using c.* for fields is extremely expensive because
654 * we are using distinct. You almost _NEVER_ need all the fields
655 * in such a large SELECT
657 * @global object
658 * @global object
659 * @global object
660 * @uses CONTEXT_COURSE
661 * @param string|int $categoryid Either a category id or 'all' for everything
662 * @param string $sort A field and direction to sort by
663 * @param string $fields The additional fields to return
664 * @param int $totalcount Reference for the number of courses
665 * @param string $limitfrom The course to start from
666 * @param string $limitnum The number of courses to limit to
667 * @return array Array of courses
669 function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
670 &$totalcount, $limitfrom="", $limitnum="") {
671 global $USER, $CFG, $DB;
673 $params = array();
675 $categoryselect = "";
676 if ($categoryid !== "all" && is_numeric($categoryid)) {
677 $categoryselect = "WHERE c.category = :catid";
678 $params['catid'] = $categoryid;
679 } else {
680 $categoryselect = "";
683 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
685 $totalcount = 0;
686 if (!$limitfrom) {
687 $limitfrom = 0;
689 $visiblecourses = array();
691 $sql = "SELECT $fields $ccselect
692 FROM {course} c
693 $ccjoin
694 $categoryselect
695 ORDER BY $sort";
697 // pull out all course matching the cat
698 $rs = $DB->get_recordset_sql($sql, $params);
699 // iteration will have to be done inside loop to keep track of the limitfrom and limitnum
700 foreach($rs as $course) {
701 context_instance_preload($course);
702 if ($course->visible <= 0) {
703 // for hidden courses, require visibility check
704 if (has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
705 $totalcount++;
706 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
707 $visiblecourses [$course->id] = $course;
710 } else {
711 $totalcount++;
712 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
713 $visiblecourses [$course->id] = $course;
717 $rs->close();
718 return $visiblecourses;
722 * A list of courses that match a search
724 * @global object
725 * @global object
726 * @param array $searchterms An array of search criteria
727 * @param string $sort A field and direction to sort by
728 * @param int $page The page number to get
729 * @param int $recordsperpage The number of records per page
730 * @param int $totalcount Passed in by reference.
731 * @return object {@link $COURSE} records
733 function get_courses_search($searchterms, $sort, $page, $recordsperpage, &$totalcount) {
734 global $CFG, $DB;
736 if ($DB->sql_regex_supported()) {
737 $REGEXP = $DB->sql_regex(true);
738 $NOTREGEXP = $DB->sql_regex(false);
741 $searchcond = array();
742 $params = array();
743 $i = 0;
745 // Thanks Oracle for your non-ansi concat and type limits in coalesce. MDL-29912
746 if ($DB->get_dbfamily() == 'oracle') {
747 $concat = "(c.summary|| ' ' || c.fullname || ' ' || c.idnumber || ' ' || c.shortname)";
748 } else {
749 $concat = $DB->sql_concat("COALESCE(c.summary, '')", "' '", 'c.fullname', "' '", 'c.idnumber', "' '", 'c.shortname');
752 foreach ($searchterms as $searchterm) {
753 $i++;
755 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
756 /// will use it to simulate the "-" operator with LIKE clause
758 /// Under Oracle and MSSQL, trim the + and - operators and perform
759 /// simpler LIKE (or NOT LIKE) queries
760 if (!$DB->sql_regex_supported()) {
761 if (substr($searchterm, 0, 1) == '-') {
762 $NOT = true;
764 $searchterm = trim($searchterm, '+-');
767 // TODO: +- may not work for non latin languages
769 if (substr($searchterm,0,1) == '+') {
770 $searchterm = trim($searchterm, '+-');
771 $searchterm = preg_quote($searchterm, '|');
772 $searchcond[] = "$concat $REGEXP :ss$i";
773 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
775 } else if (substr($searchterm,0,1) == "-") {
776 $searchterm = trim($searchterm, '+-');
777 $searchterm = preg_quote($searchterm, '|');
778 $searchcond[] = "$concat $NOTREGEXP :ss$i";
779 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
781 } else {
782 $searchcond[] = $DB->sql_like($concat,":ss$i", false, true, $NOT);
783 $params['ss'.$i] = "%$searchterm%";
787 if (empty($searchcond)) {
788 $totalcount = 0;
789 return array();
792 $searchcond = implode(" AND ", $searchcond);
794 $courses = array();
795 $c = 0; // counts how many visible courses we've seen
797 // Tiki pagination
798 $limitfrom = $page * $recordsperpage;
799 $limitto = $limitfrom + $recordsperpage;
801 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
802 $fields = array_diff(array_keys($DB->get_columns('course')), array('modinfo', 'sectioncache'));
803 $sql = "SELECT c.".join(',c.',$fields)." $ccselect
804 FROM {course} c
805 $ccjoin
806 WHERE $searchcond AND c.id <> ".SITEID."
807 ORDER BY $sort";
809 $rs = $DB->get_recordset_sql($sql, $params);
810 foreach($rs as $course) {
811 if (!$course->visible) {
812 // preload contexts only for hidden courses or courses we need to return
813 context_instance_preload($course);
814 $coursecontext = context_course::instance($course->id);
815 if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
816 continue;
819 // Don't exit this loop till the end
820 // we need to count all the visible courses
821 // to update $totalcount
822 if ($c >= $limitfrom && $c < $limitto) {
823 $courses[$course->id] = $course;
825 $c++;
827 $rs->close();
829 // our caller expects 2 bits of data - our return
830 // array, and an updated $totalcount
831 $totalcount = $c;
832 return $courses;
836 * Fixes course category and course sortorder, also verifies category and course parents and paths.
837 * (circular references are not fixed)
839 * @global object
840 * @global object
841 * @uses MAX_COURSES_IN_CATEGORY
842 * @uses MAX_COURSE_CATEGORIES
843 * @uses SITEID
844 * @uses CONTEXT_COURSE
845 * @return void
847 function fix_course_sortorder() {
848 global $DB, $SITE;
850 //WARNING: this is PHP5 only code!
852 // if there are any changes made to courses or categories we will trigger
853 // the cache events to purge all cached courses/categories data
854 $cacheevents = array();
856 if ($unsorted = $DB->get_records('course_categories', array('sortorder'=>0))) {
857 //move all categories that are not sorted yet to the end
858 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('sortorder'=>0));
859 $cacheevents['changesincoursecat'] = true;
862 $allcats = $DB->get_records('course_categories', null, 'sortorder, id', 'id, sortorder, parent, depth, path');
863 $topcats = array();
864 $brokencats = array();
865 foreach ($allcats as $cat) {
866 $sortorder = (int)$cat->sortorder;
867 if (!$cat->parent) {
868 while(isset($topcats[$sortorder])) {
869 $sortorder++;
871 $topcats[$sortorder] = $cat;
872 continue;
874 if (!isset($allcats[$cat->parent])) {
875 $brokencats[] = $cat;
876 continue;
878 if (!isset($allcats[$cat->parent]->children)) {
879 $allcats[$cat->parent]->children = array();
881 while(isset($allcats[$cat->parent]->children[$sortorder])) {
882 $sortorder++;
884 $allcats[$cat->parent]->children[$sortorder] = $cat;
886 unset($allcats);
888 // add broken cats to category tree
889 if ($brokencats) {
890 $defaultcat = reset($topcats);
891 foreach ($brokencats as $cat) {
892 $topcats[] = $cat;
896 // now walk recursively the tree and fix any problems found
897 $sortorder = 0;
898 $fixcontexts = array();
899 if (_fix_course_cats($topcats, $sortorder, 0, 0, '', $fixcontexts)) {
900 $cacheevents['changesincoursecat'] = true;
903 // detect if there are "multiple" frontpage courses and fix them if needed
904 $frontcourses = $DB->get_records('course', array('category'=>0), 'id');
905 if (count($frontcourses) > 1) {
906 if (isset($frontcourses[SITEID])) {
907 $frontcourse = $frontcourses[SITEID];
908 unset($frontcourses[SITEID]);
909 } else {
910 $frontcourse = array_shift($frontcourses);
912 $defaultcat = reset($topcats);
913 foreach ($frontcourses as $course) {
914 $DB->set_field('course', 'category', $defaultcat->id, array('id'=>$course->id));
915 $context = context_course::instance($course->id);
916 $fixcontexts[$context->id] = $context;
917 $cacheevents['changesincourse'] = true;
919 unset($frontcourses);
920 } else {
921 $frontcourse = reset($frontcourses);
924 // now fix the paths and depths in context table if needed
925 if ($fixcontexts) {
926 foreach ($fixcontexts as $fixcontext) {
927 $fixcontext->reset_paths(false);
929 context_helper::build_all_paths(false);
930 unset($fixcontexts);
931 $cacheevents['changesincourse'] = true;
932 $cacheevents['changesincoursecat'] = true;
935 // release memory
936 unset($topcats);
937 unset($brokencats);
938 unset($fixcontexts);
940 // fix frontpage course sortorder
941 if ($frontcourse->sortorder != 1) {
942 $DB->set_field('course', 'sortorder', 1, array('id'=>$frontcourse->id));
943 $cacheevents['changesincourse'] = true;
946 // now fix the course counts in category records if needed
947 $sql = "SELECT cc.id, cc.coursecount, COUNT(c.id) AS newcount
948 FROM {course_categories} cc
949 LEFT JOIN {course} c ON c.category = cc.id
950 GROUP BY cc.id, cc.coursecount
951 HAVING cc.coursecount <> COUNT(c.id)";
953 if ($updatecounts = $DB->get_records_sql($sql)) {
954 // categories with more courses than MAX_COURSES_IN_CATEGORY
955 $categories = array();
956 foreach ($updatecounts as $cat) {
957 $cat->coursecount = $cat->newcount;
958 if ($cat->coursecount >= MAX_COURSES_IN_CATEGORY) {
959 $categories[] = $cat->id;
961 unset($cat->newcount);
962 $DB->update_record_raw('course_categories', $cat, true);
964 if (!empty($categories)) {
965 $str = implode(', ', $categories);
966 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);
968 $cacheevents['changesincoursecat'] = true;
971 // now make sure that sortorders in course table are withing the category sortorder ranges
972 $sql = "SELECT DISTINCT cc.id, cc.sortorder
973 FROM {course_categories} cc
974 JOIN {course} c ON c.category = cc.id
975 WHERE c.sortorder < cc.sortorder OR c.sortorder > cc.sortorder + ".MAX_COURSES_IN_CATEGORY;
977 if ($fixcategories = $DB->get_records_sql($sql)) {
978 //fix the course sortorder ranges
979 foreach ($fixcategories as $cat) {
980 $sql = "UPDATE {course}
981 SET sortorder = ".$DB->sql_modulo('sortorder', MAX_COURSES_IN_CATEGORY)." + ?
982 WHERE category = ?";
983 $DB->execute($sql, array($cat->sortorder, $cat->id));
985 $cacheevents['changesincoursecat'] = true;
987 unset($fixcategories);
989 // categories having courses with sortorder duplicates or having gaps in sortorder
990 $sql = "SELECT DISTINCT c1.category AS id , cc.sortorder
991 FROM {course} c1
992 JOIN {course} c2 ON c1.sortorder = c2.sortorder
993 JOIN {course_categories} cc ON (c1.category = cc.id)
994 WHERE c1.id <> c2.id";
995 $fixcategories = $DB->get_records_sql($sql);
997 $sql = "SELECT cc.id, cc.sortorder, cc.coursecount, MAX(c.sortorder) AS maxsort, MIN(c.sortorder) AS minsort
998 FROM {course_categories} cc
999 JOIN {course} c ON c.category = cc.id
1000 GROUP BY cc.id, cc.sortorder, cc.coursecount
1001 HAVING (MAX(c.sortorder) <> cc.sortorder + cc.coursecount) OR (MIN(c.sortorder) <> cc.sortorder + 1)";
1002 $gapcategories = $DB->get_records_sql($sql);
1004 foreach ($gapcategories as $cat) {
1005 if (isset($fixcategories[$cat->id])) {
1006 // duplicates detected already
1008 } else if ($cat->minsort == $cat->sortorder and $cat->maxsort == $cat->sortorder + $cat->coursecount - 1) {
1009 // easy - new course inserted with sortorder 0, the rest is ok
1010 $sql = "UPDATE {course}
1011 SET sortorder = sortorder + 1
1012 WHERE category = ?";
1013 $DB->execute($sql, array($cat->id));
1015 } else {
1016 // it needs full resorting
1017 $fixcategories[$cat->id] = $cat;
1019 $cacheevents['changesincourse'] = true;
1021 unset($gapcategories);
1023 // fix course sortorders in problematic categories only
1024 foreach ($fixcategories as $cat) {
1025 $i = 1;
1026 $courses = $DB->get_records('course', array('category'=>$cat->id), 'sortorder ASC, id DESC', 'id, sortorder');
1027 foreach ($courses as $course) {
1028 if ($course->sortorder != $cat->sortorder + $i) {
1029 $course->sortorder = $cat->sortorder + $i;
1030 $DB->update_record_raw('course', $course, true);
1031 $cacheevents['changesincourse'] = true;
1033 $i++;
1037 // advise all caches that need to be rebuilt
1038 foreach (array_keys($cacheevents) as $event) {
1039 cache_helper::purge_by_event($event);
1044 * Internal recursive category verification function, do not use directly!
1046 * @todo Document the arguments of this function better
1048 * @global object
1049 * @uses MAX_COURSES_IN_CATEGORY
1050 * @uses CONTEXT_COURSECAT
1051 * @param array $children
1052 * @param int $sortorder
1053 * @param string $parent
1054 * @param int $depth
1055 * @param string $path
1056 * @param array $fixcontexts
1057 * @return bool if changes were made
1059 function _fix_course_cats($children, &$sortorder, $parent, $depth, $path, &$fixcontexts) {
1060 global $DB;
1062 $depth++;
1063 $changesmade = false;
1065 foreach ($children as $cat) {
1066 $sortorder = $sortorder + MAX_COURSES_IN_CATEGORY;
1067 $update = false;
1068 if ($parent != $cat->parent or $depth != $cat->depth or $path.'/'.$cat->id != $cat->path) {
1069 $cat->parent = $parent;
1070 $cat->depth = $depth;
1071 $cat->path = $path.'/'.$cat->id;
1072 $update = true;
1074 // make sure context caches are rebuild and dirty contexts marked
1075 $context = context_coursecat::instance($cat->id);
1076 $fixcontexts[$context->id] = $context;
1078 if ($cat->sortorder != $sortorder) {
1079 $cat->sortorder = $sortorder;
1080 $update = true;
1082 if ($update) {
1083 $DB->update_record('course_categories', $cat, true);
1084 $changesmade = true;
1086 if (isset($cat->children)) {
1087 if (_fix_course_cats($cat->children, $sortorder, $cat->id, $cat->depth, $cat->path, $fixcontexts)) {
1088 $changesmade = true;
1092 return $changesmade;
1096 * List of remote courses that a user has access to via MNET.
1097 * Works only on the IDP
1099 * @global object
1100 * @global object
1101 * @param int @userid The user id to get remote courses for
1102 * @return array Array of {@link $COURSE} of course objects
1104 function get_my_remotecourses($userid=0) {
1105 global $DB, $USER;
1107 if (empty($userid)) {
1108 $userid = $USER->id;
1111 // we can not use SELECT DISTINCT + text field (summary) because of MS SQL and Oracle, subselect used therefore
1112 $sql = "SELECT c.id, c.remoteid, c.shortname, c.fullname,
1113 c.hostid, c.summary, c.summaryformat, c.categoryname AS cat_name,
1114 h.name AS hostname
1115 FROM {mnetservice_enrol_courses} c
1116 JOIN (SELECT DISTINCT hostid, remotecourseid
1117 FROM {mnetservice_enrol_enrolments}
1118 WHERE userid = ?
1119 ) e ON (e.hostid = c.hostid AND e.remotecourseid = c.remoteid)
1120 JOIN {mnet_host} h ON h.id = c.hostid";
1122 return $DB->get_records_sql($sql, array($userid));
1126 * List of remote hosts that a user has access to via MNET.
1127 * Works on the SP
1129 * @global object
1130 * @global object
1131 * @return array|bool Array of host objects or false
1133 function get_my_remotehosts() {
1134 global $CFG, $USER;
1136 if ($USER->mnethostid == $CFG->mnet_localhost_id) {
1137 return false; // Return nothing on the IDP
1139 if (!empty($USER->mnet_foreign_host_array) && is_array($USER->mnet_foreign_host_array)) {
1140 return $USER->mnet_foreign_host_array;
1142 return false;
1146 * This function creates a default separated/connected scale
1148 * This function creates a default separated/connected scale
1149 * so there's something in the database. The locations of
1150 * strings and files is a bit odd, but this is because we
1151 * need to maintain backward compatibility with many different
1152 * existing language translations and older sites.
1154 * @global object
1155 * @return void
1157 function make_default_scale() {
1158 global $DB;
1160 $defaultscale = new stdClass();
1161 $defaultscale->courseid = 0;
1162 $defaultscale->userid = 0;
1163 $defaultscale->name = get_string('separateandconnected');
1164 $defaultscale->description = get_string('separateandconnectedinfo');
1165 $defaultscale->scale = get_string('postrating1', 'forum').','.
1166 get_string('postrating2', 'forum').','.
1167 get_string('postrating3', 'forum');
1168 $defaultscale->timemodified = time();
1170 $defaultscale->id = $DB->insert_record('scale', $defaultscale);
1171 $DB->execute("UPDATE {forum} SET scale = ?", array($defaultscale->id));
1176 * Returns a menu of all available scales from the site as well as the given course
1178 * @global object
1179 * @param int $courseid The id of the course as found in the 'course' table.
1180 * @return array
1182 function get_scales_menu($courseid=0) {
1183 global $DB;
1185 $sql = "SELECT id, name
1186 FROM {scale}
1187 WHERE courseid = 0 or courseid = ?
1188 ORDER BY courseid ASC, name ASC";
1189 $params = array($courseid);
1191 if ($scales = $DB->get_records_sql_menu($sql, $params)) {
1192 return $scales;
1195 make_default_scale();
1197 return $DB->get_records_sql_menu($sql, $params);
1203 * Given a set of timezone records, put them in the database, replacing what is there
1205 * @global object
1206 * @param array $timezones An array of timezone records
1207 * @return void
1209 function update_timezone_records($timezones) {
1210 global $DB;
1212 /// Clear out all the old stuff
1213 $DB->delete_records('timezone');
1215 /// Insert all the new stuff
1216 foreach ($timezones as $timezone) {
1217 if (is_array($timezone)) {
1218 $timezone = (object)$timezone;
1220 $DB->insert_record('timezone', $timezone);
1225 /// MODULE FUNCTIONS /////////////////////////////////////////////////
1228 * Just gets a raw list of all modules in a course
1230 * @global object
1231 * @param int $courseid The id of the course as found in the 'course' table.
1232 * @return array
1234 function get_course_mods($courseid) {
1235 global $DB;
1237 if (empty($courseid)) {
1238 return false; // avoid warnings
1241 return $DB->get_records_sql("SELECT cm.*, m.name as modname
1242 FROM {modules} m, {course_modules} cm
1243 WHERE cm.course = ? AND cm.module = m.id AND m.visible = 1",
1244 array($courseid)); // no disabled mods
1249 * Given an id of a course module, finds the coursemodule description
1251 * @global object
1252 * @param string $modulename name of module type, eg. resource, assignment,... (optional, slower and less safe if not specified)
1253 * @param int $cmid course module id (id in course_modules table)
1254 * @param int $courseid optional course id for extra validation
1255 * @param bool $sectionnum include relative section number (0,1,2 ...)
1256 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1257 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1258 * MUST_EXIST means throw exception if no record or multiple records found
1259 * @return stdClass
1261 function get_coursemodule_from_id($modulename, $cmid, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1262 global $DB;
1264 $params = array('cmid'=>$cmid);
1266 if (!$modulename) {
1267 if (!$modulename = $DB->get_field_sql("SELECT md.name
1268 FROM {modules} md
1269 JOIN {course_modules} cm ON cm.module = md.id
1270 WHERE cm.id = :cmid", $params, $strictness)) {
1271 return false;
1275 $params['modulename'] = $modulename;
1277 $courseselect = "";
1278 $sectionfield = "";
1279 $sectionjoin = "";
1281 if ($courseid) {
1282 $courseselect = "AND cm.course = :courseid";
1283 $params['courseid'] = $courseid;
1286 if ($sectionnum) {
1287 $sectionfield = ", cw.section AS sectionnum";
1288 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1291 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1292 FROM {course_modules} cm
1293 JOIN {modules} md ON md.id = cm.module
1294 JOIN {".$modulename."} m ON m.id = cm.instance
1295 $sectionjoin
1296 WHERE cm.id = :cmid AND md.name = :modulename
1297 $courseselect";
1299 return $DB->get_record_sql($sql, $params, $strictness);
1303 * Given an instance number of a module, finds the coursemodule description
1305 * @global object
1306 * @param string $modulename name of module type, eg. resource, assignment,...
1307 * @param int $instance module instance number (id in resource, assignment etc. table)
1308 * @param int $courseid optional course id for extra validation
1309 * @param bool $sectionnum include relative section number (0,1,2 ...)
1310 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1311 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1312 * MUST_EXIST means throw exception if no record or multiple records found
1313 * @return stdClass
1315 function get_coursemodule_from_instance($modulename, $instance, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1316 global $DB;
1318 $params = array('instance'=>$instance, 'modulename'=>$modulename);
1320 $courseselect = "";
1321 $sectionfield = "";
1322 $sectionjoin = "";
1324 if ($courseid) {
1325 $courseselect = "AND cm.course = :courseid";
1326 $params['courseid'] = $courseid;
1329 if ($sectionnum) {
1330 $sectionfield = ", cw.section AS sectionnum";
1331 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1334 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1335 FROM {course_modules} cm
1336 JOIN {modules} md ON md.id = cm.module
1337 JOIN {".$modulename."} m ON m.id = cm.instance
1338 $sectionjoin
1339 WHERE m.id = :instance AND md.name = :modulename
1340 $courseselect";
1342 return $DB->get_record_sql($sql, $params, $strictness);
1346 * Returns all course modules of given activity in course
1348 * @param string $modulename The module name (forum, quiz, etc.)
1349 * @param int $courseid The course id to get modules for
1350 * @param string $extrafields extra fields starting with m.
1351 * @return array Array of results
1353 function get_coursemodules_in_course($modulename, $courseid, $extrafields='') {
1354 global $DB;
1356 if (!empty($extrafields)) {
1357 $extrafields = ", $extrafields";
1359 $params = array();
1360 $params['courseid'] = $courseid;
1361 $params['modulename'] = $modulename;
1364 return $DB->get_records_sql("SELECT cm.*, m.name, md.name as modname $extrafields
1365 FROM {course_modules} cm, {modules} md, {".$modulename."} m
1366 WHERE cm.course = :courseid AND
1367 cm.instance = m.id AND
1368 md.name = :modulename AND
1369 md.id = cm.module", $params);
1373 * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1375 * Returns an array of all the active instances of a particular
1376 * module in given courses, sorted in the order they are defined
1377 * in the course. Returns an empty array on any errors.
1379 * The returned objects includle the columns cw.section, cm.visible,
1380 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1382 * @global object
1383 * @global object
1384 * @param string $modulename The name of the module to get instances for
1385 * @param array $courses an array of course objects.
1386 * @param int $userid
1387 * @param int $includeinvisible
1388 * @return array of module instance objects, including some extra fields from the course_modules
1389 * and course_sections tables, or an empty array if an error occurred.
1391 function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
1392 global $CFG, $DB;
1394 $outputarray = array();
1396 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1397 return $outputarray;
1400 list($coursessql, $params) = $DB->get_in_or_equal(array_keys($courses), SQL_PARAMS_NAMED, 'c0');
1401 $params['modulename'] = $modulename;
1403 if (!$rawmods = $DB->get_records_sql("SELECT cm.id AS coursemodule, m.*, cw.section, cm.visible AS visible,
1404 cm.groupmode, cm.groupingid, cm.groupmembersonly
1405 FROM {course_modules} cm, {course_sections} cw, {modules} md,
1406 {".$modulename."} m
1407 WHERE cm.course $coursessql AND
1408 cm.instance = m.id AND
1409 cm.section = cw.id AND
1410 md.name = :modulename AND
1411 md.id = cm.module", $params)) {
1412 return $outputarray;
1415 foreach ($courses as $course) {
1416 $modinfo = get_fast_modinfo($course, $userid);
1418 if (empty($modinfo->instances[$modulename])) {
1419 continue;
1422 foreach ($modinfo->instances[$modulename] as $cm) {
1423 if (!$includeinvisible and !$cm->uservisible) {
1424 continue;
1426 if (!isset($rawmods[$cm->id])) {
1427 continue;
1429 $instance = $rawmods[$cm->id];
1430 if (!empty($cm->extra)) {
1431 $instance->extra = $cm->extra;
1433 $outputarray[] = $instance;
1437 return $outputarray;
1441 * Returns an array of all the active instances of a particular module in a given course,
1442 * sorted in the order they are defined.
1444 * Returns an array of all the active instances of a particular
1445 * module in a given course, sorted in the order they are defined
1446 * in the course. Returns an empty array on any errors.
1448 * The returned objects includle the columns cw.section, cm.visible,
1449 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1451 * Simply calls {@link all_instances_in_courses()} with a single provided course
1453 * @param string $modulename The name of the module to get instances for
1454 * @param object $course The course obect.
1455 * @return array of module instance objects, including some extra fields from the course_modules
1456 * and course_sections tables, or an empty array if an error occurred.
1457 * @param int $userid
1458 * @param int $includeinvisible
1460 function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
1461 return get_all_instances_in_courses($modulename, array($course->id => $course), $userid, $includeinvisible);
1466 * Determine whether a module instance is visible within a course
1468 * Given a valid module object with info about the id and course,
1469 * and the module's type (eg "forum") returns whether the object
1470 * is visible or not, groupmembersonly visibility not tested
1472 * @global object
1474 * @param $moduletype Name of the module eg 'forum'
1475 * @param $module Object which is the instance of the module
1476 * @return bool Success
1478 function instance_is_visible($moduletype, $module) {
1479 global $DB;
1481 if (!empty($module->id)) {
1482 $params = array('courseid'=>$module->course, 'moduletype'=>$moduletype, 'moduleid'=>$module->id);
1483 if ($records = $DB->get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.groupmembersonly, cm.course
1484 FROM {course_modules} cm, {modules} m
1485 WHERE cm.course = :courseid AND
1486 cm.module = m.id AND
1487 m.name = :moduletype AND
1488 cm.instance = :moduleid", $params)) {
1490 foreach ($records as $record) { // there should only be one - use the first one
1491 return $record->visible;
1495 return true; // visible by default!
1499 * Determine whether a course module is visible within a course,
1500 * this is different from instance_is_visible() - faster and visibility for user
1502 * @global object
1503 * @global object
1504 * @uses DEBUG_DEVELOPER
1505 * @uses CONTEXT_MODULE
1506 * @uses CONDITION_MISSING_EXTRATABLE
1507 * @param object $cm object
1508 * @param int $userid empty means current user
1509 * @return bool Success
1511 function coursemodule_visible_for_user($cm, $userid=0) {
1512 global $USER,$CFG;
1514 if (empty($cm->id)) {
1515 debugging("Incorrect course module parameter!", DEBUG_DEVELOPER);
1516 return false;
1518 if (empty($userid)) {
1519 $userid = $USER->id;
1521 if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', context_module::instance($cm->id), $userid)) {
1522 return false;
1524 if ($CFG->enableavailability) {
1525 require_once($CFG->libdir.'/conditionlib.php');
1526 $ci=new condition_info($cm,CONDITION_MISSING_EXTRATABLE);
1527 if(!$ci->is_available($cm->availableinfo,false,$userid) and
1528 !has_capability('moodle/course:viewhiddenactivities',
1529 context_module::instance($cm->id), $userid)) {
1530 return false;
1533 return groups_course_module_visible($cm, $userid);
1539 /// LOG FUNCTIONS /////////////////////////////////////////////////////
1543 * Add an entry to the log table.
1545 * Add an entry to the log table. These are "action" focussed rather
1546 * than web server hits, and provide a way to easily reconstruct what
1547 * any particular student has been doing.
1549 * @package core
1550 * @category log
1551 * @global moodle_database $DB
1552 * @global stdClass $CFG
1553 * @global stdClass $USER
1554 * @uses SITEID
1555 * @uses DEBUG_DEVELOPER
1556 * @uses DEBUG_ALL
1557 * @param int $courseid The course id
1558 * @param string $module The module name e.g. forum, journal, resource, course, user etc
1559 * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
1560 * @param string $url The file and parameters used to see the results of the action
1561 * @param string $info Additional description information
1562 * @param string $cm The course_module->id if there is one
1563 * @param string $user If log regards $user other than $USER
1564 * @return void
1566 function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
1567 // Note that this function intentionally does not follow the normal Moodle DB access idioms.
1568 // This is for a good reason: it is the most frequently used DB update function,
1569 // so it has been optimised for speed.
1570 global $DB, $CFG, $USER;
1572 if ($cm === '' || is_null($cm)) { // postgres won't translate empty string to its default
1573 $cm = 0;
1576 if ($user) {
1577 $userid = $user;
1578 } else {
1579 if (session_is_loggedinas()) { // Don't log
1580 return;
1582 $userid = empty($USER->id) ? '0' : $USER->id;
1585 if (isset($CFG->logguests) and !$CFG->logguests) {
1586 if (!$userid or isguestuser($userid)) {
1587 return;
1591 $REMOTE_ADDR = getremoteaddr();
1593 $timenow = time();
1594 $info = $info;
1595 if (!empty($url)) { // could break doing html_entity_decode on an empty var.
1596 $url = html_entity_decode($url, ENT_QUOTES, 'UTF-8');
1597 } else {
1598 $url = '';
1601 // Restrict length of log lines to the space actually available in the
1602 // database so that it doesn't cause a DB error. Log a warning so that
1603 // developers can avoid doing things which are likely to cause this on a
1604 // routine basis.
1605 if(!empty($info) && textlib::strlen($info)>255) {
1606 $info = textlib::substr($info,0,252).'...';
1607 debugging('Warning: logged very long info',DEBUG_DEVELOPER);
1610 // If the 100 field size is changed, also need to alter print_log in course/lib.php
1611 if(!empty($url) && textlib::strlen($url)>100) {
1612 $url = textlib::substr($url,0,97).'...';
1613 debugging('Warning: logged very long URL',DEBUG_DEVELOPER);
1616 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->logwrites++;};
1618 $log = array('time'=>$timenow, 'userid'=>$userid, 'course'=>$courseid, 'ip'=>$REMOTE_ADDR, 'module'=>$module,
1619 'cmid'=>$cm, 'action'=>$action, 'url'=>$url, 'info'=>$info);
1621 try {
1622 $DB->insert_record_raw('log', $log, false);
1623 } catch (dml_exception $e) {
1624 debugging('Error: Could not insert a new entry to the Moodle log. '. $e->error, DEBUG_ALL);
1626 // MDL-11893, alert $CFG->supportemail if insert into log failed
1627 if ($CFG->supportemail and empty($CFG->noemailever)) {
1628 // email_to_user is not usable because email_to_user tries to write to the logs table,
1629 // and this will get caught in an infinite loop, if disk is full
1630 $site = get_site();
1631 $subject = 'Insert into log failed at your moodle site '.$site->fullname;
1632 $message = "Insert into log table failed at ". date('l dS \of F Y h:i:s A') .".\n It is possible that your disk is full.\n\n";
1633 $message .= "The failed query parameters are:\n\n" . var_export($log, true);
1635 $lasttime = get_config('admin', 'lastloginserterrormail');
1636 if(empty($lasttime) || time() - $lasttime > 60*60*24) { // limit to 1 email per day
1637 //using email directly rather than messaging as they may not be able to log in to access a message
1638 mail($CFG->supportemail, $subject, $message);
1639 set_config('lastloginserterrormail', time(), 'admin');
1646 * Store user last access times - called when use enters a course or site
1648 * @package core
1649 * @category log
1650 * @global stdClass $USER
1651 * @global stdClass $CFG
1652 * @global moodle_database $DB
1653 * @uses LASTACCESS_UPDATE_SECS
1654 * @uses SITEID
1655 * @param int $courseid empty courseid means site
1656 * @return void
1658 function user_accesstime_log($courseid=0) {
1659 global $USER, $CFG, $DB;
1661 if (!isloggedin() or session_is_loggedinas()) {
1662 // no access tracking
1663 return;
1666 if (isguestuser()) {
1667 // Do not update guest access times/ips for performance.
1668 return;
1671 if (empty($courseid)) {
1672 $courseid = SITEID;
1675 $timenow = time();
1677 /// Store site lastaccess time for the current user
1678 if ($timenow - $USER->lastaccess > LASTACCESS_UPDATE_SECS) {
1679 /// Update $USER->lastaccess for next checks
1680 $USER->lastaccess = $timenow;
1682 $last = new stdClass();
1683 $last->id = $USER->id;
1684 $last->lastip = getremoteaddr();
1685 $last->lastaccess = $timenow;
1687 $DB->update_record_raw('user', $last);
1690 if ($courseid == SITEID) {
1691 /// no user_lastaccess for frontpage
1692 return;
1695 /// Store course lastaccess times for the current user
1696 if (empty($USER->currentcourseaccess[$courseid]) or ($timenow - $USER->currentcourseaccess[$courseid] > LASTACCESS_UPDATE_SECS)) {
1698 $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid'=>$USER->id, 'courseid'=>$courseid));
1700 if ($lastaccess === false) {
1701 // Update course lastaccess for next checks
1702 $USER->currentcourseaccess[$courseid] = $timenow;
1704 $last = new stdClass();
1705 $last->userid = $USER->id;
1706 $last->courseid = $courseid;
1707 $last->timeaccess = $timenow;
1708 $DB->insert_record_raw('user_lastaccess', $last, false);
1710 } else if ($timenow - $lastaccess < LASTACCESS_UPDATE_SECS) {
1711 // no need to update now, it was updated recently in concurrent login ;-)
1713 } else {
1714 // Update course lastaccess for next checks
1715 $USER->currentcourseaccess[$courseid] = $timenow;
1717 $DB->set_field('user_lastaccess', 'timeaccess', $timenow, array('userid'=>$USER->id, 'courseid'=>$courseid));
1723 * Select all log records based on SQL criteria
1725 * @package core
1726 * @category log
1727 * @global moodle_database $DB
1728 * @param string $select SQL select criteria
1729 * @param array $params named sql type params
1730 * @param string $order SQL order by clause to sort the records returned
1731 * @param string $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
1732 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set)
1733 * @param int $totalcount Passed in by reference.
1734 * @return array
1736 function get_logs($select, array $params=null, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
1737 global $DB;
1739 if ($order) {
1740 $order = "ORDER BY $order";
1743 $selectsql = "";
1744 $countsql = "";
1746 if ($select) {
1747 $select = "WHERE $select";
1750 $sql = "SELECT COUNT(*)
1751 FROM {log} l
1752 $select";
1754 $totalcount = $DB->count_records_sql($sql, $params);
1756 $sql = "SELECT l.*, u.firstname, u.lastname, u.picture
1757 FROM {log} l
1758 LEFT JOIN {user} u ON l.userid = u.id
1759 $select
1760 $order";
1762 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum) ;
1767 * Select all log records for a given course and user
1769 * @package core
1770 * @category log
1771 * @global moodle_database $DB
1772 * @uses DAYSECS
1773 * @param int $userid The id of the user as found in the 'user' table.
1774 * @param int $courseid The id of the course as found in the 'course' table.
1775 * @param string $coursestart unix timestamp representing course start date and time.
1776 * @return array
1778 function get_logs_usercourse($userid, $courseid, $coursestart) {
1779 global $DB;
1781 $params = array();
1783 $courseselect = '';
1784 if ($courseid) {
1785 $courseselect = "AND course = :courseid";
1786 $params['courseid'] = $courseid;
1788 $params['userid'] = $userid;
1789 $$coursestart = (int)$coursestart; // note: unfortunately pg complains if you use name parameter or column alias in GROUP BY
1791 return $DB->get_records_sql("SELECT FLOOR((time - $coursestart)/". DAYSECS .") AS day, COUNT(*) AS num
1792 FROM {log}
1793 WHERE userid = :userid
1794 AND time > $coursestart $courseselect
1795 GROUP BY FLOOR((time - $coursestart)/". DAYSECS .")", $params);
1799 * Select all log records for a given course, user, and day
1801 * @package core
1802 * @category log
1803 * @global moodle_database $DB
1804 * @uses HOURSECS
1805 * @param int $userid The id of the user as found in the 'user' table.
1806 * @param int $courseid The id of the course as found in the 'course' table.
1807 * @param string $daystart unix timestamp of the start of the day for which the logs needs to be retrived
1808 * @return array
1810 function get_logs_userday($userid, $courseid, $daystart) {
1811 global $DB;
1813 $params = array('userid'=>$userid);
1815 $courseselect = '';
1816 if ($courseid) {
1817 $courseselect = "AND course = :courseid";
1818 $params['courseid'] = $courseid;
1820 $daystart = (int)$daystart; // note: unfortunately pg complains if you use name parameter or column alias in GROUP BY
1822 return $DB->get_records_sql("SELECT FLOOR((time - $daystart)/". HOURSECS .") AS hour, COUNT(*) AS num
1823 FROM {log}
1824 WHERE userid = :userid
1825 AND time > $daystart $courseselect
1826 GROUP BY FLOOR((time - $daystart)/". HOURSECS .") ", $params);
1830 * Returns an object with counts of failed login attempts
1832 * Returns information about failed login attempts. If the current user is
1833 * an admin, then two numbers are returned: the number of attempts and the
1834 * number of accounts. For non-admins, only the attempts on the given user
1835 * are shown.
1837 * @global moodle_database $DB
1838 * @uses CONTEXT_SYSTEM
1839 * @param string $mode Either 'admin' or 'everybody'
1840 * @param string $username The username we are searching for
1841 * @param string $lastlogin The date from which we are searching
1842 * @return int
1844 function count_login_failures($mode, $username, $lastlogin) {
1845 global $DB;
1847 $params = array('mode'=>$mode, 'username'=>$username, 'lastlogin'=>$lastlogin);
1848 $select = "module='login' AND action='error' AND time > :lastlogin";
1850 $count = new stdClass();
1852 if (is_siteadmin()) {
1853 if ($count->attempts = $DB->count_records_select('log', $select, $params)) {
1854 $count->accounts = $DB->count_records_select('log', $select, $params, 'COUNT(DISTINCT info)');
1855 return $count;
1857 } else if ($mode == 'everybody') {
1858 if ($count->attempts = $DB->count_records_select('log', "$select AND info = :username", $params)) {
1859 return $count;
1862 return NULL;
1866 /// GENERAL HELPFUL THINGS ///////////////////////////////////
1869 * Dumps a given object's information for debugging purposes
1871 * When used in a CLI script, the object's information is written to the standard
1872 * error output stream. When used in a web script, the object is dumped to a
1873 * pre-formatted block with the "notifytiny" CSS class.
1875 * @param mixed $object The data to be printed
1876 * @return void output is echo'd
1878 function print_object($object) {
1880 // we may need a lot of memory here
1881 raise_memory_limit(MEMORY_EXTRA);
1883 if (CLI_SCRIPT) {
1884 fwrite(STDERR, print_r($object, true));
1885 fwrite(STDERR, PHP_EOL);
1886 } else {
1887 echo html_writer::tag('pre', s(print_r($object, true)), array('class' => 'notifytiny'));
1892 * This function is the official hook inside XMLDB stuff to delegate its debug to one
1893 * external function.
1895 * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
1896 * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
1898 * @uses DEBUG_DEVELOPER
1899 * @param string $message string contains the error message
1900 * @param object $object object XMLDB object that fired the debug
1902 function xmldb_debug($message, $object) {
1904 debugging($message, DEBUG_DEVELOPER);
1908 * @global object
1909 * @uses CONTEXT_COURSECAT
1910 * @return boolean Whether the user can create courses in any category in the system.
1912 function user_can_create_courses() {
1913 global $DB;
1914 $catsrs = $DB->get_recordset('course_categories');
1915 foreach ($catsrs as $cat) {
1916 if (has_capability('moodle/course:create', context_coursecat::instance($cat->id))) {
1917 $catsrs->close();
1918 return true;
1921 $catsrs->close();
1922 return false;