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 define('LASTACCESS_UPDATE_SECS', 60);
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() {
57 static $mainadmin = null;
59 if (isset($mainadmin)) {
60 return clone($mainadmin);
63 if (empty($CFG->siteadmins
)) { // Should not happen on an ordinary site
67 foreach (explode(',', $CFG->siteadmins
) as $id) {
68 if ($user = $DB->get_record('user', array('id'=>$id, 'deleted'=>0))) {
75 return clone($mainadmin);
77 // this should not happen
83 * Returns list of all admins, using 1 DB query
87 function get_admins() {
90 if (empty($CFG->siteadmins
)) { // Should not happen on an ordinary site
96 WHERE u.deleted = 0 AND u.id IN ($CFG->siteadmins)";
98 return $DB->get_records_sql($sql);
102 * Search through course users
104 * If $coursid specifies the site course then this function searches
105 * through all undeleted and confirmed users
109 * @uses SQL_PARAMS_NAMED
110 * @uses CONTEXT_COURSE
111 * @param int $courseid The course in question.
112 * @param int $groupid The group in question.
113 * @param string $searchtext The string to search for
114 * @param string $sort A field to sort by
115 * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
118 function search_users($courseid, $groupid, $searchtext, $sort='', array $exceptions=null) {
121 $fullname = $DB->sql_fullname('u.firstname', 'u.lastname');
123 if (!empty($exceptions)) {
124 list($exceptions, $params) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED
, 'ex', false);
125 $except = "AND u.id $exceptions";
132 $order = "ORDER BY $sort";
137 $select = "u.deleted = 0 AND u.confirmed = 1 AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('u.email', ':search2', false).")";
138 $params['search1'] = "%$searchtext%";
139 $params['search2'] = "%$searchtext%";
141 if (!$courseid or $courseid == SITEID
) {
142 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
147 return $DB->get_records_sql($sql, $params);
151 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
153 JOIN {groups_members} gm ON gm.userid = u.id
154 WHERE $select AND gm.groupid = :groupid
157 $params['groupid'] = $groupid;
158 return $DB->get_records_sql($sql, $params);
161 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
162 $contextlists = get_related_contexts_string($context);
164 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
166 JOIN {role_assignments} ra ON ra.userid = u.id
167 WHERE $select AND ra.contextid $contextlists
170 return $DB->get_records_sql($sql, $params);
176 * Returns a subset of users
179 * @uses DEBUG_DEVELOPER
180 * @uses SQL_PARAMS_NAMED
181 * @param bool $get If false then only a count of the records is returned
182 * @param string $search A simple string to search for
183 * @param bool $confirmed A switch to allow/disallow unconfirmed users
184 * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
185 * @param string $sort A SQL snippet for the sorting criteria to use
186 * @param string $firstinitial Users whose first name starts with $firstinitial
187 * @param string $lastinitial Users whose last name starts with $lastinitial
188 * @param string $page The page or records to return
189 * @param string $recordsperpage The number of records to return per page
190 * @param string $fields A comma separated list of fields to be returned from the chosen table.
191 * @return array|int|bool {@link $USER} records unless get is false in which case the integer count of the records found is returned.
192 * False is returned if an error is encountered.
194 function get_users($get=true, $search='', $confirmed=false, array $exceptions=null, $sort='firstname ASC',
195 $firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields='*', $extraselect='', array $extraparams=null) {
198 if ($get && !$recordsperpage) {
199 debugging('Call to get_users with $get = true no $recordsperpage limit. ' .
200 'On large installations, this will probably cause an out of memory error. ' .
201 'Please think again and change your code so that it does not try to ' .
202 'load so much data into memory.', DEBUG_DEVELOPER
);
205 $fullname = $DB->sql_fullname();
207 $select = " id <> :guestid AND deleted = 0";
208 $params = array('guestid'=>$CFG->siteguest
);
210 if (!empty($search)){
211 $search = trim($search);
212 $select .= " AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('email', ':search2', false)." OR username = :search3)";
213 $params['search1'] = "%$search%";
214 $params['search2'] = "%$search%";
215 $params['search3'] = "$search";
219 $select .= " AND confirmed = 1";
223 list($exceptions, $eparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED
, 'ex', false);
224 $params = $params +
$eparams;
225 $select .= " AND id $exceptions";
229 $select .= " AND ".$DB->sql_like('firstname', ':fni', false, false);
230 $params['fni'] = "$firstinitial%";
233 $select .= " AND ".$DB->sql_like('lastname', ':lni', false, false);
234 $params['lni'] = "$lastinitial%";
238 $select .= " AND $extraselect";
239 $params = $params +
(array)$extraparams;
243 return $DB->get_records_select('user', $select, $params, $sort, $fields, $page, $recordsperpage);
245 return $DB->count_records_select('user', $select, $params);
251 * @todo Finish documenting this function
253 * @param string $sort An SQL field to sort by
254 * @param string $dir The sort direction ASC|DESC
255 * @param int $page The page or records to return
256 * @param int $recordsperpage The number of records to return per page
257 * @param string $search A simple string to search for
258 * @param string $firstinitial Users whose first name starts with $firstinitial
259 * @param string $lastinitial Users whose last name starts with $lastinitial
260 * @param string $extraselect An additional SQL select statement to append to the query
261 * @param array $extraparams Additional parameters to use for the above $extraselect
262 * @param object $extracontext If specified, will include user 'extra fields'
263 * as appropriate for current user and given context
264 * @return array Array of {@link $USER} records
266 function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0,
267 $search='', $firstinitial='', $lastinitial='', $extraselect='',
268 array $extraparams=null, $extracontext = null) {
271 $fullname = $DB->sql_fullname();
273 $select = "deleted <> 1";
276 if (!empty($search)) {
277 $search = trim($search);
278 $select .= " AND (". $DB->sql_like($fullname, ':search1', false, false).
279 " OR ". $DB->sql_like('email', ':search2', false, false).
280 " OR username = :search3)";
281 $params['search1'] = "%$search%";
282 $params['search2'] = "%$search%";
283 $params['search3'] = "$search";
287 $select .= " AND ". $DB->sql_like('firstname', ':fni', false, false);
288 $params['fni'] = "$firstinitial%";
291 $select .= " AND ". $DB->sql_like('lastname', ':lni', false, false);
292 $params['lni'] = "$lastinitial%";
296 $select .= " AND $extraselect";
297 $params = $params +
(array)$extraparams;
301 $sort = " ORDER BY $sort $dir";
304 // If a context is specified, get extra user fields that the current user
305 // is supposed to see.
308 $extrafields = get_extra_user_fields_sql($extracontext, '', '',
309 array('id', 'username', 'email', 'firstname', 'lastname', 'city', 'country',
310 'lastaccess', 'confirmed', 'mnethostid'));
313 // warning: will return UNCONFIRMED USERS
314 return $DB->get_records_sql("SELECT id, username, email, firstname, lastname, city, country,
315 lastaccess, confirmed, mnethostid, suspended $extrafields
318 $sort", $params, $page, $recordsperpage);
324 * Full list of users that have confirmed their accounts.
327 * @return array of unconfirmed users
329 function get_users_confirmed() {
331 return $DB->get_records_sql("SELECT *
333 WHERE confirmed = 1 AND deleted = 0 AND id <> ?", array($CFG->siteguest
));
337 /// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
341 * Returns $course object of the top-level site.
343 * @return object A {@link $COURSE} object for the site, exception if not found
345 function get_site() {
348 if (!empty($SITE->id
)) { // We already have a global to use, so return that
352 if ($course = $DB->get_record('course', array('category'=>0))) {
355 // course table exists, but the site is not there,
356 // unfortunately there is no automatic way to recover
357 throw new moodle_exception('nosite', 'error');
362 * Returns list of courses, for whole site, or category
364 * Returns list of courses, for whole site, or category
365 * Important: Using c.* for fields is extremely expensive because
366 * we are using distinct. You almost _NEVER_ need all the fields
367 * in such a large SELECT
372 * @uses CONTEXT_COURSE
373 * @param string|int $categoryid Either a category id or 'all' for everything
374 * @param string $sort A field and direction to sort by
375 * @param string $fields The additional fields to return
376 * @return array Array of courses
378 function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
380 global $USER, $CFG, $DB;
384 if ($categoryid !== "all" && is_numeric($categoryid)) {
385 $categoryselect = "WHERE c.category = :catid";
386 $params['catid'] = $categoryid;
388 $categoryselect = "";
394 $sortstatement = "ORDER BY $sort";
397 $visiblecourses = array();
399 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
401 $sql = "SELECT $fields $ccselect
407 // pull out all course matching the cat
408 if ($courses = $DB->get_records_sql($sql, $params)) {
410 // loop throught them
411 foreach ($courses as $course) {
412 context_instance_preload($course);
413 if (isset($course->visible
) && $course->visible
<= 0) {
414 // for hidden courses, require visibility check
415 if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
416 $visiblecourses [$course->id
] = $course;
419 $visiblecourses [$course->id
] = $course;
423 return $visiblecourses;
428 * Returns list of courses, for whole site, or category
430 * Similar to get_courses, but allows paging
431 * Important: Using c.* for fields is extremely expensive because
432 * we are using distinct. You almost _NEVER_ need all the fields
433 * in such a large SELECT
438 * @uses CONTEXT_COURSE
439 * @param string|int $categoryid Either a category id or 'all' for everything
440 * @param string $sort A field and direction to sort by
441 * @param string $fields The additional fields to return
442 * @param int $totalcount Reference for the number of courses
443 * @param string $limitfrom The course to start from
444 * @param string $limitnum The number of courses to limit to
445 * @return array Array of courses
447 function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
448 &$totalcount, $limitfrom="", $limitnum="") {
449 global $USER, $CFG, $DB;
453 $categoryselect = "";
454 if ($categoryid != "all" && is_numeric($categoryid)) {
455 $categoryselect = "WHERE c.category = :catid";
456 $params['catid'] = $categoryid;
458 $categoryselect = "";
461 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
467 $visiblecourses = array();
469 $sql = "SELECT $fields $ccselect
475 // pull out all course matching the cat
476 $rs = $DB->get_recordset_sql($sql, $params);
477 // iteration will have to be done inside loop to keep track of the limitfrom and limitnum
478 foreach($rs as $course) {
479 context_instance_preload($course);
480 if ($course->visible
<= 0) {
481 // for hidden courses, require visibility check
482 if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
484 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
485 $visiblecourses [$course->id
] = $course;
490 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
491 $visiblecourses [$course->id
] = $course;
496 return $visiblecourses;
500 * Retrieve course records with the course managers and other related records
501 * that we need for print_course(). This allows print_courses() to do its job
502 * in a constant number of DB queries, regardless of the number of courses,
503 * role assignments, etc.
505 * The returned array is indexed on c.id, and each course will have
506 * - $course->managers - array containing RA objects that include a $user obj
507 * with the minimal fields needed for fullname()
512 * @uses CONTEXT_COURSE
513 * @uses CONTEXT_SYSTEM
514 * @uses CONTEXT_COURSECAT
516 * @param int|string $categoryid Either the categoryid for the courses or 'all'
517 * @param string $sort A SQL sort field and direction
518 * @param array $fields An array of additional fields to fetch
521 function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=array()) {
525 * - Grab the courses JOINed w/context
527 * - Grab the interesting course-manager RAs
528 * JOINed with a base user obj and add them to each course
530 * So as to do all the work in 2 DB queries. The RA+user JOIN
531 * ends up being pretty expensive if it happens over _all_
532 * courses on a large site. (Are we surprised!?)
534 * So this should _never_ get called with 'all' on a large site.
537 global $USER, $CFG, $DB;
540 $allcats = false; // bool flag
541 if ($categoryid === 'all') {
542 $categoryclause = '';
544 } elseif (is_numeric($categoryid)) {
545 $categoryclause = "c.category = :catid";
546 $params['catid'] = $categoryid;
548 debugging("Could not recognise categoryid = $categoryid");
549 $categoryclause = '';
552 $basefields = array('id', 'category', 'sortorder',
553 'shortname', 'fullname', 'idnumber',
554 'startdate', 'visible',
555 'newsitems', 'groupmode', 'groupmodeforce');
557 if (!is_null($fields) && is_string($fields)) {
558 if (empty($fields)) {
559 $fields = $basefields;
561 // turn the fields from a string to an array that
562 // get_user_courses_bycap() will like...
563 $fields = explode(',',$fields);
564 $fields = array_map('trim', $fields);
565 $fields = array_unique(array_merge($basefields, $fields));
567 } elseif (is_array($fields)) {
568 $fields = array_merge($basefields,$fields);
570 $coursefields = 'c.' .join(',c.', $fields);
575 $sortstatement = "ORDER BY $sort";
578 $where = 'WHERE c.id != ' . SITEID
;
579 if ($categoryclause !== ''){
580 $where = "$where AND $categoryclause";
583 // pull out all courses matching the cat
584 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
585 $sql = "SELECT $coursefields $ccselect
593 if ($courses = $DB->get_records_sql($sql, $params)) {
594 // loop on courses materialising
595 // the context, and prepping data to fetch the
596 // managers efficiently later...
597 foreach ($courses as $k => $course) {
598 context_instance_preload($course);
599 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
600 $courses[$k] = $course;
601 $courses[$k]->managers
= array();
602 if ($allcats === false) {
603 // single cat, so take just the first one...
604 if ($catpath === NULL) {
605 $catpath = preg_replace(':/\d+$:', '', $coursecontext->path
);
608 // chop off the contextid of the course itself
609 // like dirname() does...
610 $catpaths[] = preg_replace(':/\d+$:', '', $coursecontext->path
);
614 return array(); // no courses!
617 $CFG->coursecontact
= trim($CFG->coursecontact
);
618 if (empty($CFG->coursecontact
)) {
622 $managerroles = explode(',', $CFG->coursecontact
);
624 if (count($managerroles)) {
625 if ($allcats === true) {
626 $catpaths = array_unique($catpaths);
628 foreach ($catpaths as $cpath) {
629 $ctxids = array_merge($ctxids, explode('/',substr($cpath,1)));
631 $ctxids = array_unique($ctxids);
632 $catctxids = implode( ',' , $ctxids);
636 // take the ctx path from the first course
637 // as all categories will be the same...
638 $catpath = substr($catpath,1);
639 $catpath = preg_replace(':/\d+$:','',$catpath);
640 $catctxids = str_replace('/',',',$catpath);
642 if ($categoryclause !== '') {
643 $categoryclause = "AND $categoryclause";
646 * Note: Here we use a LEFT OUTER JOIN that can
647 * "optionally" match to avoid passing a ton of context
648 * ids in an IN() clause. Perhaps a subselect is faster.
650 * In any case, this SQL is not-so-nice over large sets of
651 * courses with no $categoryclause.
654 $sql = "SELECT ctx.path, ctx.instanceid, ctx.contextlevel,
655 r.id AS roleid, r.name as rolename,
656 u.id AS userid, u.firstname, u.lastname
657 FROM {role_assignments} ra
658 JOIN {context} ctx ON ra.contextid = ctx.id
659 JOIN {user} u ON ra.userid = u.id
660 JOIN {role} r ON ra.roleid = r.id
661 LEFT OUTER JOIN {course} c
662 ON (ctx.instanceid=c.id AND ctx.contextlevel=".CONTEXT_COURSE
.")
663 WHERE ( c.id IS NOT NULL";
664 // under certain conditions, $catctxids is NULL
665 if($catctxids == NULL){
668 $sql .= " OR ra.contextid IN ($catctxids) )";
671 $sql .= "AND ra.roleid IN ({$CFG->coursecontact})
673 ORDER BY r.sortorder ASC, ctx.contextlevel ASC, ra.sortorder ASC";
674 $rs = $DB->get_recordset_sql($sql, $params);
676 // This loop is fairly stupid as it stands - might get better
677 // results doing an initial pass clustering RAs by path.
678 foreach($rs as $ra) {
679 $user = new stdClass
;
680 $user->id
= $ra->userid
; unset($ra->userid
);
681 $user->firstname
= $ra->firstname
; unset($ra->firstname
);
682 $user->lastname
= $ra->lastname
; unset($ra->lastname
);
684 if ($ra->contextlevel
== CONTEXT_SYSTEM
) {
685 foreach ($courses as $k => $course) {
686 $courses[$k]->managers
[] = $ra;
688 } else if ($ra->contextlevel
== CONTEXT_COURSECAT
) {
689 if ($allcats === false) {
691 foreach ($courses as $k => $course) {
692 $courses[$k]->managers
[] = $ra;
695 foreach ($courses as $k => $course) {
696 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
697 // Note that strpos() returns 0 as "matched at pos 0"
698 if (strpos($coursecontext->path
, $ra->path
.'/') === 0) {
699 // Only add it to subpaths
700 $courses[$k]->managers
[] = $ra;
704 } else { // course-level
705 if (!array_key_exists($ra->instanceid
, $courses)) {
706 //this course is not in a list, probably a frontpage course
709 $courses[$ra->instanceid
]->managers
[] = $ra;
719 * A list of courses that match a search
723 * @param array $searchterms An array of search criteria
724 * @param string $sort A field and direction to sort by
725 * @param int $page The page number to get
726 * @param int $recordsperpage The number of records per page
727 * @param int $totalcount Passed in by reference.
728 * @return object {@link $COURSE} records
730 function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $recordsperpage=50, &$totalcount) {
733 if ($DB->sql_regex_supported()) {
734 $REGEXP = $DB->sql_regex(true);
735 $NOTREGEXP = $DB->sql_regex(false);
738 $searchcond = array();
742 // Thanks Oracle for your non-ansi concat and type limits in coalesce. MDL-29912
743 if ($DB->get_dbfamily() == 'oracle') {
744 $concat = $DB->sql_concat('c.summary', "' '", 'c.fullname', "' '", 'c.idnumber', "' '", 'c.shortname');
746 $concat = $DB->sql_concat("COALESCE(c.summary, '". $DB->sql_empty() ."')", "' '", 'c.fullname', "' '", 'c.idnumber', "' '", 'c.shortname');
749 foreach ($searchterms as $searchterm) {
752 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
753 /// will use it to simulate the "-" operator with LIKE clause
755 /// Under Oracle and MSSQL, trim the + and - operators and perform
756 /// simpler LIKE (or NOT LIKE) queries
757 if (!$DB->sql_regex_supported()) {
758 if (substr($searchterm, 0, 1) == '-') {
761 $searchterm = trim($searchterm, '+-');
764 // TODO: +- may not work for non latin languages
766 if (substr($searchterm,0,1) == '+') {
767 $searchterm = trim($searchterm, '+-');
768 $searchterm = preg_quote($searchterm, '|');
769 $searchcond[] = "$concat $REGEXP :ss$i";
770 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
772 } else if (substr($searchterm,0,1) == "-") {
773 $searchterm = trim($searchterm, '+-');
774 $searchterm = preg_quote($searchterm, '|');
775 $searchcond[] = "$concat $NOTREGEXP :ss$i";
776 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
779 $searchcond[] = $DB->sql_like($concat,":ss$i", false, true, $NOT);
780 $params['ss'.$i] = "%$searchterm%";
784 if (empty($searchcond)) {
789 $searchcond = implode(" AND ", $searchcond);
792 $c = 0; // counts how many visible courses we've seen
795 $limitfrom = $page * $recordsperpage;
796 $limitto = $limitfrom +
$recordsperpage;
798 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
799 $sql = "SELECT c.* $ccselect
802 WHERE $searchcond AND c.id <> ".SITEID
."
805 $rs = $DB->get_recordset_sql($sql, $params);
806 foreach($rs as $course) {
807 context_instance_preload($course);
808 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
809 if ($course->visible ||
has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
810 // Don't exit this loop till the end
811 // we need to count all the visible courses
812 // to update $totalcount
813 if ($c >= $limitfrom && $c < $limitto) {
814 $courses[$course->id
] = $course;
821 // our caller expects 2 bits of data - our return
822 // array, and an updated $totalcount
829 * Returns a sorted list of categories. Each category object has a context
830 * property that is a context object.
832 * When asking for $parent='none' it will return all the categories, regardless
833 * of depth. Wheen asking for a specific parent, the default is to return
834 * a "shallow" resultset. Pass false to $shallow and it will return all
835 * the child categories as well.
838 * @uses CONTEXT_COURSECAT
839 * @param string $parent The parent category if any
840 * @param string $sort the sortorder
841 * @param bool $shallow - set to false to get the children too
842 * @return array of categories
844 function get_categories($parent='none', $sort=NULL, $shallow=true) {
847 if ($sort === NULL) {
848 $sort = 'ORDER BY cc.sortorder ASC';
849 } elseif ($sort ==='') {
852 $sort = "ORDER BY $sort";
855 list($ccselect, $ccjoin) = context_instance_preload_sql('cc.id', CONTEXT_COURSECAT
, 'ctx');
857 if ($parent === 'none') {
858 $sql = "SELECT cc.* $ccselect
859 FROM {course_categories} cc
864 } elseif ($shallow) {
865 $sql = "SELECT cc.* $ccselect
866 FROM {course_categories} cc
870 $params = array($parent);
873 $sql = "SELECT cc.* $ccselect
874 FROM {course_categories} cc
876 JOIN {course_categories} ccp
877 ON ((cc.parent = ccp.id) OR (cc.path LIKE ".$DB->sql_concat('ccp.path',"'/%'")."))
880 $params = array($parent);
882 $categories = array();
884 $rs = $DB->get_recordset_sql($sql, $params);
885 foreach($rs as $cat) {
886 context_instance_preload($cat);
887 $catcontext = get_context_instance(CONTEXT_COURSECAT
, $cat->id
);
888 if ($cat->visible ||
has_capability('moodle/category:viewhiddencategories', $catcontext)) {
889 $categories[$cat->id
] = $cat;
898 * Returns an array of category ids of all the subcategories for a given
902 * @param int $catid - The id of the category whose subcategories we want to find.
903 * @return array of category ids.
905 function get_all_subcategories($catid) {
910 if ($categories = $DB->get_records('course_categories', array('parent'=>$catid))) {
911 foreach ($categories as $cat) {
912 array_push($subcats, $cat->id
);
913 $subcats = array_merge($subcats, get_all_subcategories($cat->id
));
920 * Return specified category, default if given does not exist
923 * @uses MAX_COURSES_IN_CATEGORY
924 * @uses CONTEXT_COURSECAT
926 * @param int $catid course category id
927 * @return object caregory
929 function get_course_category($catid=0) {
934 if (!empty($catid)) {
935 $category = $DB->get_record('course_categories', array('id'=>$catid));
939 // the first category is considered default for now
940 if ($category = $DB->get_records('course_categories', null, 'sortorder', '*', 0, 1)) {
941 $category = reset($category);
944 $cat = new stdClass();
945 $cat->name
= get_string('miscellaneous');
947 $cat->sortorder
= MAX_COURSES_IN_CATEGORY
;
948 $cat->timemodified
= time();
949 $catid = $DB->insert_record('course_categories', $cat);
950 // make sure category context exists
951 get_context_instance(CONTEXT_COURSECAT
, $catid);
952 mark_context_dirty('/'.SYSCONTEXTID
);
953 fix_course_sortorder(); // Required to build course_categories.depth and .path.
954 $category = $DB->get_record('course_categories', array('id'=>$catid));
962 * Fixes course category and course sortorder, also verifies category and course parents and paths.
963 * (circular references are not fixed)
967 * @uses MAX_COURSES_IN_CATEGORY
968 * @uses MAX_COURSE_CATEGORIES
970 * @uses CONTEXT_COURSE
973 function fix_course_sortorder() {
976 //WARNING: this is PHP5 only code!
978 if ($unsorted = $DB->get_records('course_categories', array('sortorder'=>0))) {
979 //move all categories that are not sorted yet to the end
980 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY
*MAX_COURSE_CATEGORIES
, array('sortorder'=>0));
983 $allcats = $DB->get_records('course_categories', null, 'sortorder, id', 'id, sortorder, parent, depth, path');
985 $brokencats = array();
986 foreach ($allcats as $cat) {
987 $sortorder = (int)$cat->sortorder
;
989 while(isset($topcats[$sortorder])) {
992 $topcats[$sortorder] = $cat;
995 if (!isset($allcats[$cat->parent
])) {
996 $brokencats[] = $cat;
999 if (!isset($allcats[$cat->parent
]->children
)) {
1000 $allcats[$cat->parent
]->children
= array();
1002 while(isset($allcats[$cat->parent
]->children
[$sortorder])) {
1005 $allcats[$cat->parent
]->children
[$sortorder] = $cat;
1009 // add broken cats to category tree
1011 $defaultcat = reset($topcats);
1012 foreach ($brokencats as $cat) {
1017 // now walk recursively the tree and fix any problems found
1019 $fixcontexts = array();
1020 _fix_course_cats($topcats, $sortorder, 0, 0, '', $fixcontexts);
1022 // detect if there are "multiple" frontpage courses and fix them if needed
1023 $frontcourses = $DB->get_records('course', array('category'=>0), 'id');
1024 if (count($frontcourses) > 1) {
1025 if (isset($frontcourses[SITEID
])) {
1026 $frontcourse = $frontcourses[SITEID
];
1027 unset($frontcourses[SITEID
]);
1029 $frontcourse = array_shift($frontcourses);
1031 $defaultcat = reset($topcats);
1032 foreach ($frontcourses as $course) {
1033 $DB->set_field('course', 'category', $defaultcat->id
, array('id'=>$course->id
));
1034 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
1035 $fixcontexts[$context->id
] = $context;
1037 unset($frontcourses);
1039 $frontcourse = reset($frontcourses);
1042 // now fix the paths and depths in context table if needed
1044 foreach ($fixcontexts as $fixcontext) {
1045 $fixcontext->reset_paths(false);
1047 context_helper
::build_all_paths(false);
1048 unset($fixcontexts);
1054 unset($fixcontexts);
1056 // fix frontpage course sortorder
1057 if ($frontcourse->sortorder
!= 1) {
1058 $DB->set_field('course', 'sortorder', 1, array('id'=>$frontcourse->id
));
1061 // now fix the course counts in category records if needed
1062 $sql = "SELECT cc.id, cc.coursecount, COUNT(c.id) AS newcount
1063 FROM {course_categories} cc
1064 LEFT JOIN {course} c ON c.category = cc.id
1065 GROUP BY cc.id, cc.coursecount
1066 HAVING cc.coursecount <> COUNT(c.id)";
1068 if ($updatecounts = $DB->get_records_sql($sql)) {
1069 // categories with more courses than MAX_COURSES_IN_CATEGORY
1070 $categories = array();
1071 foreach ($updatecounts as $cat) {
1072 $cat->coursecount
= $cat->newcount
;
1073 if ($cat->coursecount
>= MAX_COURSES_IN_CATEGORY
) {
1074 $categories[] = $cat->id
;
1076 unset($cat->newcount
);
1077 $DB->update_record_raw('course_categories', $cat, true);
1079 if (!empty($categories)) {
1080 $str = implode(', ', $categories);
1081 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
);
1085 // now make sure that sortorders in course table are withing the category sortorder ranges
1086 $sql = "SELECT DISTINCT cc.id, cc.sortorder
1087 FROM {course_categories} cc
1088 JOIN {course} c ON c.category = cc.id
1089 WHERE c.sortorder < cc.sortorder OR c.sortorder > cc.sortorder + ".MAX_COURSES_IN_CATEGORY
;
1091 if ($fixcategories = $DB->get_records_sql($sql)) {
1092 //fix the course sortorder ranges
1093 foreach ($fixcategories as $cat) {
1094 $sql = "UPDATE {course}
1095 SET sortorder = ".$DB->sql_modulo('sortorder', MAX_COURSES_IN_CATEGORY
)." + ?
1096 WHERE category = ?";
1097 $DB->execute($sql, array($cat->sortorder
, $cat->id
));
1100 unset($fixcategories);
1102 // categories having courses with sortorder duplicates or having gaps in sortorder
1103 $sql = "SELECT DISTINCT c1.category AS id , cc.sortorder
1105 JOIN {course} c2 ON c1.sortorder = c2.sortorder
1106 JOIN {course_categories} cc ON (c1.category = cc.id)
1107 WHERE c1.id <> c2.id";
1108 $fixcategories = $DB->get_records_sql($sql);
1110 $sql = "SELECT cc.id, cc.sortorder, cc.coursecount, MAX(c.sortorder) AS maxsort, MIN(c.sortorder) AS minsort
1111 FROM {course_categories} cc
1112 JOIN {course} c ON c.category = cc.id
1113 GROUP BY cc.id, cc.sortorder, cc.coursecount
1114 HAVING (MAX(c.sortorder) <> cc.sortorder + cc.coursecount) OR (MIN(c.sortorder) <> cc.sortorder + 1)";
1115 $gapcategories = $DB->get_records_sql($sql);
1117 foreach ($gapcategories as $cat) {
1118 if (isset($fixcategories[$cat->id
])) {
1119 // duplicates detected already
1121 } else if ($cat->minsort
== $cat->sortorder
and $cat->maxsort
== $cat->sortorder +
$cat->coursecount
- 1) {
1122 // easy - new course inserted with sortorder 0, the rest is ok
1123 $sql = "UPDATE {course}
1124 SET sortorder = sortorder + 1
1125 WHERE category = ?";
1126 $DB->execute($sql, array($cat->id
));
1129 // it needs full resorting
1130 $fixcategories[$cat->id
] = $cat;
1133 unset($gapcategories);
1135 // fix course sortorders in problematic categories only
1136 foreach ($fixcategories as $cat) {
1138 $courses = $DB->get_records('course', array('category'=>$cat->id
), 'sortorder ASC, id DESC', 'id, sortorder');
1139 foreach ($courses as $course) {
1140 if ($course->sortorder
!= $cat->sortorder +
$i) {
1141 $course->sortorder
= $cat->sortorder +
$i;
1142 $DB->update_record_raw('course', $course, true);
1150 * Internal recursive category verification function, do not use directly!
1152 * @todo Document the arguments of this function better
1155 * @uses MAX_COURSES_IN_CATEGORY
1156 * @uses CONTEXT_COURSECAT
1157 * @param array $children
1158 * @param int $sortorder
1159 * @param string $parent
1161 * @param string $path
1162 * @param array $fixcontexts
1165 function _fix_course_cats($children, &$sortorder, $parent, $depth, $path, &$fixcontexts) {
1170 foreach ($children as $cat) {
1171 $sortorder = $sortorder + MAX_COURSES_IN_CATEGORY
;
1173 if ($parent != $cat->parent
or $depth != $cat->depth
or $path.'/'.$cat->id
!= $cat->path
) {
1174 $cat->parent
= $parent;
1175 $cat->depth
= $depth;
1176 $cat->path
= $path.'/'.$cat->id
;
1179 // make sure context caches are rebuild and dirty contexts marked
1180 $context = get_context_instance(CONTEXT_COURSECAT
, $cat->id
);
1181 $fixcontexts[$context->id
] = $context;
1183 if ($cat->sortorder
!= $sortorder) {
1184 $cat->sortorder
= $sortorder;
1188 $DB->update_record('course_categories', $cat, true);
1190 if (isset($cat->children
)) {
1191 _fix_course_cats($cat->children
, $sortorder, $cat->id
, $cat->depth
, $cat->path
, $fixcontexts);
1197 * List of remote courses that a user has access to via MNET.
1198 * Works only on the IDP
1202 * @param int @userid The user id to get remote courses for
1203 * @return array Array of {@link $COURSE} of course objects
1205 function get_my_remotecourses($userid=0) {
1208 if (empty($userid)) {
1209 $userid = $USER->id
;
1212 // we can not use SELECT DISTINCT + text field (summary) because of MS SQL and Oracle, subselect used therefore
1213 $sql = "SELECT c.id, c.remoteid, c.shortname, c.fullname,
1214 c.hostid, c.summary, c.summaryformat, c.categoryname AS cat_name,
1216 FROM {mnetservice_enrol_courses} c
1217 JOIN (SELECT DISTINCT hostid, remotecourseid
1218 FROM {mnetservice_enrol_enrolments}
1220 ) e ON (e.hostid = c.hostid AND e.remotecourseid = c.remoteid)
1221 JOIN {mnet_host} h ON h.id = c.hostid";
1223 return $DB->get_records_sql($sql, array($userid));
1227 * List of remote hosts that a user has access to via MNET.
1232 * @return array|bool Array of host objects or false
1234 function get_my_remotehosts() {
1237 if ($USER->mnethostid
== $CFG->mnet_localhost_id
) {
1238 return false; // Return nothing on the IDP
1240 if (!empty($USER->mnet_foreign_host_array
) && is_array($USER->mnet_foreign_host_array
)) {
1241 return $USER->mnet_foreign_host_array
;
1247 * This function creates a default separated/connected scale
1249 * This function creates a default separated/connected scale
1250 * so there's something in the database. The locations of
1251 * strings and files is a bit odd, but this is because we
1252 * need to maintain backward compatibility with many different
1253 * existing language translations and older sites.
1258 function make_default_scale() {
1261 $defaultscale = new stdClass();
1262 $defaultscale->courseid
= 0;
1263 $defaultscale->userid
= 0;
1264 $defaultscale->name
= get_string('separateandconnected');
1265 $defaultscale->description
= get_string('separateandconnectedinfo');
1266 $defaultscale->scale
= get_string('postrating1', 'forum').','.
1267 get_string('postrating2', 'forum').','.
1268 get_string('postrating3', 'forum');
1269 $defaultscale->timemodified
= time();
1271 $defaultscale->id
= $DB->insert_record('scale', $defaultscale);
1272 $DB->execute("UPDATE {forum} SET scale = ?", array($defaultscale->id
));
1277 * Returns a menu of all available scales from the site as well as the given course
1280 * @param int $courseid The id of the course as found in the 'course' table.
1283 function get_scales_menu($courseid=0) {
1286 $sql = "SELECT id, name
1288 WHERE courseid = 0 or courseid = ?
1289 ORDER BY courseid ASC, name ASC";
1290 $params = array($courseid);
1292 if ($scales = $DB->get_records_sql_menu($sql, $params)) {
1296 make_default_scale();
1298 return $DB->get_records_sql_menu($sql, $params);
1304 * Given a set of timezone records, put them in the database, replacing what is there
1307 * @param array $timezones An array of timezone records
1310 function update_timezone_records($timezones) {
1313 /// Clear out all the old stuff
1314 $DB->delete_records('timezone');
1316 /// Insert all the new stuff
1317 foreach ($timezones as $timezone) {
1318 if (is_array($timezone)) {
1319 $timezone = (object)$timezone;
1321 $DB->insert_record('timezone', $timezone);
1326 /// MODULE FUNCTIONS /////////////////////////////////////////////////
1329 * Just gets a raw list of all modules in a course
1332 * @param int $courseid The id of the course as found in the 'course' table.
1335 function get_course_mods($courseid) {
1338 if (empty($courseid)) {
1339 return false; // avoid warnings
1342 return $DB->get_records_sql("SELECT cm.*, m.name as modname
1343 FROM {modules} m, {course_modules} cm
1344 WHERE cm.course = ? AND cm.module = m.id AND m.visible = 1",
1345 array($courseid)); // no disabled mods
1350 * Given an id of a course module, finds the coursemodule description
1353 * @param string $modulename name of module type, eg. resource, assignment,... (optional, slower and less safe if not specified)
1354 * @param int $cmid course module id (id in course_modules table)
1355 * @param int $courseid optional course id for extra validation
1356 * @param bool $sectionnum include relative section number (0,1,2 ...)
1357 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1358 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1359 * MUST_EXIST means throw exception if no record or multiple records found
1362 function get_coursemodule_from_id($modulename, $cmid, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING
) {
1365 $params = array('cmid'=>$cmid);
1368 if (!$modulename = $DB->get_field_sql("SELECT md.name
1370 JOIN {course_modules} cm ON cm.module = md.id
1371 WHERE cm.id = :cmid", $params, $strictness)) {
1376 $params['modulename'] = $modulename;
1383 $courseselect = "AND cm.course = :courseid";
1384 $params['courseid'] = $courseid;
1388 $sectionfield = ", cw.section AS sectionnum";
1389 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1392 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1393 FROM {course_modules} cm
1394 JOIN {modules} md ON md.id = cm.module
1395 JOIN {".$modulename."} m ON m.id = cm.instance
1397 WHERE cm.id = :cmid AND md.name = :modulename
1400 return $DB->get_record_sql($sql, $params, $strictness);
1404 * Given an instance number of a module, finds the coursemodule description
1407 * @param string $modulename name of module type, eg. resource, assignment,...
1408 * @param int $instance module instance number (id in resource, assignment etc. table)
1409 * @param int $courseid optional course id for extra validation
1410 * @param bool $sectionnum include relative section number (0,1,2 ...)
1411 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1412 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1413 * MUST_EXIST means throw exception if no record or multiple records found
1416 function get_coursemodule_from_instance($modulename, $instance, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING
) {
1419 $params = array('instance'=>$instance, 'modulename'=>$modulename);
1426 $courseselect = "AND cm.course = :courseid";
1427 $params['courseid'] = $courseid;
1431 $sectionfield = ", cw.section AS sectionnum";
1432 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1435 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1436 FROM {course_modules} cm
1437 JOIN {modules} md ON md.id = cm.module
1438 JOIN {".$modulename."} m ON m.id = cm.instance
1440 WHERE m.id = :instance AND md.name = :modulename
1443 return $DB->get_record_sql($sql, $params, $strictness);
1447 * Returns all course modules of given activity in course
1449 * @param string $modulename The module name (forum, quiz, etc.)
1450 * @param int $courseid The course id to get modules for
1451 * @param string $extrafields extra fields starting with m.
1452 * @return array Array of results
1454 function get_coursemodules_in_course($modulename, $courseid, $extrafields='') {
1457 if (!empty($extrafields)) {
1458 $extrafields = ", $extrafields";
1461 $params['courseid'] = $courseid;
1462 $params['modulename'] = $modulename;
1465 return $DB->get_records_sql("SELECT cm.*, m.name, md.name as modname $extrafields
1466 FROM {course_modules} cm, {modules} md, {".$modulename."} m
1467 WHERE cm.course = :courseid AND
1468 cm.instance = m.id AND
1469 md.name = :modulename AND
1470 md.id = cm.module", $params);
1474 * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1476 * Returns an array of all the active instances of a particular
1477 * module in given courses, sorted in the order they are defined
1478 * in the course. Returns an empty array on any errors.
1480 * The returned objects includle the columns cw.section, cm.visible,
1481 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1485 * @param string $modulename The name of the module to get instances for
1486 * @param array $courses an array of course objects.
1487 * @param int $userid
1488 * @param int $includeinvisible
1489 * @return array of module instance objects, including some extra fields from the course_modules
1490 * and course_sections tables, or an empty array if an error occurred.
1492 function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
1495 $outputarray = array();
1497 if (empty($courses) ||
!is_array($courses) ||
count($courses) == 0) {
1498 return $outputarray;
1501 list($coursessql, $params) = $DB->get_in_or_equal(array_keys($courses), SQL_PARAMS_NAMED
, 'c0');
1502 $params['modulename'] = $modulename;
1504 if (!$rawmods = $DB->get_records_sql("SELECT cm.id AS coursemodule, m.*, cw.section, cm.visible AS visible,
1505 cm.groupmode, cm.groupingid, cm.groupmembersonly
1506 FROM {course_modules} cm, {course_sections} cw, {modules} md,
1508 WHERE cm.course $coursessql AND
1509 cm.instance = m.id AND
1510 cm.section = cw.id AND
1511 md.name = :modulename AND
1512 md.id = cm.module", $params)) {
1513 return $outputarray;
1516 foreach ($courses as $course) {
1517 $modinfo = get_fast_modinfo($course, $userid);
1519 if (empty($modinfo->instances
[$modulename])) {
1523 foreach ($modinfo->instances
[$modulename] as $cm) {
1524 if (!$includeinvisible and !$cm->uservisible
) {
1527 if (!isset($rawmods[$cm->id
])) {
1530 $instance = $rawmods[$cm->id
];
1531 if (!empty($cm->extra
)) {
1532 $instance->extra
= $cm->extra
;
1534 $outputarray[] = $instance;
1538 return $outputarray;
1542 * Returns an array of all the active instances of a particular module in a given course,
1543 * sorted in the order they are defined.
1545 * Returns an array of all the active instances of a particular
1546 * module in a given course, sorted in the order they are defined
1547 * in the course. Returns an empty array on any errors.
1549 * The returned objects includle the columns cw.section, cm.visible,
1550 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1552 * Simply calls {@link all_instances_in_courses()} with a single provided course
1554 * @param string $modulename The name of the module to get instances for
1555 * @param object $course The course obect.
1556 * @return array of module instance objects, including some extra fields from the course_modules
1557 * and course_sections tables, or an empty array if an error occurred.
1558 * @param int $userid
1559 * @param int $includeinvisible
1561 function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
1562 return get_all_instances_in_courses($modulename, array($course->id
=> $course), $userid, $includeinvisible);
1567 * Determine whether a module instance is visible within a course
1569 * Given a valid module object with info about the id and course,
1570 * and the module's type (eg "forum") returns whether the object
1571 * is visible or not, groupmembersonly visibility not tested
1575 * @param $moduletype Name of the module eg 'forum'
1576 * @param $module Object which is the instance of the module
1577 * @return bool Success
1579 function instance_is_visible($moduletype, $module) {
1582 if (!empty($module->id
)) {
1583 $params = array('courseid'=>$module->course
, 'moduletype'=>$moduletype, 'moduleid'=>$module->id
);
1584 if ($records = $DB->get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.groupmembersonly, cm.course
1585 FROM {course_modules} cm, {modules} m
1586 WHERE cm.course = :courseid AND
1587 cm.module = m.id AND
1588 m.name = :moduletype AND
1589 cm.instance = :moduleid", $params)) {
1591 foreach ($records as $record) { // there should only be one - use the first one
1592 return $record->visible
;
1596 return true; // visible by default!
1600 * Determine whether a course module is visible within a course,
1601 * this is different from instance_is_visible() - faster and visibility for user
1605 * @uses DEBUG_DEVELOPER
1606 * @uses CONTEXT_MODULE
1607 * @uses CONDITION_MISSING_EXTRATABLE
1608 * @param object $cm object
1609 * @param int $userid empty means current user
1610 * @return bool Success
1612 function coursemodule_visible_for_user($cm, $userid=0) {
1615 if (empty($cm->id
)) {
1616 debugging("Incorrect course module parameter!", DEBUG_DEVELOPER
);
1619 if (empty($userid)) {
1620 $userid = $USER->id
;
1622 if (!$cm->visible
and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_MODULE
, $cm->id
), $userid)) {
1625 if ($CFG->enableavailability
) {
1626 require_once($CFG->libdir
.'/conditionlib.php');
1627 $ci=new condition_info($cm,CONDITION_MISSING_EXTRATABLE
);
1628 if(!$ci->is_available($cm->availableinfo
,false,$userid) and
1629 !has_capability('moodle/course:viewhiddenactivities',
1630 get_context_instance(CONTEXT_MODULE
, $cm->id
), $userid)) {
1634 return groups_course_module_visible($cm, $userid);
1640 /// LOG FUNCTIONS /////////////////////////////////////////////////////
1644 * Add an entry to the log table.
1646 * Add an entry to the log table. These are "action" focussed rather
1647 * than web server hits, and provide a way to easily reconstruct what
1648 * any particular student has been doing.
1652 * @global moodle_database $DB
1653 * @global stdClass $CFG
1654 * @global stdClass $USER
1656 * @uses DEBUG_DEVELOPER
1658 * @param int $courseid The course id
1659 * @param string $module The module name e.g. forum, journal, resource, course, user etc
1660 * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
1661 * @param string $url The file and parameters used to see the results of the action
1662 * @param string $info Additional description information
1663 * @param string $cm The course_module->id if there is one
1664 * @param string $user If log regards $user other than $USER
1667 function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
1668 // Note that this function intentionally does not follow the normal Moodle DB access idioms.
1669 // This is for a good reason: it is the most frequently used DB update function,
1670 // so it has been optimised for speed.
1671 global $DB, $CFG, $USER;
1673 if ($cm === '' ||
is_null($cm)) { // postgres won't translate empty string to its default
1680 if (session_is_loggedinas()) { // Don't log
1683 $userid = empty($USER->id
) ?
'0' : $USER->id
;
1686 if (isset($CFG->logguests
) and !$CFG->logguests
) {
1687 if (!$userid or isguestuser($userid)) {
1692 $REMOTE_ADDR = getremoteaddr();
1696 if (!empty($url)) { // could break doing html_entity_decode on an empty var.
1697 $url = html_entity_decode($url, ENT_QUOTES
, 'UTF-8');
1702 // Restrict length of log lines to the space actually available in the
1703 // database so that it doesn't cause a DB error. Log a warning so that
1704 // developers can avoid doing things which are likely to cause this on a
1706 if(!empty($info) && textlib
::strlen($info)>255) {
1707 $info = textlib
::substr($info,0,252).'...';
1708 debugging('Warning: logged very long info',DEBUG_DEVELOPER
);
1711 // If the 100 field size is changed, also need to alter print_log in course/lib.php
1712 if(!empty($url) && textlib
::strlen($url)>100) {
1713 $url = textlib
::substr($url,0,97).'...';
1714 debugging('Warning: logged very long URL',DEBUG_DEVELOPER
);
1717 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->logwrites++
;};
1719 $log = array('time'=>$timenow, 'userid'=>$userid, 'course'=>$courseid, 'ip'=>$REMOTE_ADDR, 'module'=>$module,
1720 'cmid'=>$cm, 'action'=>$action, 'url'=>$url, 'info'=>$info);
1723 $DB->insert_record_raw('log', $log, false);
1724 } catch (dml_exception
$e) {
1725 debugging('Error: Could not insert a new entry to the Moodle log. '. $e->error
, DEBUG_ALL
);
1727 // MDL-11893, alert $CFG->supportemail if insert into log failed
1728 if ($CFG->supportemail
and empty($CFG->noemailever
)) {
1729 // email_to_user is not usable because email_to_user tries to write to the logs table,
1730 // and this will get caught in an infinite loop, if disk is full
1732 $subject = 'Insert into log failed at your moodle site '.$site->fullname
;
1733 $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";
1734 $message .= "The failed query parameters are:\n\n" . var_export($log, true);
1736 $lasttime = get_config('admin', 'lastloginserterrormail');
1737 if(empty($lasttime) ||
time() - $lasttime > 60*60*24) { // limit to 1 email per day
1738 //using email directly rather than messaging as they may not be able to log in to access a message
1739 mail($CFG->supportemail
, $subject, $message);
1740 set_config('lastloginserterrormail', time(), 'admin');
1747 * Store user last access times - called when use enters a course or site
1751 * @global stdClass $USER
1752 * @global stdClass $CFG
1753 * @global moodle_database $DB
1754 * @uses LASTACCESS_UPDATE_SECS
1756 * @param int $courseid empty courseid means site
1759 function user_accesstime_log($courseid=0) {
1760 global $USER, $CFG, $DB;
1762 if (!isloggedin() or session_is_loggedinas()) {
1763 // no access tracking
1767 if (isguestuser()) {
1768 // Do not update guest access times/ips for performance.
1772 if (empty($courseid)) {
1778 /// Store site lastaccess time for the current user
1779 if ($timenow - $USER->lastaccess
> LASTACCESS_UPDATE_SECS
) {
1780 /// Update $USER->lastaccess for next checks
1781 $USER->lastaccess
= $timenow;
1783 $last = new stdClass();
1784 $last->id
= $USER->id
;
1785 $last->lastip
= getremoteaddr();
1786 $last->lastaccess
= $timenow;
1788 $DB->update_record_raw('user', $last);
1791 if ($courseid == SITEID
) {
1792 /// no user_lastaccess for frontpage
1796 /// Store course lastaccess times for the current user
1797 if (empty($USER->currentcourseaccess
[$courseid]) or ($timenow - $USER->currentcourseaccess
[$courseid] > LASTACCESS_UPDATE_SECS
)) {
1799 $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid'=>$USER->id
, 'courseid'=>$courseid));
1801 if ($lastaccess === false) {
1802 // Update course lastaccess for next checks
1803 $USER->currentcourseaccess
[$courseid] = $timenow;
1805 $last = new stdClass();
1806 $last->userid
= $USER->id
;
1807 $last->courseid
= $courseid;
1808 $last->timeaccess
= $timenow;
1809 $DB->insert_record_raw('user_lastaccess', $last, false);
1811 } else if ($timenow - $lastaccess < LASTACCESS_UPDATE_SECS
) {
1812 // no need to update now, it was updated recently in concurrent login ;-)
1815 // Update course lastaccess for next checks
1816 $USER->currentcourseaccess
[$courseid] = $timenow;
1818 $DB->set_field('user_lastaccess', 'timeaccess', $timenow, array('userid'=>$USER->id
, 'courseid'=>$courseid));
1824 * Select all log records based on SQL criteria
1828 * @global moodle_database $DB
1829 * @param string $select SQL select criteria
1830 * @param array $params named sql type params
1831 * @param string $order SQL order by clause to sort the records returned
1832 * @param string $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
1833 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set)
1834 * @param int $totalcount Passed in by reference.
1837 function get_logs($select, array $params=null, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
1841 $order = "ORDER BY $order";
1848 $select = "WHERE $select";
1851 $sql = "SELECT COUNT(*)
1855 $totalcount = $DB->count_records_sql($sql, $params);
1857 $sql = "SELECT l.*, u.firstname, u.lastname, u.picture
1859 LEFT JOIN {user} u ON l.userid = u.id
1863 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum) ;
1868 * Select all log records for a given course and user
1872 * @global moodle_database $DB
1874 * @param int $userid The id of the user as found in the 'user' table.
1875 * @param int $courseid The id of the course as found in the 'course' table.
1876 * @param string $coursestart unix timestamp representing course start date and time.
1879 function get_logs_usercourse($userid, $courseid, $coursestart) {
1886 $courseselect = "AND course = :courseid";
1887 $params['courseid'] = $courseid;
1889 $params['userid'] = $userid;
1890 $
$coursestart = (int)$coursestart; // note: unfortunately pg complains if you use name parameter or column alias in GROUP BY
1892 return $DB->get_records_sql("SELECT FLOOR((time - $coursestart)/". DAYSECS
.") AS day, COUNT(*) AS num
1894 WHERE userid = :userid
1895 AND time > $coursestart $courseselect
1896 GROUP BY FLOOR((time - $coursestart)/". DAYSECS
.")", $params);
1900 * Select all log records for a given course, user, and day
1904 * @global moodle_database $DB
1906 * @param int $userid The id of the user as found in the 'user' table.
1907 * @param int $courseid The id of the course as found in the 'course' table.
1908 * @param string $daystart unix timestamp of the start of the day for which the logs needs to be retrived
1911 function get_logs_userday($userid, $courseid, $daystart) {
1914 $params = array('userid'=>$userid);
1918 $courseselect = "AND course = :courseid";
1919 $params['courseid'] = $courseid;
1921 $daystart = (int)$daystart; // note: unfortunately pg complains if you use name parameter or column alias in GROUP BY
1923 return $DB->get_records_sql("SELECT FLOOR((time - $daystart)/". HOURSECS
.") AS hour, COUNT(*) AS num
1925 WHERE userid = :userid
1926 AND time > $daystart $courseselect
1927 GROUP BY FLOOR((time - $daystart)/". HOURSECS
.") ", $params);
1931 * Returns an object with counts of failed login attempts
1933 * Returns information about failed login attempts. If the current user is
1934 * an admin, then two numbers are returned: the number of attempts and the
1935 * number of accounts. For non-admins, only the attempts on the given user
1938 * @global moodle_database $DB
1939 * @uses CONTEXT_SYSTEM
1940 * @param string $mode Either 'admin' or 'everybody'
1941 * @param string $username The username we are searching for
1942 * @param string $lastlogin The date from which we are searching
1945 function count_login_failures($mode, $username, $lastlogin) {
1948 $params = array('mode'=>$mode, 'username'=>$username, 'lastlogin'=>$lastlogin);
1949 $select = "module='login' AND action='error' AND time > :lastlogin";
1951 $count = new stdClass();
1953 if (is_siteadmin()) {
1954 if ($count->attempts
= $DB->count_records_select('log', $select, $params)) {
1955 $count->accounts
= $DB->count_records_select('log', $select, $params, 'COUNT(DISTINCT info)');
1958 } else if ($mode == 'everybody') {
1959 if ($count->attempts
= $DB->count_records_select('log', "$select AND info = :username", $params)) {
1967 /// GENERAL HELPFUL THINGS ///////////////////////////////////
1970 * Dumps a given object's information for debugging purposes
1972 * When used in a CLI script, the object's information is written to the standard
1973 * error output stream. When used in a web script, the object is dumped to a
1974 * pre-formatted block with the "notifytiny" CSS class.
1976 * @param mixed $object The data to be printed
1977 * @return void output is echo'd
1979 function print_object($object) {
1981 // we may need a lot of memory here
1982 raise_memory_limit(MEMORY_EXTRA
);
1985 fwrite(STDERR
, print_r($object, true));
1986 fwrite(STDERR
, PHP_EOL
);
1988 echo html_writer
::tag('pre', s(print_r($object, true)), array('class' => 'notifytiny'));
1993 * This function is the official hook inside XMLDB stuff to delegate its debug to one
1994 * external function.
1996 * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
1997 * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
1999 * @uses DEBUG_DEVELOPER
2000 * @param string $message string contains the error message
2001 * @param object $object object XMLDB object that fired the debug
2003 function xmldb_debug($message, $object) {
2005 debugging($message, DEBUG_DEVELOPER
);
2010 * @uses CONTEXT_COURSECAT
2011 * @return boolean Whether the user can create courses in any category in the system.
2013 function user_can_create_courses() {
2015 $catsrs = $DB->get_recordset('course_categories');
2016 foreach ($catsrs as $cat) {
2017 if (has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT
, $cat->id
))) {