MDL-40589 - Theme/CLEAN - Flip YUI3 tree item icon in RTL mode in folder resource
[moodle.git] / lib / datalib.php
blob36ad2972a471a1dda5bfc6ac8e9ab8d87cdbc24e
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'));
510 $namefields = get_all_user_name_fields(true);
511 $extrafields = "$extrafields, $namefields";
513 // warning: will return UNCONFIRMED USERS
514 return $DB->get_records_sql("SELECT id, username, email, city, country, lastaccess, confirmed, mnethostid, suspended $extrafields
515 FROM {user}
516 WHERE $select
517 $sort", $params, $page, $recordsperpage);
523 * Full list of users that have confirmed their accounts.
525 * @global object
526 * @return array of unconfirmed users
528 function get_users_confirmed() {
529 global $DB, $CFG;
530 return $DB->get_records_sql("SELECT *
531 FROM {user}
532 WHERE confirmed = 1 AND deleted = 0 AND id <> ?", array($CFG->siteguest));
536 /// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
540 * Returns $course object of the top-level site.
542 * @return object A {@link $COURSE} object for the site, exception if not found
544 function get_site() {
545 global $SITE, $DB;
547 if (!empty($SITE->id)) { // We already have a global to use, so return that
548 return $SITE;
551 if ($course = $DB->get_record('course', array('category'=>0))) {
552 return $course;
553 } else {
554 // course table exists, but the site is not there,
555 // unfortunately there is no automatic way to recover
556 throw new moodle_exception('nosite', 'error');
561 * Gets a course object from database. If the course id corresponds to an
562 * already-loaded $COURSE or $SITE object, then the loaded object will be used,
563 * saving a database query.
565 * If it reuses an existing object, by default the object will be cloned. This
566 * means you can modify the object safely without affecting other code.
568 * @param int $courseid Course id
569 * @param bool $clone If true (default), makes a clone of the record
570 * @return stdClass A course object
571 * @throws dml_exception If not found in database
573 function get_course($courseid, $clone = true) {
574 global $DB, $COURSE, $SITE;
575 if (!empty($COURSE->id) && $COURSE->id == $courseid) {
576 return $clone ? clone($COURSE) : $COURSE;
577 } else if (!empty($SITE->id) && $SITE->id == $courseid) {
578 return $clone ? clone($SITE) : $SITE;
579 } else {
580 return $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
585 * Returns list of courses, for whole site, or category
587 * Returns list of courses, for whole site, or category
588 * Important: Using c.* for fields is extremely expensive because
589 * we are using distinct. You almost _NEVER_ need all the fields
590 * in such a large SELECT
592 * @global object
593 * @global object
594 * @global object
595 * @uses CONTEXT_COURSE
596 * @param string|int $categoryid Either a category id or 'all' for everything
597 * @param string $sort A field and direction to sort by
598 * @param string $fields The additional fields to return
599 * @return array Array of courses
601 function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
603 global $USER, $CFG, $DB;
605 $params = array();
607 if ($categoryid !== "all" && is_numeric($categoryid)) {
608 $categoryselect = "WHERE c.category = :catid";
609 $params['catid'] = $categoryid;
610 } else {
611 $categoryselect = "";
614 if (empty($sort)) {
615 $sortstatement = "";
616 } else {
617 $sortstatement = "ORDER BY $sort";
620 $visiblecourses = array();
622 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
624 $sql = "SELECT $fields $ccselect
625 FROM {course} c
626 $ccjoin
627 $categoryselect
628 $sortstatement";
630 // pull out all course matching the cat
631 if ($courses = $DB->get_records_sql($sql, $params)) {
633 // loop throught them
634 foreach ($courses as $course) {
635 context_helper::preload_from_record($course);
636 if (isset($course->visible) && $course->visible <= 0) {
637 // for hidden courses, require visibility check
638 if (has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
639 $visiblecourses [$course->id] = $course;
641 } else {
642 $visiblecourses [$course->id] = $course;
646 return $visiblecourses;
651 * Returns list of courses, for whole site, or category
653 * Similar to get_courses, but allows paging
654 * Important: Using c.* for fields is extremely expensive because
655 * we are using distinct. You almost _NEVER_ need all the fields
656 * in such a large SELECT
658 * @global object
659 * @global object
660 * @global object
661 * @uses CONTEXT_COURSE
662 * @param string|int $categoryid Either a category id or 'all' for everything
663 * @param string $sort A field and direction to sort by
664 * @param string $fields The additional fields to return
665 * @param int $totalcount Reference for the number of courses
666 * @param string $limitfrom The course to start from
667 * @param string $limitnum The number of courses to limit to
668 * @return array Array of courses
670 function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
671 &$totalcount, $limitfrom="", $limitnum="") {
672 global $USER, $CFG, $DB;
674 $params = array();
676 $categoryselect = "";
677 if ($categoryid !== "all" && is_numeric($categoryid)) {
678 $categoryselect = "WHERE c.category = :catid";
679 $params['catid'] = $categoryid;
680 } else {
681 $categoryselect = "";
684 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
686 $totalcount = 0;
687 if (!$limitfrom) {
688 $limitfrom = 0;
690 $visiblecourses = array();
692 $sql = "SELECT $fields $ccselect
693 FROM {course} c
694 $ccjoin
695 $categoryselect
696 ORDER BY $sort";
698 // pull out all course matching the cat
699 $rs = $DB->get_recordset_sql($sql, $params);
700 // iteration will have to be done inside loop to keep track of the limitfrom and limitnum
701 foreach($rs as $course) {
702 context_helper::preload_from_record($course);
703 if ($course->visible <= 0) {
704 // for hidden courses, require visibility check
705 if (has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
706 $totalcount++;
707 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
708 $visiblecourses [$course->id] = $course;
711 } else {
712 $totalcount++;
713 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
714 $visiblecourses [$course->id] = $course;
718 $rs->close();
719 return $visiblecourses;
723 * A list of courses that match a search
725 * @global object
726 * @global object
727 * @param array $searchterms An array of search criteria
728 * @param string $sort A field and direction to sort by
729 * @param int $page The page number to get
730 * @param int $recordsperpage The number of records per page
731 * @param int $totalcount Passed in by reference.
732 * @return object {@link $COURSE} records
734 function get_courses_search($searchterms, $sort, $page, $recordsperpage, &$totalcount) {
735 global $CFG, $DB;
737 if ($DB->sql_regex_supported()) {
738 $REGEXP = $DB->sql_regex(true);
739 $NOTREGEXP = $DB->sql_regex(false);
742 $searchcond = array();
743 $params = array();
744 $i = 0;
746 // Thanks Oracle for your non-ansi concat and type limits in coalesce. MDL-29912
747 if ($DB->get_dbfamily() == 'oracle') {
748 $concat = "(c.summary|| ' ' || c.fullname || ' ' || c.idnumber || ' ' || c.shortname)";
749 } else {
750 $concat = $DB->sql_concat("COALESCE(c.summary, '')", "' '", 'c.fullname', "' '", 'c.idnumber', "' '", 'c.shortname');
753 foreach ($searchterms as $searchterm) {
754 $i++;
756 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
757 /// will use it to simulate the "-" operator with LIKE clause
759 /// Under Oracle and MSSQL, trim the + and - operators and perform
760 /// simpler LIKE (or NOT LIKE) queries
761 if (!$DB->sql_regex_supported()) {
762 if (substr($searchterm, 0, 1) == '-') {
763 $NOT = true;
765 $searchterm = trim($searchterm, '+-');
768 // TODO: +- may not work for non latin languages
770 if (substr($searchterm,0,1) == '+') {
771 $searchterm = trim($searchterm, '+-');
772 $searchterm = preg_quote($searchterm, '|');
773 $searchcond[] = "$concat $REGEXP :ss$i";
774 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
776 } else if (substr($searchterm,0,1) == "-") {
777 $searchterm = trim($searchterm, '+-');
778 $searchterm = preg_quote($searchterm, '|');
779 $searchcond[] = "$concat $NOTREGEXP :ss$i";
780 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
782 } else {
783 $searchcond[] = $DB->sql_like($concat,":ss$i", false, true, $NOT);
784 $params['ss'.$i] = "%$searchterm%";
788 if (empty($searchcond)) {
789 $totalcount = 0;
790 return array();
793 $searchcond = implode(" AND ", $searchcond);
795 $courses = array();
796 $c = 0; // counts how many visible courses we've seen
798 // Tiki pagination
799 $limitfrom = $page * $recordsperpage;
800 $limitto = $limitfrom + $recordsperpage;
802 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
803 $fields = array_diff(array_keys($DB->get_columns('course')), array('modinfo', 'sectioncache'));
804 $sql = "SELECT c.".join(',c.',$fields)." $ccselect
805 FROM {course} c
806 $ccjoin
807 WHERE $searchcond AND c.id <> ".SITEID."
808 ORDER BY $sort";
810 $rs = $DB->get_recordset_sql($sql, $params);
811 foreach($rs as $course) {
812 if (!$course->visible) {
813 // preload contexts only for hidden courses or courses we need to return
814 context_helper::preload_from_record($course);
815 $coursecontext = context_course::instance($course->id);
816 if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
817 continue;
820 // Don't exit this loop till the end
821 // we need to count all the visible courses
822 // to update $totalcount
823 if ($c >= $limitfrom && $c < $limitto) {
824 $courses[$course->id] = $course;
826 $c++;
828 $rs->close();
830 // our caller expects 2 bits of data - our return
831 // array, and an updated $totalcount
832 $totalcount = $c;
833 return $courses;
837 * Fixes course category and course sortorder, also verifies category and course parents and paths.
838 * (circular references are not fixed)
840 * @global object
841 * @global object
842 * @uses MAX_COURSES_IN_CATEGORY
843 * @uses MAX_COURSE_CATEGORIES
844 * @uses SITEID
845 * @uses CONTEXT_COURSE
846 * @return void
848 function fix_course_sortorder() {
849 global $DB, $SITE;
851 //WARNING: this is PHP5 only code!
853 // if there are any changes made to courses or categories we will trigger
854 // the cache events to purge all cached courses/categories data
855 $cacheevents = array();
857 if ($unsorted = $DB->get_records('course_categories', array('sortorder'=>0))) {
858 //move all categories that are not sorted yet to the end
859 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('sortorder'=>0));
860 $cacheevents['changesincoursecat'] = true;
863 $allcats = $DB->get_records('course_categories', null, 'sortorder, id', 'id, sortorder, parent, depth, path');
864 $topcats = array();
865 $brokencats = array();
866 foreach ($allcats as $cat) {
867 $sortorder = (int)$cat->sortorder;
868 if (!$cat->parent) {
869 while(isset($topcats[$sortorder])) {
870 $sortorder++;
872 $topcats[$sortorder] = $cat;
873 continue;
875 if (!isset($allcats[$cat->parent])) {
876 $brokencats[] = $cat;
877 continue;
879 if (!isset($allcats[$cat->parent]->children)) {
880 $allcats[$cat->parent]->children = array();
882 while(isset($allcats[$cat->parent]->children[$sortorder])) {
883 $sortorder++;
885 $allcats[$cat->parent]->children[$sortorder] = $cat;
887 unset($allcats);
889 // add broken cats to category tree
890 if ($brokencats) {
891 $defaultcat = reset($topcats);
892 foreach ($brokencats as $cat) {
893 $topcats[] = $cat;
897 // now walk recursively the tree and fix any problems found
898 $sortorder = 0;
899 $fixcontexts = array();
900 if (_fix_course_cats($topcats, $sortorder, 0, 0, '', $fixcontexts)) {
901 $cacheevents['changesincoursecat'] = true;
904 // detect if there are "multiple" frontpage courses and fix them if needed
905 $frontcourses = $DB->get_records('course', array('category'=>0), 'id');
906 if (count($frontcourses) > 1) {
907 if (isset($frontcourses[SITEID])) {
908 $frontcourse = $frontcourses[SITEID];
909 unset($frontcourses[SITEID]);
910 } else {
911 $frontcourse = array_shift($frontcourses);
913 $defaultcat = reset($topcats);
914 foreach ($frontcourses as $course) {
915 $DB->set_field('course', 'category', $defaultcat->id, array('id'=>$course->id));
916 $context = context_course::instance($course->id);
917 $fixcontexts[$context->id] = $context;
918 $cacheevents['changesincourse'] = true;
920 unset($frontcourses);
921 } else {
922 $frontcourse = reset($frontcourses);
925 // now fix the paths and depths in context table if needed
926 if ($fixcontexts) {
927 foreach ($fixcontexts as $fixcontext) {
928 $fixcontext->reset_paths(false);
930 context_helper::build_all_paths(false);
931 unset($fixcontexts);
932 $cacheevents['changesincourse'] = true;
933 $cacheevents['changesincoursecat'] = true;
936 // release memory
937 unset($topcats);
938 unset($brokencats);
939 unset($fixcontexts);
941 // fix frontpage course sortorder
942 if ($frontcourse->sortorder != 1) {
943 $DB->set_field('course', 'sortorder', 1, array('id'=>$frontcourse->id));
944 $cacheevents['changesincourse'] = true;
947 // now fix the course counts in category records if needed
948 $sql = "SELECT cc.id, cc.coursecount, COUNT(c.id) AS newcount
949 FROM {course_categories} cc
950 LEFT JOIN {course} c ON c.category = cc.id
951 GROUP BY cc.id, cc.coursecount
952 HAVING cc.coursecount <> COUNT(c.id)";
954 if ($updatecounts = $DB->get_records_sql($sql)) {
955 // categories with more courses than MAX_COURSES_IN_CATEGORY
956 $categories = array();
957 foreach ($updatecounts as $cat) {
958 $cat->coursecount = $cat->newcount;
959 if ($cat->coursecount >= MAX_COURSES_IN_CATEGORY) {
960 $categories[] = $cat->id;
962 unset($cat->newcount);
963 $DB->update_record_raw('course_categories', $cat, true);
965 if (!empty($categories)) {
966 $str = implode(', ', $categories);
967 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);
969 $cacheevents['changesincoursecat'] = true;
972 // now make sure that sortorders in course table are withing the category sortorder ranges
973 $sql = "SELECT DISTINCT cc.id, cc.sortorder
974 FROM {course_categories} cc
975 JOIN {course} c ON c.category = cc.id
976 WHERE c.sortorder < cc.sortorder OR c.sortorder > cc.sortorder + ".MAX_COURSES_IN_CATEGORY;
978 if ($fixcategories = $DB->get_records_sql($sql)) {
979 //fix the course sortorder ranges
980 foreach ($fixcategories as $cat) {
981 $sql = "UPDATE {course}
982 SET sortorder = ".$DB->sql_modulo('sortorder', MAX_COURSES_IN_CATEGORY)." + ?
983 WHERE category = ?";
984 $DB->execute($sql, array($cat->sortorder, $cat->id));
986 $cacheevents['changesincoursecat'] = true;
988 unset($fixcategories);
990 // categories having courses with sortorder duplicates or having gaps in sortorder
991 $sql = "SELECT DISTINCT c1.category AS id , cc.sortorder
992 FROM {course} c1
993 JOIN {course} c2 ON c1.sortorder = c2.sortorder
994 JOIN {course_categories} cc ON (c1.category = cc.id)
995 WHERE c1.id <> c2.id";
996 $fixcategories = $DB->get_records_sql($sql);
998 $sql = "SELECT cc.id, cc.sortorder, cc.coursecount, MAX(c.sortorder) AS maxsort, MIN(c.sortorder) AS minsort
999 FROM {course_categories} cc
1000 JOIN {course} c ON c.category = cc.id
1001 GROUP BY cc.id, cc.sortorder, cc.coursecount
1002 HAVING (MAX(c.sortorder) <> cc.sortorder + cc.coursecount) OR (MIN(c.sortorder) <> cc.sortorder + 1)";
1003 $gapcategories = $DB->get_records_sql($sql);
1005 foreach ($gapcategories as $cat) {
1006 if (isset($fixcategories[$cat->id])) {
1007 // duplicates detected already
1009 } else if ($cat->minsort == $cat->sortorder and $cat->maxsort == $cat->sortorder + $cat->coursecount - 1) {
1010 // easy - new course inserted with sortorder 0, the rest is ok
1011 $sql = "UPDATE {course}
1012 SET sortorder = sortorder + 1
1013 WHERE category = ?";
1014 $DB->execute($sql, array($cat->id));
1016 } else {
1017 // it needs full resorting
1018 $fixcategories[$cat->id] = $cat;
1020 $cacheevents['changesincourse'] = true;
1022 unset($gapcategories);
1024 // fix course sortorders in problematic categories only
1025 foreach ($fixcategories as $cat) {
1026 $i = 1;
1027 $courses = $DB->get_records('course', array('category'=>$cat->id), 'sortorder ASC, id DESC', 'id, sortorder');
1028 foreach ($courses as $course) {
1029 if ($course->sortorder != $cat->sortorder + $i) {
1030 $course->sortorder = $cat->sortorder + $i;
1031 $DB->update_record_raw('course', $course, true);
1032 $cacheevents['changesincourse'] = true;
1034 $i++;
1038 // advise all caches that need to be rebuilt
1039 foreach (array_keys($cacheevents) as $event) {
1040 cache_helper::purge_by_event($event);
1045 * Internal recursive category verification function, do not use directly!
1047 * @todo Document the arguments of this function better
1049 * @global object
1050 * @uses MAX_COURSES_IN_CATEGORY
1051 * @uses CONTEXT_COURSECAT
1052 * @param array $children
1053 * @param int $sortorder
1054 * @param string $parent
1055 * @param int $depth
1056 * @param string $path
1057 * @param array $fixcontexts
1058 * @return bool if changes were made
1060 function _fix_course_cats($children, &$sortorder, $parent, $depth, $path, &$fixcontexts) {
1061 global $DB;
1063 $depth++;
1064 $changesmade = false;
1066 foreach ($children as $cat) {
1067 $sortorder = $sortorder + MAX_COURSES_IN_CATEGORY;
1068 $update = false;
1069 if ($parent != $cat->parent or $depth != $cat->depth or $path.'/'.$cat->id != $cat->path) {
1070 $cat->parent = $parent;
1071 $cat->depth = $depth;
1072 $cat->path = $path.'/'.$cat->id;
1073 $update = true;
1075 // make sure context caches are rebuild and dirty contexts marked
1076 $context = context_coursecat::instance($cat->id);
1077 $fixcontexts[$context->id] = $context;
1079 if ($cat->sortorder != $sortorder) {
1080 $cat->sortorder = $sortorder;
1081 $update = true;
1083 if ($update) {
1084 $DB->update_record('course_categories', $cat, true);
1085 $changesmade = true;
1087 if (isset($cat->children)) {
1088 if (_fix_course_cats($cat->children, $sortorder, $cat->id, $cat->depth, $cat->path, $fixcontexts)) {
1089 $changesmade = true;
1093 return $changesmade;
1097 * List of remote courses that a user has access to via MNET.
1098 * Works only on the IDP
1100 * @global object
1101 * @global object
1102 * @param int @userid The user id to get remote courses for
1103 * @return array Array of {@link $COURSE} of course objects
1105 function get_my_remotecourses($userid=0) {
1106 global $DB, $USER;
1108 if (empty($userid)) {
1109 $userid = $USER->id;
1112 // we can not use SELECT DISTINCT + text field (summary) because of MS SQL and Oracle, subselect used therefore
1113 $sql = "SELECT c.id, c.remoteid, c.shortname, c.fullname,
1114 c.hostid, c.summary, c.summaryformat, c.categoryname AS cat_name,
1115 h.name AS hostname
1116 FROM {mnetservice_enrol_courses} c
1117 JOIN (SELECT DISTINCT hostid, remotecourseid
1118 FROM {mnetservice_enrol_enrolments}
1119 WHERE userid = ?
1120 ) e ON (e.hostid = c.hostid AND e.remotecourseid = c.remoteid)
1121 JOIN {mnet_host} h ON h.id = c.hostid";
1123 return $DB->get_records_sql($sql, array($userid));
1127 * List of remote hosts that a user has access to via MNET.
1128 * Works on the SP
1130 * @global object
1131 * @global object
1132 * @return array|bool Array of host objects or false
1134 function get_my_remotehosts() {
1135 global $CFG, $USER;
1137 if ($USER->mnethostid == $CFG->mnet_localhost_id) {
1138 return false; // Return nothing on the IDP
1140 if (!empty($USER->mnet_foreign_host_array) && is_array($USER->mnet_foreign_host_array)) {
1141 return $USER->mnet_foreign_host_array;
1143 return false;
1147 * This function creates a default separated/connected scale
1149 * This function creates a default separated/connected scale
1150 * so there's something in the database. The locations of
1151 * strings and files is a bit odd, but this is because we
1152 * need to maintain backward compatibility with many different
1153 * existing language translations and older sites.
1155 * @global object
1156 * @return void
1158 function make_default_scale() {
1159 global $DB;
1161 $defaultscale = new stdClass();
1162 $defaultscale->courseid = 0;
1163 $defaultscale->userid = 0;
1164 $defaultscale->name = get_string('separateandconnected');
1165 $defaultscale->description = get_string('separateandconnectedinfo');
1166 $defaultscale->scale = get_string('postrating1', 'forum').','.
1167 get_string('postrating2', 'forum').','.
1168 get_string('postrating3', 'forum');
1169 $defaultscale->timemodified = time();
1171 $defaultscale->id = $DB->insert_record('scale', $defaultscale);
1172 $DB->execute("UPDATE {forum} SET scale = ?", array($defaultscale->id));
1177 * Returns a menu of all available scales from the site as well as the given course
1179 * @global object
1180 * @param int $courseid The id of the course as found in the 'course' table.
1181 * @return array
1183 function get_scales_menu($courseid=0) {
1184 global $DB;
1186 $sql = "SELECT id, name
1187 FROM {scale}
1188 WHERE courseid = 0 or courseid = ?
1189 ORDER BY courseid ASC, name ASC";
1190 $params = array($courseid);
1192 if ($scales = $DB->get_records_sql_menu($sql, $params)) {
1193 return $scales;
1196 make_default_scale();
1198 return $DB->get_records_sql_menu($sql, $params);
1204 * Given a set of timezone records, put them in the database, replacing what is there
1206 * @global object
1207 * @param array $timezones An array of timezone records
1208 * @return void
1210 function update_timezone_records($timezones) {
1211 global $DB;
1213 /// Clear out all the old stuff
1214 $DB->delete_records('timezone');
1216 /// Insert all the new stuff
1217 foreach ($timezones as $timezone) {
1218 if (is_array($timezone)) {
1219 $timezone = (object)$timezone;
1221 $DB->insert_record('timezone', $timezone);
1226 /// MODULE FUNCTIONS /////////////////////////////////////////////////
1229 * Just gets a raw list of all modules in a course
1231 * @global object
1232 * @param int $courseid The id of the course as found in the 'course' table.
1233 * @return array
1235 function get_course_mods($courseid) {
1236 global $DB;
1238 if (empty($courseid)) {
1239 return false; // avoid warnings
1242 return $DB->get_records_sql("SELECT cm.*, m.name as modname
1243 FROM {modules} m, {course_modules} cm
1244 WHERE cm.course = ? AND cm.module = m.id AND m.visible = 1",
1245 array($courseid)); // no disabled mods
1250 * Given an id of a course module, finds the coursemodule description
1252 * @global object
1253 * @param string $modulename name of module type, eg. resource, assignment,... (optional, slower and less safe if not specified)
1254 * @param int $cmid course module id (id in course_modules table)
1255 * @param int $courseid optional course id for extra validation
1256 * @param bool $sectionnum include relative section number (0,1,2 ...)
1257 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1258 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1259 * MUST_EXIST means throw exception if no record or multiple records found
1260 * @return stdClass
1262 function get_coursemodule_from_id($modulename, $cmid, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1263 global $DB;
1265 $params = array('cmid'=>$cmid);
1267 if (!$modulename) {
1268 if (!$modulename = $DB->get_field_sql("SELECT md.name
1269 FROM {modules} md
1270 JOIN {course_modules} cm ON cm.module = md.id
1271 WHERE cm.id = :cmid", $params, $strictness)) {
1272 return false;
1276 $params['modulename'] = $modulename;
1278 $courseselect = "";
1279 $sectionfield = "";
1280 $sectionjoin = "";
1282 if ($courseid) {
1283 $courseselect = "AND cm.course = :courseid";
1284 $params['courseid'] = $courseid;
1287 if ($sectionnum) {
1288 $sectionfield = ", cw.section AS sectionnum";
1289 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1292 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1293 FROM {course_modules} cm
1294 JOIN {modules} md ON md.id = cm.module
1295 JOIN {".$modulename."} m ON m.id = cm.instance
1296 $sectionjoin
1297 WHERE cm.id = :cmid AND md.name = :modulename
1298 $courseselect";
1300 return $DB->get_record_sql($sql, $params, $strictness);
1304 * Given an instance number of a module, finds the coursemodule description
1306 * @global object
1307 * @param string $modulename name of module type, eg. resource, assignment,...
1308 * @param int $instance module instance number (id in resource, assignment etc. table)
1309 * @param int $courseid optional course id for extra validation
1310 * @param bool $sectionnum include relative section number (0,1,2 ...)
1311 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1312 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1313 * MUST_EXIST means throw exception if no record or multiple records found
1314 * @return stdClass
1316 function get_coursemodule_from_instance($modulename, $instance, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1317 global $DB;
1319 $params = array('instance'=>$instance, 'modulename'=>$modulename);
1321 $courseselect = "";
1322 $sectionfield = "";
1323 $sectionjoin = "";
1325 if ($courseid) {
1326 $courseselect = "AND cm.course = :courseid";
1327 $params['courseid'] = $courseid;
1330 if ($sectionnum) {
1331 $sectionfield = ", cw.section AS sectionnum";
1332 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1335 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1336 FROM {course_modules} cm
1337 JOIN {modules} md ON md.id = cm.module
1338 JOIN {".$modulename."} m ON m.id = cm.instance
1339 $sectionjoin
1340 WHERE m.id = :instance AND md.name = :modulename
1341 $courseselect";
1343 return $DB->get_record_sql($sql, $params, $strictness);
1347 * Returns all course modules of given activity in course
1349 * @param string $modulename The module name (forum, quiz, etc.)
1350 * @param int $courseid The course id to get modules for
1351 * @param string $extrafields extra fields starting with m.
1352 * @return array Array of results
1354 function get_coursemodules_in_course($modulename, $courseid, $extrafields='') {
1355 global $DB;
1357 if (!empty($extrafields)) {
1358 $extrafields = ", $extrafields";
1360 $params = array();
1361 $params['courseid'] = $courseid;
1362 $params['modulename'] = $modulename;
1365 return $DB->get_records_sql("SELECT cm.*, m.name, md.name as modname $extrafields
1366 FROM {course_modules} cm, {modules} md, {".$modulename."} m
1367 WHERE cm.course = :courseid AND
1368 cm.instance = m.id AND
1369 md.name = :modulename AND
1370 md.id = cm.module", $params);
1374 * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1376 * Returns an array of all the active instances of a particular
1377 * module in given courses, sorted in the order they are defined
1378 * in the course. Returns an empty array on any errors.
1380 * The returned objects includle the columns cw.section, cm.visible,
1381 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1383 * @global object
1384 * @global object
1385 * @param string $modulename The name of the module to get instances for
1386 * @param array $courses an array of course objects.
1387 * @param int $userid
1388 * @param int $includeinvisible
1389 * @return array of module instance objects, including some extra fields from the course_modules
1390 * and course_sections tables, or an empty array if an error occurred.
1392 function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
1393 global $CFG, $DB;
1395 $outputarray = array();
1397 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1398 return $outputarray;
1401 list($coursessql, $params) = $DB->get_in_or_equal(array_keys($courses), SQL_PARAMS_NAMED, 'c0');
1402 $params['modulename'] = $modulename;
1404 if (!$rawmods = $DB->get_records_sql("SELECT cm.id AS coursemodule, m.*, cw.section, cm.visible AS visible,
1405 cm.groupmode, cm.groupingid, cm.groupmembersonly
1406 FROM {course_modules} cm, {course_sections} cw, {modules} md,
1407 {".$modulename."} m
1408 WHERE cm.course $coursessql AND
1409 cm.instance = m.id AND
1410 cm.section = cw.id AND
1411 md.name = :modulename AND
1412 md.id = cm.module", $params)) {
1413 return $outputarray;
1416 foreach ($courses as $course) {
1417 $modinfo = get_fast_modinfo($course, $userid);
1419 if (empty($modinfo->instances[$modulename])) {
1420 continue;
1423 foreach ($modinfo->instances[$modulename] as $cm) {
1424 if (!$includeinvisible and !$cm->uservisible) {
1425 continue;
1427 if (!isset($rawmods[$cm->id])) {
1428 continue;
1430 $instance = $rawmods[$cm->id];
1431 if (!empty($cm->extra)) {
1432 $instance->extra = $cm->extra;
1434 $outputarray[] = $instance;
1438 return $outputarray;
1442 * Returns an array of all the active instances of a particular module in a given course,
1443 * sorted in the order they are defined.
1445 * Returns an array of all the active instances of a particular
1446 * module in a given course, sorted in the order they are defined
1447 * in the course. Returns an empty array on any errors.
1449 * The returned objects includle the columns cw.section, cm.visible,
1450 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1452 * Simply calls {@link all_instances_in_courses()} with a single provided course
1454 * @param string $modulename The name of the module to get instances for
1455 * @param object $course The course obect.
1456 * @return array of module instance objects, including some extra fields from the course_modules
1457 * and course_sections tables, or an empty array if an error occurred.
1458 * @param int $userid
1459 * @param int $includeinvisible
1461 function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
1462 return get_all_instances_in_courses($modulename, array($course->id => $course), $userid, $includeinvisible);
1467 * Determine whether a module instance is visible within a course
1469 * Given a valid module object with info about the id and course,
1470 * and the module's type (eg "forum") returns whether the object
1471 * is visible or not, groupmembersonly visibility not tested
1473 * @global object
1475 * @param $moduletype Name of the module eg 'forum'
1476 * @param $module Object which is the instance of the module
1477 * @return bool Success
1479 function instance_is_visible($moduletype, $module) {
1480 global $DB;
1482 if (!empty($module->id)) {
1483 $params = array('courseid'=>$module->course, 'moduletype'=>$moduletype, 'moduleid'=>$module->id);
1484 if ($records = $DB->get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.groupmembersonly, cm.course
1485 FROM {course_modules} cm, {modules} m
1486 WHERE cm.course = :courseid AND
1487 cm.module = m.id AND
1488 m.name = :moduletype AND
1489 cm.instance = :moduleid", $params)) {
1491 foreach ($records as $record) { // there should only be one - use the first one
1492 return $record->visible;
1496 return true; // visible by default!
1500 * Determine whether a course module is visible within a course,
1501 * this is different from instance_is_visible() - faster and visibility for user
1503 * @global object
1504 * @global object
1505 * @uses DEBUG_DEVELOPER
1506 * @uses CONTEXT_MODULE
1507 * @uses CONDITION_MISSING_EXTRATABLE
1508 * @param object $cm object
1509 * @param int $userid empty means current user
1510 * @return bool Success
1512 function coursemodule_visible_for_user($cm, $userid=0) {
1513 global $USER,$CFG;
1515 if (empty($cm->id)) {
1516 debugging("Incorrect course module parameter!", DEBUG_DEVELOPER);
1517 return false;
1519 if (empty($userid)) {
1520 $userid = $USER->id;
1522 if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', context_module::instance($cm->id), $userid)) {
1523 return false;
1525 if ($CFG->enableavailability) {
1526 require_once($CFG->libdir.'/conditionlib.php');
1527 $ci=new condition_info($cm,CONDITION_MISSING_EXTRATABLE);
1528 if(!$ci->is_available($cm->availableinfo,false,$userid) and
1529 !has_capability('moodle/course:viewhiddenactivities',
1530 context_module::instance($cm->id), $userid)) {
1531 return false;
1534 return groups_course_module_visible($cm, $userid);
1540 /// LOG FUNCTIONS /////////////////////////////////////////////////////
1543 * Add an entry to the config log table.
1545 * These are "action" focussed rather than web server hits,
1546 * and provide a way to easily reconstruct changes to Moodle configuration.
1548 * @package core
1549 * @category log
1550 * @global moodle_database $DB
1551 * @global stdClass $USER
1552 * @param string $name The name of the configuration change action
1553 For example 'filter_active' when activating or deactivating a filter
1554 * @param string $oldvalue The config setting's previous value
1555 * @param string $value The config setting's new value
1556 * @param string $plugin Plugin name, for example a filter name when changing filter configuration
1557 * @return void
1559 function add_to_config_log($name, $oldvalue, $value, $plugin) {
1560 global $USER, $DB;
1562 $log = new stdClass();
1563 $log->userid = during_initial_install() ? 0 :$USER->id; // 0 as user id during install
1564 $log->timemodified = time();
1565 $log->name = $name;
1566 $log->oldvalue = $oldvalue;
1567 $log->value = $value;
1568 $log->plugin = $plugin;
1569 $DB->insert_record('config_log', $log);
1573 * Add an entry to the log table.
1575 * Add an entry to the log table. These are "action" focussed rather
1576 * than web server hits, and provide a way to easily reconstruct what
1577 * any particular student has been doing.
1579 * @package core
1580 * @category log
1581 * @global moodle_database $DB
1582 * @global stdClass $CFG
1583 * @global stdClass $USER
1584 * @uses SITEID
1585 * @uses DEBUG_DEVELOPER
1586 * @uses DEBUG_ALL
1587 * @param int $courseid The course id
1588 * @param string $module The module name e.g. forum, journal, resource, course, user etc
1589 * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
1590 * @param string $url The file and parameters used to see the results of the action
1591 * @param string $info Additional description information
1592 * @param string $cm The course_module->id if there is one
1593 * @param string $user If log regards $user other than $USER
1594 * @return void
1596 function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
1597 // Note that this function intentionally does not follow the normal Moodle DB access idioms.
1598 // This is for a good reason: it is the most frequently used DB update function,
1599 // so it has been optimised for speed.
1600 global $DB, $CFG, $USER;
1602 if ($cm === '' || is_null($cm)) { // postgres won't translate empty string to its default
1603 $cm = 0;
1606 if ($user) {
1607 $userid = $user;
1608 } else {
1609 if (session_is_loggedinas()) { // Don't log
1610 return;
1612 $userid = empty($USER->id) ? '0' : $USER->id;
1615 if (isset($CFG->logguests) and !$CFG->logguests) {
1616 if (!$userid or isguestuser($userid)) {
1617 return;
1621 $REMOTE_ADDR = getremoteaddr();
1623 $timenow = time();
1624 $info = $info;
1625 if (!empty($url)) { // could break doing html_entity_decode on an empty var.
1626 $url = html_entity_decode($url, ENT_QUOTES, 'UTF-8');
1627 } else {
1628 $url = '';
1631 // Restrict length of log lines to the space actually available in the
1632 // database so that it doesn't cause a DB error. Log a warning so that
1633 // developers can avoid doing things which are likely to cause this on a
1634 // routine basis.
1635 if(!empty($info) && textlib::strlen($info)>255) {
1636 $info = textlib::substr($info,0,252).'...';
1637 debugging('Warning: logged very long info',DEBUG_DEVELOPER);
1640 // If the 100 field size is changed, also need to alter print_log in course/lib.php
1641 if(!empty($url) && textlib::strlen($url)>100) {
1642 $url = textlib::substr($url,0,97).'...';
1643 debugging('Warning: logged very long URL',DEBUG_DEVELOPER);
1646 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->logwrites++;};
1648 $log = array('time'=>$timenow, 'userid'=>$userid, 'course'=>$courseid, 'ip'=>$REMOTE_ADDR, 'module'=>$module,
1649 'cmid'=>$cm, 'action'=>$action, 'url'=>$url, 'info'=>$info);
1651 try {
1652 $DB->insert_record_raw('log', $log, false);
1653 } catch (dml_exception $e) {
1654 debugging('Error: Could not insert a new entry to the Moodle log. '. $e->error, DEBUG_ALL);
1656 // MDL-11893, alert $CFG->supportemail if insert into log failed
1657 if ($CFG->supportemail and empty($CFG->noemailever)) {
1658 // email_to_user is not usable because email_to_user tries to write to the logs table,
1659 // and this will get caught in an infinite loop, if disk is full
1660 $site = get_site();
1661 $subject = 'Insert into log failed at your moodle site '.$site->fullname;
1662 $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";
1663 $message .= "The failed query parameters are:\n\n" . var_export($log, true);
1665 $lasttime = get_config('admin', 'lastloginserterrormail');
1666 if(empty($lasttime) || time() - $lasttime > 60*60*24) { // limit to 1 email per day
1667 //using email directly rather than messaging as they may not be able to log in to access a message
1668 mail($CFG->supportemail, $subject, $message);
1669 set_config('lastloginserterrormail', time(), 'admin');
1676 * Store user last access times - called when use enters a course or site
1678 * @package core
1679 * @category log
1680 * @global stdClass $USER
1681 * @global stdClass $CFG
1682 * @global moodle_database $DB
1683 * @uses LASTACCESS_UPDATE_SECS
1684 * @uses SITEID
1685 * @param int $courseid empty courseid means site
1686 * @return void
1688 function user_accesstime_log($courseid=0) {
1689 global $USER, $CFG, $DB;
1691 if (!isloggedin() or session_is_loggedinas()) {
1692 // no access tracking
1693 return;
1696 if (isguestuser()) {
1697 // Do not update guest access times/ips for performance.
1698 return;
1701 if (empty($courseid)) {
1702 $courseid = SITEID;
1705 $timenow = time();
1707 /// Store site lastaccess time for the current user
1708 if ($timenow - $USER->lastaccess > LASTACCESS_UPDATE_SECS) {
1709 /// Update $USER->lastaccess for next checks
1710 $USER->lastaccess = $timenow;
1712 $last = new stdClass();
1713 $last->id = $USER->id;
1714 $last->lastip = getremoteaddr();
1715 $last->lastaccess = $timenow;
1717 $DB->update_record_raw('user', $last);
1720 if ($courseid == SITEID) {
1721 /// no user_lastaccess for frontpage
1722 return;
1725 /// Store course lastaccess times for the current user
1726 if (empty($USER->currentcourseaccess[$courseid]) or ($timenow - $USER->currentcourseaccess[$courseid] > LASTACCESS_UPDATE_SECS)) {
1728 $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid'=>$USER->id, 'courseid'=>$courseid));
1730 if ($lastaccess === false) {
1731 // Update course lastaccess for next checks
1732 $USER->currentcourseaccess[$courseid] = $timenow;
1734 $last = new stdClass();
1735 $last->userid = $USER->id;
1736 $last->courseid = $courseid;
1737 $last->timeaccess = $timenow;
1738 $DB->insert_record_raw('user_lastaccess', $last, false);
1740 } else if ($timenow - $lastaccess < LASTACCESS_UPDATE_SECS) {
1741 // no need to update now, it was updated recently in concurrent login ;-)
1743 } else {
1744 // Update course lastaccess for next checks
1745 $USER->currentcourseaccess[$courseid] = $timenow;
1747 $DB->set_field('user_lastaccess', 'timeaccess', $timenow, array('userid'=>$USER->id, 'courseid'=>$courseid));
1753 * Select all log records based on SQL criteria
1755 * @package core
1756 * @category log
1757 * @global moodle_database $DB
1758 * @param string $select SQL select criteria
1759 * @param array $params named sql type params
1760 * @param string $order SQL order by clause to sort the records returned
1761 * @param string $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
1762 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set)
1763 * @param int $totalcount Passed in by reference.
1764 * @return array
1766 function get_logs($select, array $params=null, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
1767 global $DB;
1769 if ($order) {
1770 $order = "ORDER BY $order";
1773 $selectsql = "";
1774 $countsql = "";
1776 if ($select) {
1777 $select = "WHERE $select";
1780 $sql = "SELECT COUNT(*)
1781 FROM {log} l
1782 $select";
1784 $totalcount = $DB->count_records_sql($sql, $params);
1785 $allnames = get_all_user_name_fields(true, 'u');
1786 $sql = "SELECT l.*, $allnames, u.picture
1787 FROM {log} l
1788 LEFT JOIN {user} u ON l.userid = u.id
1789 $select
1790 $order";
1792 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum) ;
1797 * Select all log records for a given course and user
1799 * @package core
1800 * @category log
1801 * @global moodle_database $DB
1802 * @uses DAYSECS
1803 * @param int $userid The id of the user as found in the 'user' table.
1804 * @param int $courseid The id of the course as found in the 'course' table.
1805 * @param string $coursestart unix timestamp representing course start date and time.
1806 * @return array
1808 function get_logs_usercourse($userid, $courseid, $coursestart) {
1809 global $DB;
1811 $params = array();
1813 $courseselect = '';
1814 if ($courseid) {
1815 $courseselect = "AND course = :courseid";
1816 $params['courseid'] = $courseid;
1818 $params['userid'] = $userid;
1819 $$coursestart = (int)$coursestart; // note: unfortunately pg complains if you use name parameter or column alias in GROUP BY
1821 return $DB->get_records_sql("SELECT FLOOR((time - $coursestart)/". DAYSECS .") AS day, COUNT(*) AS num
1822 FROM {log}
1823 WHERE userid = :userid
1824 AND time > $coursestart $courseselect
1825 GROUP BY FLOOR((time - $coursestart)/". DAYSECS .")", $params);
1829 * Select all log records for a given course, user, and day
1831 * @package core
1832 * @category log
1833 * @global moodle_database $DB
1834 * @uses HOURSECS
1835 * @param int $userid The id of the user as found in the 'user' table.
1836 * @param int $courseid The id of the course as found in the 'course' table.
1837 * @param string $daystart unix timestamp of the start of the day for which the logs needs to be retrived
1838 * @return array
1840 function get_logs_userday($userid, $courseid, $daystart) {
1841 global $DB;
1843 $params = array('userid'=>$userid);
1845 $courseselect = '';
1846 if ($courseid) {
1847 $courseselect = "AND course = :courseid";
1848 $params['courseid'] = $courseid;
1850 $daystart = (int)$daystart; // note: unfortunately pg complains if you use name parameter or column alias in GROUP BY
1852 return $DB->get_records_sql("SELECT FLOOR((time - $daystart)/". HOURSECS .") AS hour, COUNT(*) AS num
1853 FROM {log}
1854 WHERE userid = :userid
1855 AND time > $daystart $courseselect
1856 GROUP BY FLOOR((time - $daystart)/". HOURSECS .") ", $params);
1860 * Returns an object with counts of failed login attempts
1862 * Returns information about failed login attempts. If the current user is
1863 * an admin, then two numbers are returned: the number of attempts and the
1864 * number of accounts. For non-admins, only the attempts on the given user
1865 * are shown.
1867 * @global moodle_database $DB
1868 * @uses CONTEXT_SYSTEM
1869 * @param string $mode Either 'admin' or 'everybody'
1870 * @param string $username The username we are searching for
1871 * @param string $lastlogin The date from which we are searching
1872 * @return int
1874 function count_login_failures($mode, $username, $lastlogin) {
1875 global $DB;
1877 $params = array('mode'=>$mode, 'username'=>$username, 'lastlogin'=>$lastlogin);
1878 $select = "module='login' AND action='error' AND time > :lastlogin";
1880 $count = new stdClass();
1882 if (is_siteadmin()) {
1883 if ($count->attempts = $DB->count_records_select('log', $select, $params)) {
1884 $count->accounts = $DB->count_records_select('log', $select, $params, 'COUNT(DISTINCT info)');
1885 return $count;
1887 } else if ($mode == 'everybody') {
1888 if ($count->attempts = $DB->count_records_select('log', "$select AND info = :username", $params)) {
1889 return $count;
1892 return NULL;
1896 /// GENERAL HELPFUL THINGS ///////////////////////////////////
1899 * Dumps a given object's information for debugging purposes
1901 * When used in a CLI script, the object's information is written to the standard
1902 * error output stream. When used in a web script, the object is dumped to a
1903 * pre-formatted block with the "notifytiny" CSS class.
1905 * @param mixed $object The data to be printed
1906 * @return void output is echo'd
1908 function print_object($object) {
1910 // we may need a lot of memory here
1911 raise_memory_limit(MEMORY_EXTRA);
1913 if (CLI_SCRIPT) {
1914 fwrite(STDERR, print_r($object, true));
1915 fwrite(STDERR, PHP_EOL);
1916 } else {
1917 echo html_writer::tag('pre', s(print_r($object, true)), array('class' => 'notifytiny'));
1922 * This function is the official hook inside XMLDB stuff to delegate its debug to one
1923 * external function.
1925 * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
1926 * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
1928 * @uses DEBUG_DEVELOPER
1929 * @param string $message string contains the error message
1930 * @param object $object object XMLDB object that fired the debug
1932 function xmldb_debug($message, $object) {
1934 debugging($message, DEBUG_DEVELOPER);
1938 * @global object
1939 * @uses CONTEXT_COURSECAT
1940 * @return boolean Whether the user can create courses in any category in the system.
1942 function user_can_create_courses() {
1943 global $DB;
1944 $catsrs = $DB->get_recordset('course_categories');
1945 foreach ($catsrs as $cat) {
1946 if (has_capability('moodle/course:create', context_coursecat::instance($cat->id))) {
1947 $catsrs->close();
1948 return true;
1951 $catsrs->close();
1952 return false;