2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Library of functions for database manipulation.
20 * Other main libraries:
21 * - weblib.php - functions that produce web output
22 * - moodlelib.php - general-purpose Moodle functions
25 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') ||
die();
32 * The maximum courses in a category
33 * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
35 define('MAX_COURSES_IN_CATEGORY', 10000);
38 * The maximum number of course categories
39 * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
41 define('MAX_COURSE_CATEGORIES', 10000);
44 * Number of seconds to wait before updating lastaccess information in DB.
46 * We allow overwrites from config.php, useful to ensure coherence in performance
49 if (!defined('LASTACCESS_UPDATE_SECS')) {
50 define('LASTACCESS_UPDATE_SECS', 60);
54 * Returns $user object of the main admin user
56 * @static stdClass $mainadmin
57 * @return stdClass {@link $USER} record from DB, false if not found
59 function get_admin() {
62 static $mainadmin = null;
63 static $prevadmins = null;
65 if (empty($CFG->siteadmins
)) {
66 // Should not happen on an ordinary site.
67 // It does however happen during unit tests.
71 if (isset($mainadmin) and $prevadmins === $CFG->siteadmins
) {
72 return clone($mainadmin);
77 foreach (explode(',', $CFG->siteadmins
) as $id) {
78 if ($user = $DB->get_record('user', array('id'=>$id, 'deleted'=>0))) {
85 $prevadmins = $CFG->siteadmins
;
86 return clone($mainadmin);
88 // this should not happen
94 * Returns list of all admins, using 1 DB query
98 function get_admins() {
101 if (empty($CFG->siteadmins
)) { // Should not happen on an ordinary site
107 WHERE u.deleted = 0 AND u.id IN ($CFG->siteadmins)";
109 // We want the same order as in $CFG->siteadmins.
110 $records = $DB->get_records_sql($sql);
112 foreach (explode(',', $CFG->siteadmins
) as $id) {
114 if (!isset($records[$id])) {
115 // User does not exist, this should not happen.
118 $admins[$records[$id]->id
] = $records[$id];
125 * Search through course users
127 * If $coursid specifies the site course then this function searches
128 * through all undeleted and confirmed users
132 * @uses SQL_PARAMS_NAMED
133 * @uses CONTEXT_COURSE
134 * @param int $courseid The course in question.
135 * @param int $groupid The group in question.
136 * @param string $searchtext The string to search for
137 * @param string $sort A field to sort by
138 * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
141 function search_users($courseid, $groupid, $searchtext, $sort='', array $exceptions=null) {
144 $fullname = $DB->sql_fullname('u.firstname', 'u.lastname');
146 if (!empty($exceptions)) {
147 list($exceptions, $params) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED
, 'ex', false);
148 $except = "AND u.id $exceptions";
155 $order = "ORDER BY $sort";
160 $select = "u.deleted = 0 AND u.confirmed = 1 AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('u.email', ':search2', false).")";
161 $params['search1'] = "%$searchtext%";
162 $params['search2'] = "%$searchtext%";
164 if (!$courseid or $courseid == SITEID
) {
165 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
170 return $DB->get_records_sql($sql, $params);
174 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
176 JOIN {groups_members} gm ON gm.userid = u.id
177 WHERE $select AND gm.groupid = :groupid
180 $params['groupid'] = $groupid;
181 return $DB->get_records_sql($sql, $params);
184 $context = context_course
::instance($courseid);
186 // We want to query both the current context and parent contexts.
187 list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'relatedctx');
189 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
191 JOIN {role_assignments} ra ON ra.userid = u.id
192 WHERE $select AND ra.contextid $relatedctxsql
195 $params = array_merge($params, $relatedctxparams);
196 return $DB->get_records_sql($sql, $params);
202 * Returns SQL used to search through user table to find users (in a query
203 * which may also join and apply other conditions).
205 * You can combine this SQL with an existing query by adding 'AND $sql' to the
206 * WHERE clause of your query (where $sql is the first element in the array
207 * returned by this function), and merging in the $params array to the parameters
208 * of your query (where $params is the second element). Your query should use
209 * named parameters such as :param, rather than the question mark style.
211 * There are examples of basic usage in the unit test for this function.
213 * @param string $search the text to search for (empty string = find all)
214 * @param string $u the table alias for the user table in the query being
216 * @param bool $searchanywhere If true (default), searches in the middle of
217 * names, otherwise only searches at start
218 * @param array $extrafields Array of extra user fields to include in search
219 * @param array $exclude Array of user ids to exclude (empty = don't exclude)
220 * @param array $includeonly If specified, only returns users that have ids
221 * incldued in this array (empty = don't restrict)
222 * @return array an array with two elements, a fragment of SQL to go in the
223 * where clause the query, and an associative array containing any required
224 * parameters (using named placeholders).
226 function users_search_sql($search, $u = 'u', $searchanywhere = true, array $extrafields = array(),
227 array $exclude = null, array $includeonly = null) {
236 // If we have a $search string, put a field LIKE '$search%' condition on each field.
239 $DB->sql_fullname($u . 'firstname', $u . 'lastname'),
240 $conditions[] = $u . 'lastname'
242 foreach ($extrafields as $field) {
243 $conditions[] = $u . $field;
245 if ($searchanywhere) {
246 $searchparam = '%' . $search . '%';
248 $searchparam = $search . '%';
251 foreach ($conditions as $key => $condition) {
252 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false, false);
253 $params["con{$i}00"] = $searchparam;
256 $tests[] = '(' . implode(' OR ', $conditions) . ')';
259 // Add some additional sensible conditions.
260 $tests[] = $u . "id <> :guestid";
261 $params['guestid'] = $CFG->siteguest
;
262 $tests[] = $u . 'deleted = 0';
263 $tests[] = $u . 'confirmed = 1';
265 // If we are being asked to exclude any users, do that.
266 if (!empty($exclude)) {
267 list($usertest, $userparams) = $DB->get_in_or_equal($exclude, SQL_PARAMS_NAMED
, 'ex', false);
268 $tests[] = $u . 'id ' . $usertest;
269 $params = array_merge($params, $userparams);
272 // If we are validating a set list of userids, add an id IN (...) test.
273 if (!empty($includeonly)) {
274 list($usertest, $userparams) = $DB->get_in_or_equal($includeonly, SQL_PARAMS_NAMED
, 'val');
275 $tests[] = $u . 'id ' . $usertest;
276 $params = array_merge($params, $userparams);
279 // In case there are no tests, add one result (this makes it easier to combine
280 // this with an existing query as you can always add AND $sql).
285 // Combing the conditions and return.
286 return array(implode(' AND ', $tests), $params);
291 * This function generates the standard ORDER BY clause for use when generating
292 * lists of users. If you don't have a reason to use a different order, then
293 * you should use this method to generate the order when displaying lists of users.
295 * If the optional $search parameter is passed, then exact matches to the search
296 * will be sorted first. For example, suppose you have two users 'Al Zebra' and
297 * 'Alan Aardvark'. The default sort is Alan, then Al. If, however, you search for
298 * 'Al', then Al will be listed first. (With two users, this is not a big deal,
299 * but with thousands of users, it is essential.)
301 * The list of fields scanned for exact matches are:
304 * - $DB->sql_fullname
305 * - those returned by get_extra_user_fields
307 * If named parameters are used (which is the default, and highly recommended),
308 * then the parameter names are like :usersortexactN, where N is an int.
310 * The simplest possible example use is:
311 * list($sort, $params) = users_order_by_sql();
312 * $sql = 'SELECT * FROM {users} ORDER BY ' . $sort;
314 * A more complex example, showing that this sort can be combined with other sorts:
315 * list($sort, $sortparams) = users_order_by_sql('u');
316 * $sql = "SELECT g.id AS groupid, gg.groupingid, u.id AS userid, u.firstname, u.lastname, u.idnumber, u.username
318 * LEFT JOIN {groupings_groups} gg ON g.id = gg.groupid
319 * LEFT JOIN {groups_members} gm ON g.id = gm.groupid
320 * LEFT JOIN {user} u ON gm.userid = u.id
321 * WHERE g.courseid = :courseid $groupwhere $groupingwhere
322 * ORDER BY g.name, $sort";
323 * $params += $sortparams;
325 * An example showing the use of $search:
326 * list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
327 * $order = ' ORDER BY ' . $sort;
328 * $params += $sortparams;
329 * $availableusers = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage);
331 * @param string $usertablealias (optional) any table prefix for the {users} table. E.g. 'u'.
332 * @param string $search (optional) a current search string. If given,
333 * any exact matches to this string will be sorted first.
334 * @param context $context the context we are in. Use by get_extra_user_fields.
335 * Defaults to $PAGE->context.
336 * @return array with two elements:
337 * string SQL fragment to use in the ORDER BY clause. For example, "firstname, lastname".
338 * array of parameters used in the SQL fragment.
340 function users_order_by_sql($usertablealias = '', $search = null, context
$context = null) {
343 if ($usertablealias) {
344 $tableprefix = $usertablealias . '.';
349 $sort = "{$tableprefix}lastname, {$tableprefix}firstname, {$tableprefix}id";
353 return array($sort, $params);
357 $context = $PAGE->context
;
360 $exactconditions = array();
361 $paramkey = 'usersortexact1';
363 $exactconditions[] = $DB->sql_fullname($tableprefix . 'firstname', $tableprefix . 'lastname') .
365 $params[$paramkey] = $search;
368 $fieldstocheck = array_merge(array('firstname', 'lastname'), get_extra_user_fields($context));
369 foreach ($fieldstocheck as $key => $field) {
370 $exactconditions[] = 'LOWER(' . $tableprefix . $field . ') = LOWER(:' . $paramkey . ')';
371 $params[$paramkey] = $search;
375 $sort = 'CASE WHEN ' . implode(' OR ', $exactconditions) .
376 ' THEN 0 ELSE 1 END, ' . $sort;
378 return array($sort, $params);
382 * Returns a subset of users
385 * @uses DEBUG_DEVELOPER
386 * @uses SQL_PARAMS_NAMED
387 * @param bool $get If false then only a count of the records is returned
388 * @param string $search A simple string to search for
389 * @param bool $confirmed A switch to allow/disallow unconfirmed users
390 * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
391 * @param string $sort A SQL snippet for the sorting criteria to use
392 * @param string $firstinitial Users whose first name starts with $firstinitial
393 * @param string $lastinitial Users whose last name starts with $lastinitial
394 * @param string $page The page or records to return
395 * @param string $recordsperpage The number of records to return per page
396 * @param string $fields A comma separated list of fields to be returned from the chosen table.
397 * @return array|int|bool {@link $USER} records unless get is false in which case the integer count of the records found is returned.
398 * False is returned if an error is encountered.
400 function get_users($get=true, $search='', $confirmed=false, array $exceptions=null, $sort='firstname ASC',
401 $firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields='*', $extraselect='', array $extraparams=null) {
404 if ($get && !$recordsperpage) {
405 debugging('Call to get_users with $get = true no $recordsperpage limit. ' .
406 'On large installations, this will probably cause an out of memory error. ' .
407 'Please think again and change your code so that it does not try to ' .
408 'load so much data into memory.', DEBUG_DEVELOPER
);
411 $fullname = $DB->sql_fullname();
413 $select = " id <> :guestid AND deleted = 0";
414 $params = array('guestid'=>$CFG->siteguest
);
416 if (!empty($search)){
417 $search = trim($search);
418 $select .= " AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('email', ':search2', false)." OR username = :search3)";
419 $params['search1'] = "%$search%";
420 $params['search2'] = "%$search%";
421 $params['search3'] = "$search";
425 $select .= " AND confirmed = 1";
429 list($exceptions, $eparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED
, 'ex', false);
430 $params = $params +
$eparams;
431 $select .= " AND id $exceptions";
435 $select .= " AND ".$DB->sql_like('firstname', ':fni', false, false);
436 $params['fni'] = "$firstinitial%";
439 $select .= " AND ".$DB->sql_like('lastname', ':lni', false, false);
440 $params['lni'] = "$lastinitial%";
444 $select .= " AND $extraselect";
445 $params = $params +
(array)$extraparams;
449 return $DB->get_records_select('user', $select, $params, $sort, $fields, $page, $recordsperpage);
451 return $DB->count_records_select('user', $select, $params);
457 * Return filtered (if provided) list of users in site, except guest and deleted users.
459 * @param string $sort An SQL field to sort by
460 * @param string $dir The sort direction ASC|DESC
461 * @param int $page The page or records to return
462 * @param int $recordsperpage The number of records to return per page
463 * @param string $search A simple string to search for
464 * @param string $firstinitial Users whose first name starts with $firstinitial
465 * @param string $lastinitial Users whose last name starts with $lastinitial
466 * @param string $extraselect An additional SQL select statement to append to the query
467 * @param array $extraparams Additional parameters to use for the above $extraselect
468 * @param stdClass $extracontext If specified, will include user 'extra fields'
469 * as appropriate for current user and given context
470 * @return array Array of {@link $USER} records
472 function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0,
473 $search='', $firstinitial='', $lastinitial='', $extraselect='',
474 array $extraparams=null, $extracontext = null) {
477 $fullname = $DB->sql_fullname();
479 $select = "deleted <> 1 AND id <> :guestid";
480 $params = array('guestid' => $CFG->siteguest
);
482 if (!empty($search)) {
483 $search = trim($search);
484 $select .= " AND (". $DB->sql_like($fullname, ':search1', false, false).
485 " OR ". $DB->sql_like('email', ':search2', false, false).
486 " OR username = :search3)";
487 $params['search1'] = "%$search%";
488 $params['search2'] = "%$search%";
489 $params['search3'] = "$search";
493 $select .= " AND ". $DB->sql_like('firstname', ':fni', false, false);
494 $params['fni'] = "$firstinitial%";
497 $select .= " AND ". $DB->sql_like('lastname', ':lni', false, false);
498 $params['lni'] = "$lastinitial%";
502 $select .= " AND $extraselect";
503 $params = $params +
(array)$extraparams;
507 $sort = " ORDER BY $sort $dir";
510 // If a context is specified, get extra user fields that the current user
511 // is supposed to see.
514 $extrafields = get_extra_user_fields_sql($extracontext, '', '',
515 array('id', 'username', 'email', 'firstname', 'lastname', 'city', 'country',
516 'lastaccess', 'confirmed', 'mnethostid'));
518 $namefields = get_all_user_name_fields(true);
519 $extrafields = "$extrafields, $namefields";
521 // warning: will return UNCONFIRMED USERS
522 return $DB->get_records_sql("SELECT id, username, email, city, country, lastaccess, confirmed, mnethostid, suspended $extrafields
525 $sort", $params, $page, $recordsperpage);
531 * Full list of users that have confirmed their accounts.
534 * @return array of unconfirmed users
536 function get_users_confirmed() {
538 return $DB->get_records_sql("SELECT *
540 WHERE confirmed = 1 AND deleted = 0 AND id <> ?", array($CFG->siteguest
));
544 /// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
548 * Returns $course object of the top-level site.
550 * @return object A {@link $COURSE} object for the site, exception if not found
552 function get_site() {
555 if (!empty($SITE->id
)) { // We already have a global to use, so return that
559 if ($course = $DB->get_record('course', array('category'=>0))) {
562 // course table exists, but the site is not there,
563 // unfortunately there is no automatic way to recover
564 throw new moodle_exception('nosite', 'error');
569 * Gets a course object from database. If the course id corresponds to an
570 * already-loaded $COURSE or $SITE object, then the loaded object will be used,
571 * saving a database query.
573 * If it reuses an existing object, by default the object will be cloned. This
574 * means you can modify the object safely without affecting other code.
576 * @param int $courseid Course id
577 * @param bool $clone If true (default), makes a clone of the record
578 * @return stdClass A course object
579 * @throws dml_exception If not found in database
581 function get_course($courseid, $clone = true) {
582 global $DB, $COURSE, $SITE;
583 if (!empty($COURSE->id
) && $COURSE->id
== $courseid) {
584 return $clone ?
clone($COURSE) : $COURSE;
585 } else if (!empty($SITE->id
) && $SITE->id
== $courseid) {
586 return $clone ?
clone($SITE) : $SITE;
588 return $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST
);
593 * Returns list of courses, for whole site, or category
595 * Returns list of courses, for whole site, or category
596 * Important: Using c.* for fields is extremely expensive because
597 * we are using distinct. You almost _NEVER_ need all the fields
598 * in such a large SELECT
603 * @uses CONTEXT_COURSE
604 * @param string|int $categoryid Either a category id or 'all' for everything
605 * @param string $sort A field and direction to sort by
606 * @param string $fields The additional fields to return
607 * @return array Array of courses
609 function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
611 global $USER, $CFG, $DB;
615 if ($categoryid !== "all" && is_numeric($categoryid)) {
616 $categoryselect = "WHERE c.category = :catid";
617 $params['catid'] = $categoryid;
619 $categoryselect = "";
625 $sortstatement = "ORDER BY $sort";
628 $visiblecourses = array();
630 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
631 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
632 $params['contextlevel'] = CONTEXT_COURSE
;
634 $sql = "SELECT $fields $ccselect
640 // pull out all course matching the cat
641 if ($courses = $DB->get_records_sql($sql, $params)) {
643 // loop throught them
644 foreach ($courses as $course) {
645 context_helper
::preload_from_record($course);
646 if (isset($course->visible
) && $course->visible
<= 0) {
647 // for hidden courses, require visibility check
648 if (has_capability('moodle/course:viewhiddencourses', context_course
::instance($course->id
))) {
649 $visiblecourses [$course->id
] = $course;
652 $visiblecourses [$course->id
] = $course;
656 return $visiblecourses;
661 * Returns list of courses, for whole site, or category
663 * Similar to get_courses, but allows paging
664 * Important: Using c.* for fields is extremely expensive because
665 * we are using distinct. You almost _NEVER_ need all the fields
666 * in such a large SELECT
671 * @uses CONTEXT_COURSE
672 * @param string|int $categoryid Either a category id or 'all' for everything
673 * @param string $sort A field and direction to sort by
674 * @param string $fields The additional fields to return
675 * @param int $totalcount Reference for the number of courses
676 * @param string $limitfrom The course to start from
677 * @param string $limitnum The number of courses to limit to
678 * @return array Array of courses
680 function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
681 &$totalcount, $limitfrom="", $limitnum="") {
682 global $USER, $CFG, $DB;
686 $categoryselect = "";
687 if ($categoryid !== "all" && is_numeric($categoryid)) {
688 $categoryselect = "WHERE c.category = :catid";
689 $params['catid'] = $categoryid;
691 $categoryselect = "";
694 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
695 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
696 $params['contextlevel'] = CONTEXT_COURSE
;
702 $visiblecourses = array();
704 $sql = "SELECT $fields $ccselect
710 // pull out all course matching the cat
711 $rs = $DB->get_recordset_sql($sql, $params);
712 // iteration will have to be done inside loop to keep track of the limitfrom and limitnum
713 foreach($rs as $course) {
714 context_helper
::preload_from_record($course);
715 if ($course->visible
<= 0) {
716 // for hidden courses, require visibility check
717 if (has_capability('moodle/course:viewhiddencourses', context_course
::instance($course->id
))) {
719 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
720 $visiblecourses [$course->id
] = $course;
725 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
726 $visiblecourses [$course->id
] = $course;
731 return $visiblecourses;
735 * A list of courses that match a search
739 * @param array $searchterms An array of search criteria
740 * @param string $sort A field and direction to sort by
741 * @param int $page The page number to get
742 * @param int $recordsperpage The number of records per page
743 * @param int $totalcount Passed in by reference.
744 * @return object {@link $COURSE} records
746 function get_courses_search($searchterms, $sort, $page, $recordsperpage, &$totalcount) {
749 if ($DB->sql_regex_supported()) {
750 $REGEXP = $DB->sql_regex(true);
751 $NOTREGEXP = $DB->sql_regex(false);
754 $searchcond = array();
758 // Thanks Oracle for your non-ansi concat and type limits in coalesce. MDL-29912
759 if ($DB->get_dbfamily() == 'oracle') {
760 $concat = "(c.summary|| ' ' || c.fullname || ' ' || c.idnumber || ' ' || c.shortname)";
762 $concat = $DB->sql_concat("COALESCE(c.summary, '')", "' '", 'c.fullname', "' '", 'c.idnumber', "' '", 'c.shortname');
765 foreach ($searchterms as $searchterm) {
768 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
769 /// will use it to simulate the "-" operator with LIKE clause
771 /// Under Oracle and MSSQL, trim the + and - operators and perform
772 /// simpler LIKE (or NOT LIKE) queries
773 if (!$DB->sql_regex_supported()) {
774 if (substr($searchterm, 0, 1) == '-') {
777 $searchterm = trim($searchterm, '+-');
780 // TODO: +- may not work for non latin languages
782 if (substr($searchterm,0,1) == '+') {
783 $searchterm = trim($searchterm, '+-');
784 $searchterm = preg_quote($searchterm, '|');
785 $searchcond[] = "$concat $REGEXP :ss$i";
786 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
788 } else if (substr($searchterm,0,1) == "-") {
789 $searchterm = trim($searchterm, '+-');
790 $searchterm = preg_quote($searchterm, '|');
791 $searchcond[] = "$concat $NOTREGEXP :ss$i";
792 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
795 $searchcond[] = $DB->sql_like($concat,":ss$i", false, true, $NOT);
796 $params['ss'.$i] = "%$searchterm%";
800 if (empty($searchcond)) {
805 $searchcond = implode(" AND ", $searchcond);
808 $c = 0; // counts how many visible courses we've seen
811 $limitfrom = $page * $recordsperpage;
812 $limitto = $limitfrom +
$recordsperpage;
814 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
815 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
816 $params['contextlevel'] = CONTEXT_COURSE
;
818 $sql = "SELECT c.* $ccselect
821 WHERE $searchcond AND c.id <> ".SITEID
."
824 $rs = $DB->get_recordset_sql($sql, $params);
825 foreach($rs as $course) {
826 if (!$course->visible
) {
827 // preload contexts only for hidden courses or courses we need to return
828 context_helper
::preload_from_record($course);
829 $coursecontext = context_course
::instance($course->id
);
830 if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
834 // Don't exit this loop till the end
835 // we need to count all the visible courses
836 // to update $totalcount
837 if ($c >= $limitfrom && $c < $limitto) {
838 $courses[$course->id
] = $course;
844 // our caller expects 2 bits of data - our return
845 // array, and an updated $totalcount
851 * Fixes course category and course sortorder, also verifies category and course parents and paths.
852 * (circular references are not fixed)
856 * @uses MAX_COURSES_IN_CATEGORY
857 * @uses MAX_COURSE_CATEGORIES
859 * @uses CONTEXT_COURSE
862 function fix_course_sortorder() {
865 //WARNING: this is PHP5 only code!
867 // if there are any changes made to courses or categories we will trigger
868 // the cache events to purge all cached courses/categories data
869 $cacheevents = array();
871 if ($unsorted = $DB->get_records('course_categories', array('sortorder'=>0))) {
872 //move all categories that are not sorted yet to the end
873 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY
*MAX_COURSE_CATEGORIES
, array('sortorder'=>0));
874 $cacheevents['changesincoursecat'] = true;
877 $allcats = $DB->get_records('course_categories', null, 'sortorder, id', 'id, sortorder, parent, depth, path');
879 $brokencats = array();
880 foreach ($allcats as $cat) {
881 $sortorder = (int)$cat->sortorder
;
883 while(isset($topcats[$sortorder])) {
886 $topcats[$sortorder] = $cat;
889 if (!isset($allcats[$cat->parent
])) {
890 $brokencats[] = $cat;
893 if (!isset($allcats[$cat->parent
]->children
)) {
894 $allcats[$cat->parent
]->children
= array();
896 while(isset($allcats[$cat->parent
]->children
[$sortorder])) {
899 $allcats[$cat->parent
]->children
[$sortorder] = $cat;
903 // add broken cats to category tree
905 $defaultcat = reset($topcats);
906 foreach ($brokencats as $cat) {
911 // now walk recursively the tree and fix any problems found
913 $fixcontexts = array();
914 if (_fix_course_cats($topcats, $sortorder, 0, 0, '', $fixcontexts)) {
915 $cacheevents['changesincoursecat'] = true;
918 // detect if there are "multiple" frontpage courses and fix them if needed
919 $frontcourses = $DB->get_records('course', array('category'=>0), 'id');
920 if (count($frontcourses) > 1) {
921 if (isset($frontcourses[SITEID
])) {
922 $frontcourse = $frontcourses[SITEID
];
923 unset($frontcourses[SITEID
]);
925 $frontcourse = array_shift($frontcourses);
927 $defaultcat = reset($topcats);
928 foreach ($frontcourses as $course) {
929 $DB->set_field('course', 'category', $defaultcat->id
, array('id'=>$course->id
));
930 $context = context_course
::instance($course->id
);
931 $fixcontexts[$context->id
] = $context;
932 $cacheevents['changesincourse'] = true;
934 unset($frontcourses);
936 $frontcourse = reset($frontcourses);
939 // now fix the paths and depths in context table if needed
941 foreach ($fixcontexts as $fixcontext) {
942 $fixcontext->reset_paths(false);
944 context_helper
::build_all_paths(false);
946 $cacheevents['changesincourse'] = true;
947 $cacheevents['changesincoursecat'] = true;
955 // fix frontpage course sortorder
956 if ($frontcourse->sortorder
!= 1) {
957 $DB->set_field('course', 'sortorder', 1, array('id'=>$frontcourse->id
));
958 $cacheevents['changesincourse'] = true;
961 // now fix the course counts in category records if needed
962 $sql = "SELECT cc.id, cc.coursecount, COUNT(c.id) AS newcount
963 FROM {course_categories} cc
964 LEFT JOIN {course} c ON c.category = cc.id
965 GROUP BY cc.id, cc.coursecount
966 HAVING cc.coursecount <> COUNT(c.id)";
968 if ($updatecounts = $DB->get_records_sql($sql)) {
969 // categories with more courses than MAX_COURSES_IN_CATEGORY
970 $categories = array();
971 foreach ($updatecounts as $cat) {
972 $cat->coursecount
= $cat->newcount
;
973 if ($cat->coursecount
>= MAX_COURSES_IN_CATEGORY
) {
974 $categories[] = $cat->id
;
976 unset($cat->newcount
);
977 $DB->update_record_raw('course_categories', $cat, true);
979 if (!empty($categories)) {
980 $str = implode(', ', $categories);
981 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
);
983 $cacheevents['changesincoursecat'] = true;
986 // now make sure that sortorders in course table are withing the category sortorder ranges
987 $sql = "SELECT DISTINCT cc.id, cc.sortorder
988 FROM {course_categories} cc
989 JOIN {course} c ON c.category = cc.id
990 WHERE c.sortorder < cc.sortorder OR c.sortorder > cc.sortorder + ".MAX_COURSES_IN_CATEGORY
;
992 if ($fixcategories = $DB->get_records_sql($sql)) {
993 //fix the course sortorder ranges
994 foreach ($fixcategories as $cat) {
995 $sql = "UPDATE {course}
996 SET sortorder = ".$DB->sql_modulo('sortorder', MAX_COURSES_IN_CATEGORY
)." + ?
998 $DB->execute($sql, array($cat->sortorder
, $cat->id
));
1000 $cacheevents['changesincoursecat'] = true;
1002 unset($fixcategories);
1004 // categories having courses with sortorder duplicates or having gaps in sortorder
1005 $sql = "SELECT DISTINCT c1.category AS id , cc.sortorder
1007 JOIN {course} c2 ON c1.sortorder = c2.sortorder
1008 JOIN {course_categories} cc ON (c1.category = cc.id)
1009 WHERE c1.id <> c2.id";
1010 $fixcategories = $DB->get_records_sql($sql);
1012 $sql = "SELECT cc.id, cc.sortorder, cc.coursecount, MAX(c.sortorder) AS maxsort, MIN(c.sortorder) AS minsort
1013 FROM {course_categories} cc
1014 JOIN {course} c ON c.category = cc.id
1015 GROUP BY cc.id, cc.sortorder, cc.coursecount
1016 HAVING (MAX(c.sortorder) <> cc.sortorder + cc.coursecount) OR (MIN(c.sortorder) <> cc.sortorder + 1)";
1017 $gapcategories = $DB->get_records_sql($sql);
1019 foreach ($gapcategories as $cat) {
1020 if (isset($fixcategories[$cat->id
])) {
1021 // duplicates detected already
1023 } else if ($cat->minsort
== $cat->sortorder
and $cat->maxsort
== $cat->sortorder +
$cat->coursecount
- 1) {
1024 // easy - new course inserted with sortorder 0, the rest is ok
1025 $sql = "UPDATE {course}
1026 SET sortorder = sortorder + 1
1027 WHERE category = ?";
1028 $DB->execute($sql, array($cat->id
));
1031 // it needs full resorting
1032 $fixcategories[$cat->id
] = $cat;
1034 $cacheevents['changesincourse'] = true;
1036 unset($gapcategories);
1038 // fix course sortorders in problematic categories only
1039 foreach ($fixcategories as $cat) {
1041 $courses = $DB->get_records('course', array('category'=>$cat->id
), 'sortorder ASC, id DESC', 'id, sortorder');
1042 foreach ($courses as $course) {
1043 if ($course->sortorder
!= $cat->sortorder +
$i) {
1044 $course->sortorder
= $cat->sortorder +
$i;
1045 $DB->update_record_raw('course', $course, true);
1046 $cacheevents['changesincourse'] = true;
1052 // advise all caches that need to be rebuilt
1053 foreach (array_keys($cacheevents) as $event) {
1054 cache_helper
::purge_by_event($event);
1059 * Internal recursive category verification function, do not use directly!
1061 * @todo Document the arguments of this function better
1064 * @uses MAX_COURSES_IN_CATEGORY
1065 * @uses CONTEXT_COURSECAT
1066 * @param array $children
1067 * @param int $sortorder
1068 * @param string $parent
1070 * @param string $path
1071 * @param array $fixcontexts
1072 * @return bool if changes were made
1074 function _fix_course_cats($children, &$sortorder, $parent, $depth, $path, &$fixcontexts) {
1078 $changesmade = false;
1080 foreach ($children as $cat) {
1081 $sortorder = $sortorder + MAX_COURSES_IN_CATEGORY
;
1083 if ($parent != $cat->parent
or $depth != $cat->depth
or $path.'/'.$cat->id
!= $cat->path
) {
1084 $cat->parent
= $parent;
1085 $cat->depth
= $depth;
1086 $cat->path
= $path.'/'.$cat->id
;
1089 // make sure context caches are rebuild and dirty contexts marked
1090 $context = context_coursecat
::instance($cat->id
);
1091 $fixcontexts[$context->id
] = $context;
1093 if ($cat->sortorder
!= $sortorder) {
1094 $cat->sortorder
= $sortorder;
1098 $DB->update_record('course_categories', $cat, true);
1099 $changesmade = true;
1101 if (isset($cat->children
)) {
1102 if (_fix_course_cats($cat->children
, $sortorder, $cat->id
, $cat->depth
, $cat->path
, $fixcontexts)) {
1103 $changesmade = true;
1107 return $changesmade;
1111 * List of remote courses that a user has access to via MNET.
1112 * Works only on the IDP
1116 * @param int @userid The user id to get remote courses for
1117 * @return array Array of {@link $COURSE} of course objects
1119 function get_my_remotecourses($userid=0) {
1122 if (empty($userid)) {
1123 $userid = $USER->id
;
1126 // we can not use SELECT DISTINCT + text field (summary) because of MS SQL and Oracle, subselect used therefore
1127 $sql = "SELECT c.id, c.remoteid, c.shortname, c.fullname,
1128 c.hostid, c.summary, c.summaryformat, c.categoryname AS cat_name,
1130 FROM {mnetservice_enrol_courses} c
1131 JOIN (SELECT DISTINCT hostid, remotecourseid
1132 FROM {mnetservice_enrol_enrolments}
1134 ) e ON (e.hostid = c.hostid AND e.remotecourseid = c.remoteid)
1135 JOIN {mnet_host} h ON h.id = c.hostid";
1137 return $DB->get_records_sql($sql, array($userid));
1141 * List of remote hosts that a user has access to via MNET.
1146 * @return array|bool Array of host objects or false
1148 function get_my_remotehosts() {
1151 if ($USER->mnethostid
== $CFG->mnet_localhost_id
) {
1152 return false; // Return nothing on the IDP
1154 if (!empty($USER->mnet_foreign_host_array
) && is_array($USER->mnet_foreign_host_array
)) {
1155 return $USER->mnet_foreign_host_array
;
1161 * This function creates a default separated/connected scale
1163 * This function creates a default separated/connected scale
1164 * so there's something in the database. The locations of
1165 * strings and files is a bit odd, but this is because we
1166 * need to maintain backward compatibility with many different
1167 * existing language translations and older sites.
1172 function make_default_scale() {
1175 $defaultscale = new stdClass();
1176 $defaultscale->courseid
= 0;
1177 $defaultscale->userid
= 0;
1178 $defaultscale->name
= get_string('separateandconnected');
1179 $defaultscale->description
= get_string('separateandconnectedinfo');
1180 $defaultscale->scale
= get_string('postrating1', 'forum').','.
1181 get_string('postrating2', 'forum').','.
1182 get_string('postrating3', 'forum');
1183 $defaultscale->timemodified
= time();
1185 $defaultscale->id
= $DB->insert_record('scale', $defaultscale);
1186 $DB->execute("UPDATE {forum} SET scale = ?", array($defaultscale->id
));
1191 * Returns a menu of all available scales from the site as well as the given course
1194 * @param int $courseid The id of the course as found in the 'course' table.
1197 function get_scales_menu($courseid=0) {
1200 $sql = "SELECT id, name
1202 WHERE courseid = 0 or courseid = ?
1203 ORDER BY courseid ASC, name ASC";
1204 $params = array($courseid);
1206 if ($scales = $DB->get_records_sql_menu($sql, $params)) {
1210 make_default_scale();
1212 return $DB->get_records_sql_menu($sql, $params);
1218 * Given a set of timezone records, put them in the database, replacing what is there
1221 * @param array $timezones An array of timezone records
1224 function update_timezone_records($timezones) {
1227 /// Clear out all the old stuff
1228 $DB->delete_records('timezone');
1230 /// Insert all the new stuff
1231 foreach ($timezones as $timezone) {
1232 if (is_array($timezone)) {
1233 $timezone = (object)$timezone;
1235 $DB->insert_record('timezone', $timezone);
1240 * Increment standard revision field.
1242 * The revision are based on current time and are incrementing.
1243 * There is a protection for runaway revisions, it may not go further than
1244 * one hour into future.
1246 * The field has to be XMLDB_TYPE_INTEGER with size 10.
1248 * @param string $table
1249 * @param string $field name of the field containing revision
1250 * @param string $select use empty string when updating all records
1251 * @param array $params optional select parameters
1253 function increment_revision_number($table, $field, $select, array $params = null) {
1257 $sql = "UPDATE {{$table}}
1259 WHEN $field IS NULL THEN $now
1260 WHEN $field < $now THEN $now
1261 WHEN $field > $now + 3600 THEN $now
1262 ELSE $field + 1 END)";
1264 $sql = $sql . " WHERE $select";
1266 $DB->execute($sql, $params);
1270 /// MODULE FUNCTIONS /////////////////////////////////////////////////
1273 * Just gets a raw list of all modules in a course
1276 * @param int $courseid The id of the course as found in the 'course' table.
1279 function get_course_mods($courseid) {
1282 if (empty($courseid)) {
1283 return false; // avoid warnings
1286 return $DB->get_records_sql("SELECT cm.*, m.name as modname
1287 FROM {modules} m, {course_modules} cm
1288 WHERE cm.course = ? AND cm.module = m.id AND m.visible = 1",
1289 array($courseid)); // no disabled mods
1294 * Given an id of a course module, finds the coursemodule description
1297 * @param string $modulename name of module type, eg. resource, assignment,... (optional, slower and less safe if not specified)
1298 * @param int $cmid course module id (id in course_modules table)
1299 * @param int $courseid optional course id for extra validation
1300 * @param bool $sectionnum include relative section number (0,1,2 ...)
1301 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1302 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1303 * MUST_EXIST means throw exception if no record or multiple records found
1306 function get_coursemodule_from_id($modulename, $cmid, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING
) {
1309 $params = array('cmid'=>$cmid);
1312 if (!$modulename = $DB->get_field_sql("SELECT md.name
1314 JOIN {course_modules} cm ON cm.module = md.id
1315 WHERE cm.id = :cmid", $params, $strictness)) {
1320 $params['modulename'] = $modulename;
1327 $courseselect = "AND cm.course = :courseid";
1328 $params['courseid'] = $courseid;
1332 $sectionfield = ", cw.section AS sectionnum";
1333 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1336 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1337 FROM {course_modules} cm
1338 JOIN {modules} md ON md.id = cm.module
1339 JOIN {".$modulename."} m ON m.id = cm.instance
1341 WHERE cm.id = :cmid AND md.name = :modulename
1344 return $DB->get_record_sql($sql, $params, $strictness);
1348 * Given an instance number of a module, finds the coursemodule description
1351 * @param string $modulename name of module type, eg. resource, assignment,...
1352 * @param int $instance module instance number (id in resource, assignment etc. table)
1353 * @param int $courseid optional course id for extra validation
1354 * @param bool $sectionnum include relative section number (0,1,2 ...)
1355 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1356 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1357 * MUST_EXIST means throw exception if no record or multiple records found
1360 function get_coursemodule_from_instance($modulename, $instance, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING
) {
1363 $params = array('instance'=>$instance, 'modulename'=>$modulename);
1370 $courseselect = "AND cm.course = :courseid";
1371 $params['courseid'] = $courseid;
1375 $sectionfield = ", cw.section AS sectionnum";
1376 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1379 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1380 FROM {course_modules} cm
1381 JOIN {modules} md ON md.id = cm.module
1382 JOIN {".$modulename."} m ON m.id = cm.instance
1384 WHERE m.id = :instance AND md.name = :modulename
1387 return $DB->get_record_sql($sql, $params, $strictness);
1391 * Returns all course modules of given activity in course
1393 * @param string $modulename The module name (forum, quiz, etc.)
1394 * @param int $courseid The course id to get modules for
1395 * @param string $extrafields extra fields starting with m.
1396 * @return array Array of results
1398 function get_coursemodules_in_course($modulename, $courseid, $extrafields='') {
1401 if (!empty($extrafields)) {
1402 $extrafields = ", $extrafields";
1405 $params['courseid'] = $courseid;
1406 $params['modulename'] = $modulename;
1409 return $DB->get_records_sql("SELECT cm.*, m.name, md.name as modname $extrafields
1410 FROM {course_modules} cm, {modules} md, {".$modulename."} m
1411 WHERE cm.course = :courseid AND
1412 cm.instance = m.id AND
1413 md.name = :modulename AND
1414 md.id = cm.module", $params);
1418 * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1420 * Returns an array of all the active instances of a particular
1421 * module in given courses, sorted in the order they are defined
1422 * in the course. Returns an empty array on any errors.
1424 * The returned objects includle the columns cw.section, cm.visible,
1425 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1429 * @param string $modulename The name of the module to get instances for
1430 * @param array $courses an array of course objects.
1431 * @param int $userid
1432 * @param int $includeinvisible
1433 * @return array of module instance objects, including some extra fields from the course_modules
1434 * and course_sections tables, or an empty array if an error occurred.
1436 function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
1439 $outputarray = array();
1441 if (empty($courses) ||
!is_array($courses) ||
count($courses) == 0) {
1442 return $outputarray;
1445 list($coursessql, $params) = $DB->get_in_or_equal(array_keys($courses), SQL_PARAMS_NAMED
, 'c0');
1446 $params['modulename'] = $modulename;
1448 if (!$rawmods = $DB->get_records_sql("SELECT cm.id AS coursemodule, m.*, cw.section, cm.visible AS visible,
1449 cm.groupmode, cm.groupingid, cm.groupmembersonly
1450 FROM {course_modules} cm, {course_sections} cw, {modules} md,
1452 WHERE cm.course $coursessql AND
1453 cm.instance = m.id AND
1454 cm.section = cw.id AND
1455 md.name = :modulename AND
1456 md.id = cm.module", $params)) {
1457 return $outputarray;
1460 foreach ($courses as $course) {
1461 $modinfo = get_fast_modinfo($course, $userid);
1463 if (empty($modinfo->instances
[$modulename])) {
1467 foreach ($modinfo->instances
[$modulename] as $cm) {
1468 if (!$includeinvisible and !$cm->uservisible
) {
1471 if (!isset($rawmods[$cm->id
])) {
1474 $instance = $rawmods[$cm->id
];
1475 if (!empty($cm->extra
)) {
1476 $instance->extra
= $cm->extra
;
1478 $outputarray[] = $instance;
1482 return $outputarray;
1486 * Returns an array of all the active instances of a particular module in a given course,
1487 * sorted in the order they are defined.
1489 * Returns an array of all the active instances of a particular
1490 * module in a given course, sorted in the order they are defined
1491 * in the course. Returns an empty array on any errors.
1493 * The returned objects includle the columns cw.section, cm.visible,
1494 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1496 * Simply calls {@link all_instances_in_courses()} with a single provided course
1498 * @param string $modulename The name of the module to get instances for
1499 * @param object $course The course obect.
1500 * @return array of module instance objects, including some extra fields from the course_modules
1501 * and course_sections tables, or an empty array if an error occurred.
1502 * @param int $userid
1503 * @param int $includeinvisible
1505 function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
1506 return get_all_instances_in_courses($modulename, array($course->id
=> $course), $userid, $includeinvisible);
1511 * Determine whether a module instance is visible within a course
1513 * Given a valid module object with info about the id and course,
1514 * and the module's type (eg "forum") returns whether the object
1515 * is visible or not, groupmembersonly visibility not tested
1519 * @param $moduletype Name of the module eg 'forum'
1520 * @param $module Object which is the instance of the module
1521 * @return bool Success
1523 function instance_is_visible($moduletype, $module) {
1526 if (!empty($module->id
)) {
1527 $params = array('courseid'=>$module->course
, 'moduletype'=>$moduletype, 'moduleid'=>$module->id
);
1528 if ($records = $DB->get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.groupmembersonly, cm.course
1529 FROM {course_modules} cm, {modules} m
1530 WHERE cm.course = :courseid AND
1531 cm.module = m.id AND
1532 m.name = :moduletype AND
1533 cm.instance = :moduleid", $params)) {
1535 foreach ($records as $record) { // there should only be one - use the first one
1536 return $record->visible
;
1540 return true; // visible by default!
1544 * Determine whether a course module is visible within a course,
1545 * this is different from instance_is_visible() - faster and visibility for user
1549 * @uses DEBUG_DEVELOPER
1550 * @uses CONTEXT_MODULE
1551 * @uses CONDITION_MISSING_EXTRATABLE
1552 * @param object $cm object
1553 * @param int $userid empty means current user
1554 * @return bool Success
1556 function coursemodule_visible_for_user($cm, $userid=0) {
1559 if (empty($cm->id
)) {
1560 debugging("Incorrect course module parameter!", DEBUG_DEVELOPER
);
1563 if (empty($userid)) {
1564 $userid = $USER->id
;
1566 if (!$cm->visible
and !has_capability('moodle/course:viewhiddenactivities', context_module
::instance($cm->id
), $userid)) {
1569 if ($CFG->enableavailability
) {
1570 require_once($CFG->libdir
.'/conditionlib.php');
1571 $ci=new condition_info($cm,CONDITION_MISSING_EXTRATABLE
);
1572 if(!$ci->is_available($cm->availableinfo
,false,$userid) and
1573 !has_capability('moodle/course:viewhiddenactivities',
1574 context_module
::instance($cm->id
), $userid)) {
1578 return groups_course_module_visible($cm, $userid);
1584 /// LOG FUNCTIONS /////////////////////////////////////////////////////
1587 * Add an entry to the config log table.
1589 * These are "action" focussed rather than web server hits,
1590 * and provide a way to easily reconstruct changes to Moodle configuration.
1594 * @global moodle_database $DB
1595 * @global stdClass $USER
1596 * @param string $name The name of the configuration change action
1597 For example 'filter_active' when activating or deactivating a filter
1598 * @param string $oldvalue The config setting's previous value
1599 * @param string $value The config setting's new value
1600 * @param string $plugin Plugin name, for example a filter name when changing filter configuration
1603 function add_to_config_log($name, $oldvalue, $value, $plugin) {
1606 $log = new stdClass();
1607 $log->userid
= during_initial_install() ?
0 :$USER->id
; // 0 as user id during install
1608 $log->timemodified
= time();
1610 $log->oldvalue
= $oldvalue;
1611 $log->value
= $value;
1612 $log->plugin
= $plugin;
1613 $DB->insert_record('config_log', $log);
1617 * Add an entry to the log table.
1619 * Add an entry to the log table. These are "action" focussed rather
1620 * than web server hits, and provide a way to easily reconstruct what
1621 * any particular student has been doing.
1625 * @global moodle_database $DB
1626 * @global stdClass $CFG
1627 * @global stdClass $USER
1629 * @uses DEBUG_DEVELOPER
1631 * @param int $courseid The course id
1632 * @param string $module The module name e.g. forum, journal, resource, course, user etc
1633 * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
1634 * @param string $url The file and parameters used to see the results of the action
1635 * @param string $info Additional description information
1636 * @param string $cm The course_module->id if there is one
1637 * @param string $user If log regards $user other than $USER
1640 function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
1641 // Note that this function intentionally does not follow the normal Moodle DB access idioms.
1642 // This is for a good reason: it is the most frequently used DB update function,
1643 // so it has been optimised for speed.
1644 global $DB, $CFG, $USER;
1646 if ($cm === '' ||
is_null($cm)) { // postgres won't translate empty string to its default
1653 if (\core\session\manager
::is_loggedinas()) { // Don't log
1656 $userid = empty($USER->id
) ?
'0' : $USER->id
;
1659 if (isset($CFG->logguests
) and !$CFG->logguests
) {
1660 if (!$userid or isguestuser($userid)) {
1665 $REMOTE_ADDR = getremoteaddr();
1669 if (!empty($url)) { // could break doing html_entity_decode on an empty var.
1670 $url = html_entity_decode($url, ENT_QUOTES
, 'UTF-8');
1675 // Restrict length of log lines to the space actually available in the
1676 // database so that it doesn't cause a DB error. Log a warning so that
1677 // developers can avoid doing things which are likely to cause this on a
1679 if (core_text
::strlen($action) > 40) {
1680 $action = core_text
::substr($action, 0, 37) . '...';
1681 debugging('Warning: logged very long action', DEBUG_DEVELOPER
);
1684 if(!empty($info) && core_text
::strlen($info)>255) {
1685 $info = core_text
::substr($info,0,252).'...';
1686 debugging('Warning: logged very long info',DEBUG_DEVELOPER
);
1689 // If the 100 field size is changed, also need to alter print_log in course/lib.php
1690 if(!empty($url) && core_text
::strlen($url)>100) {
1691 $url = core_text
::substr($url,0,97).'...';
1692 debugging('Warning: logged very long URL',DEBUG_DEVELOPER
);
1695 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->logwrites++
;};
1697 $log = array('time'=>$timenow, 'userid'=>$userid, 'course'=>$courseid, 'ip'=>$REMOTE_ADDR, 'module'=>$module,
1698 'cmid'=>$cm, 'action'=>$action, 'url'=>$url, 'info'=>$info);
1701 $DB->insert_record_raw('log', $log, false);
1702 } catch (dml_exception
$e) {
1703 debugging('Error: Could not insert a new entry to the Moodle log. '. $e->error
, DEBUG_ALL
);
1705 // MDL-11893, alert $CFG->supportemail if insert into log failed
1706 if ($CFG->supportemail
and empty($CFG->noemailever
)) {
1707 // email_to_user is not usable because email_to_user tries to write to the logs table,
1708 // and this will get caught in an infinite loop, if disk is full
1710 $subject = 'Insert into log failed at your moodle site '.$site->fullname
;
1711 $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";
1712 $message .= "The failed query parameters are:\n\n" . var_export($log, true);
1714 $lasttime = get_config('admin', 'lastloginserterrormail');
1715 if(empty($lasttime) ||
time() - $lasttime > 60*60*24) { // limit to 1 email per day
1716 //using email directly rather than messaging as they may not be able to log in to access a message
1717 mail($CFG->supportemail
, $subject, $message);
1718 set_config('lastloginserterrormail', time(), 'admin');
1725 * Store user last access times - called when use enters a course or site
1729 * @global stdClass $USER
1730 * @global stdClass $CFG
1731 * @global moodle_database $DB
1732 * @uses LASTACCESS_UPDATE_SECS
1734 * @param int $courseid empty courseid means site
1737 function user_accesstime_log($courseid=0) {
1738 global $USER, $CFG, $DB;
1740 if (!isloggedin() or \core\session\manager
::is_loggedinas()) {
1741 // no access tracking
1745 if (isguestuser()) {
1746 // Do not update guest access times/ips for performance.
1750 if (empty($courseid)) {
1756 /// Store site lastaccess time for the current user
1757 if ($timenow - $USER->lastaccess
> LASTACCESS_UPDATE_SECS
) {
1758 /// Update $USER->lastaccess for next checks
1759 $USER->lastaccess
= $timenow;
1761 $last = new stdClass();
1762 $last->id
= $USER->id
;
1763 $last->lastip
= getremoteaddr();
1764 $last->lastaccess
= $timenow;
1766 $DB->update_record_raw('user', $last);
1769 if ($courseid == SITEID
) {
1770 /// no user_lastaccess for frontpage
1774 /// Store course lastaccess times for the current user
1775 if (empty($USER->currentcourseaccess
[$courseid]) or ($timenow - $USER->currentcourseaccess
[$courseid] > LASTACCESS_UPDATE_SECS
)) {
1777 $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid'=>$USER->id
, 'courseid'=>$courseid));
1779 if ($lastaccess === false) {
1780 // Update course lastaccess for next checks
1781 $USER->currentcourseaccess
[$courseid] = $timenow;
1783 $last = new stdClass();
1784 $last->userid
= $USER->id
;
1785 $last->courseid
= $courseid;
1786 $last->timeaccess
= $timenow;
1787 $DB->insert_record_raw('user_lastaccess', $last, false);
1789 } else if ($timenow - $lastaccess < LASTACCESS_UPDATE_SECS
) {
1790 // no need to update now, it was updated recently in concurrent login ;-)
1793 // Update course lastaccess for next checks
1794 $USER->currentcourseaccess
[$courseid] = $timenow;
1796 $DB->set_field('user_lastaccess', 'timeaccess', $timenow, array('userid'=>$USER->id
, 'courseid'=>$courseid));
1802 * Select all log records based on SQL criteria
1806 * @global moodle_database $DB
1807 * @param string $select SQL select criteria
1808 * @param array $params named sql type params
1809 * @param string $order SQL order by clause to sort the records returned
1810 * @param string $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
1811 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set)
1812 * @param int $totalcount Passed in by reference.
1815 function get_logs($select, array $params=null, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
1819 $order = "ORDER BY $order";
1826 $select = "WHERE $select";
1829 $sql = "SELECT COUNT(*)
1833 $totalcount = $DB->count_records_sql($sql, $params);
1834 $allnames = get_all_user_name_fields(true, 'u');
1835 $sql = "SELECT l.*, $allnames, u.picture
1837 LEFT JOIN {user} u ON l.userid = u.id
1841 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum) ;
1846 * Select all log records for a given course and user
1850 * @global moodle_database $DB
1852 * @param int $userid The id of the user as found in the 'user' table.
1853 * @param int $courseid The id of the course as found in the 'course' table.
1854 * @param string $coursestart unix timestamp representing course start date and time.
1857 function get_logs_usercourse($userid, $courseid, $coursestart) {
1864 $courseselect = "AND course = :courseid";
1865 $params['courseid'] = $courseid;
1867 $params['userid'] = $userid;
1868 $
$coursestart = (int)$coursestart; // note: unfortunately pg complains if you use name parameter or column alias in GROUP BY
1870 return $DB->get_records_sql("SELECT FLOOR((time - $coursestart)/". DAYSECS
.") AS day, COUNT(*) AS num
1872 WHERE userid = :userid
1873 AND time > $coursestart $courseselect
1874 GROUP BY FLOOR((time - $coursestart)/". DAYSECS
.")", $params);
1878 * Select all log records for a given course, user, and day
1882 * @global moodle_database $DB
1884 * @param int $userid The id of the user as found in the 'user' table.
1885 * @param int $courseid The id of the course as found in the 'course' table.
1886 * @param string $daystart unix timestamp of the start of the day for which the logs needs to be retrived
1889 function get_logs_userday($userid, $courseid, $daystart) {
1892 $params = array('userid'=>$userid);
1896 $courseselect = "AND course = :courseid";
1897 $params['courseid'] = $courseid;
1899 $daystart = (int)$daystart; // note: unfortunately pg complains if you use name parameter or column alias in GROUP BY
1901 return $DB->get_records_sql("SELECT FLOOR((time - $daystart)/". HOURSECS
.") AS hour, COUNT(*) AS num
1903 WHERE userid = :userid
1904 AND time > $daystart $courseselect
1905 GROUP BY FLOOR((time - $daystart)/". HOURSECS
.") ", $params);
1909 * Returns an object with counts of failed login attempts
1911 * Returns information about failed login attempts. If the current user is
1912 * an admin, then two numbers are returned: the number of attempts and the
1913 * number of accounts. For non-admins, only the attempts on the given user
1916 * @global moodle_database $DB
1917 * @uses CONTEXT_SYSTEM
1918 * @param string $mode Either 'admin' or 'everybody'
1919 * @param string $username The username we are searching for
1920 * @param string $lastlogin The date from which we are searching
1923 function count_login_failures($mode, $username, $lastlogin) {
1926 $params = array('mode'=>$mode, 'username'=>$username, 'lastlogin'=>$lastlogin);
1927 $select = "module='login' AND action='error' AND time > :lastlogin";
1929 $count = new stdClass();
1931 if (is_siteadmin()) {
1932 if ($count->attempts
= $DB->count_records_select('log', $select, $params)) {
1933 $count->accounts
= $DB->count_records_select('log', $select, $params, 'COUNT(DISTINCT info)');
1936 } else if ($mode == 'everybody') {
1937 if ($count->attempts
= $DB->count_records_select('log', "$select AND info = :username", $params)) {
1945 /// GENERAL HELPFUL THINGS ///////////////////////////////////
1948 * Dumps a given object's information for debugging purposes
1950 * When used in a CLI script, the object's information is written to the standard
1951 * error output stream. When used in a web script, the object is dumped to a
1952 * pre-formatted block with the "notifytiny" CSS class.
1954 * @param mixed $object The data to be printed
1955 * @return void output is echo'd
1957 function print_object($object) {
1959 // we may need a lot of memory here
1960 raise_memory_limit(MEMORY_EXTRA
);
1963 fwrite(STDERR
, print_r($object, true));
1964 fwrite(STDERR
, PHP_EOL
);
1966 echo html_writer
::tag('pre', s(print_r($object, true)), array('class' => 'notifytiny'));
1971 * This function is the official hook inside XMLDB stuff to delegate its debug to one
1972 * external function.
1974 * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
1975 * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
1977 * @uses DEBUG_DEVELOPER
1978 * @param string $message string contains the error message
1979 * @param object $object object XMLDB object that fired the debug
1981 function xmldb_debug($message, $object) {
1983 debugging($message, DEBUG_DEVELOPER
);
1988 * @uses CONTEXT_COURSECAT
1989 * @return boolean Whether the user can create courses in any category in the system.
1991 function user_can_create_courses() {
1993 $catsrs = $DB->get_recordset('course_categories');
1994 foreach ($catsrs as $cat) {
1995 if (has_capability('moodle/course:create', context_coursecat
::instance($cat->id
))) {