3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Library of functions for database manipulation.
21 * Other main libraries:
22 * - weblib.php - functions that produce web output
23 * - moodlelib.php - general-purpose Moodle functions
26 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 * The maximum courses in a category
32 * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
34 define('MAX_COURSES_IN_CATEGORY', 10000);
37 * The maximum number of course categories
38 * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
40 define('MAX_COURSE_CATEGORIES', 10000);
43 * Number of seconds to wait before updating lastaccess information in DB.
45 define('LASTACCESS_UPDATE_SECS', 60);
48 * Returns $user object of the main admin user
49 * primary admin = admin with lowest role_assignment id among admins
52 * @static object $myadmin
53 * @return object An associative array representing the admin user.
55 function get_admin() {
56 static $mainadmin = null;
58 if (!isset($mainadmin)) {
59 if (! $admins = get_admins()) {
62 //TODO: add some admin setting for specifying of THE main admin
63 // for now return the first assigned admin
64 $mainadmin = reset($admins);
70 * Returns list of all admins, using 1 DB query
74 function get_admins() {
79 WHERE u.deleted = 0 AND u.id IN ($CFG->siteadmins)";
81 return $DB->get_records_sql($sql);
85 * Get all of the courses in a given meta course
88 * @param int $metacourseid The metacourse id
91 function get_courses_in_metacourse($metacourseid) {
94 $sql = "SELECT c.id, c.shortname, c.fullname
95 FROM {course} c, {course_meta} mc
96 WHERE mc.parent_course = ? AND mc.child_course = c.id
97 ORDER BY c.shortname";
98 $params = array($metacourseid);
100 return $DB->get_records_sql($sql, $params);
104 * @todo Document this function
108 * @param int $metacourseid
111 function get_courses_notin_metacourse($metacourseid) {
114 if ($alreadycourses = get_courses_in_metacourse($metacourseid)) {
115 $alreadycourses = implode(',',array_keys($alreadycourses));
116 $alreadycourses = "AND c.id NOT IN ($alreadycourses)";
118 $alreadycourses = "";
121 $sql = "SELECT c.id,c.shortname,c.fullname
123 WHERE c.id != ? and c.id != ".SITEID." and c.metacourse != 1
125 ORDER BY c.shortname";
126 $params = array($metacourseid);
128 return $DB->get_records_sql($sql, $params);
132 * @todo Document this function
134 * This function is nearly identical to {@link get_courses_notin_metacourse()}
138 * @param int $metacourseid
139 * @return int The count
141 function count_courses_notin_metacourse($metacourseid) {
144 if ($alreadycourses = get_courses_in_metacourse($metacourseid)) {
145 $alreadycourses = implode(',',array_keys($alreadycourses));
146 $alreadycourses = "AND c.id NOT IN ($alreadycourses)";
148 $alreadycourses = "";
151 $sql = "SELECT COUNT(c.id)
153 WHERE c.id != ? and c.id != ".SITEID." and c.metacourse != 1
155 $params = array($metacourseid);
157 return $DB->count_records_sql($sql, $params);
161 * Search through course users
163 * If $coursid specifies the site course then this function searches
164 * through all undeleted and confirmed users
168 * @uses SQL_PARAMS_NAMED
169 * @uses CONTEXT_COURSE
170 * @param int $courseid The course in question.
171 * @param int $groupid The group in question.
172 * @param string $searchtext The string to search for
173 * @param string $sort A field to sort by
174 * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
177 function search_users($courseid, $groupid, $searchtext, $sort='', array $exceptions=null) {
180 $LIKE = $DB->sql_ilike();
181 $fullname = $DB->sql_fullname('u.firstname', 'u.lastname');
183 if (!empty($exceptions)) {
184 list($exceptions, $params) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex0000', false);
185 $except = "AND u.id $exceptions";
192 $order = "ORDER BY $sort";
197 $select = "u.deleted = 0 AND u.confirmed = 1 AND ($fullname $LIKE :search1 OR u.email $LIKE :search2)";
198 $params['search1'] = "%$searchtext%";
199 $params['search2'] = "%$searchtext%";
201 if (!$courseid or $courseid == SITEID) {
202 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
207 return $DB->get_records_sql($sql, $params);
211 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
213 JOIN {groups_members} gm ON gm.userid = u.id
214 WHERE $select AND gm.groupid = :groupid
217 $params['groupid'] = $groupid;
218 return $DB->get_records_sql($sql, $params);
221 $context = get_context_instance(CONTEXT_COURSE, $courseid);
222 $contextlists = get_related_contexts_string($context);
224 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
226 JOIN {role_assignments} ra ON ra.userid = u.id
227 WHERE $select AND ra.contextid $contextlists
230 return $DB->get_records_sql($sql, $params);
236 * Returns a subset of users
239 * @uses DEBUG_DEVELOPER
240 * @uses SQL_PARAMS_NAMED
241 * @param bool $get If false then only a count of the records is returned
242 * @param string $search A simple string to search for
243 * @param bool $confirmed A switch to allow/disallow unconfirmed users
244 * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
245 * @param string $sort A SQL snippet for the sorting criteria to use
246 * @param string $firstinitial Users whose first name starts with $firstinitial
247 * @param string $lastinitial Users whose last name starts with $lastinitial
248 * @param string $page The page or records to return
249 * @param string $recordsperpage The number of records to return per page
250 * @param string $fields A comma separated list of fields to be returned from the chosen table.
251 * @return array|int|bool {@link $USER} records unless get is false in which case the integer count of the records found is returned.
252 * False is returned if an error is encountered.
254 function get_users($get=true, $search='', $confirmed=false, array $exceptions=null, $sort='firstname ASC',
255 $firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields='*', $extraselect='', array $extraparams=null) {
258 if ($get && !$recordsperpage) {
259 debugging('Call to get_users with $get = true no $recordsperpage limit. ' .
260 'On large installations, this will probably cause an out of memory error. ' .
261 'Please think again and change your code so that it does not try to ' .
262 'load so much data into memory.', DEBUG_DEVELOPER);
265 $LIKE = $DB->sql_ilike();
266 $fullname = $DB->sql_fullname();
268 $select = " username <> :guest AND deleted = 0";
269 $params = array('guest'=>'guest');
271 if (!empty($search)){
272 $search = trim($search);
273 $select .= " AND ($fullname $LIKE :search1 OR email $LIKE :search2 OR username = :search3)";
274 $params['search1'] = "%$search%";
275 $params['search2'] = "%$search%";
276 $params['search3'] = "$search";
280 $select .= " AND confirmed = 1";
284 list($exceptions, $eparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex0000', false);
285 $params = $params + $eparams;
286 $except = " AND id $exceptions";
290 $select .= " AND firstname $LIKE :fni";
291 $params['fni'] = "$firstinitial%";
294 $select .= " AND lastname $LIKE :lni";
295 $params['lni'] = "$lastinitial%";
299 $select .= " AND $extraselect";
300 $params = $params + (array)$extraparams;
304 return $DB->get_records_select('user', $select, $params, $sort, $fields, $page, $recordsperpage);
306 return $DB->count_records_select('user', $select, $params);
312 * @todo Finish documenting this function
314 * @param string $sort An SQL field to sort by
315 * @param string $dir The sort direction ASC|DESC
316 * @param int $page The page or records to return
317 * @param int $recordsperpage The number of records to return per page
318 * @param string $search A simple string to search for
319 * @param string $firstinitial Users whose first name starts with $firstinitial
320 * @param string $lastinitial Users whose last name starts with $lastinitial
321 * @param string $extraselect An additional SQL select statement to append to the query
322 * @param array $extraparams Additional parameters to use for the above $extraselect
323 * @return array Array of {@link $USER} records
326 function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0,
327 $search='', $firstinitial='', $lastinitial='', $extraselect='', array $extraparams=null) {
330 $LIKE = $DB->sql_ilike();
331 $fullname = $DB->sql_fullname();
333 $select = "deleted <> 1";
336 if (!empty($search)) {
337 $search = trim($search);
338 $select .= " AND ($fullname $LIKE :search1 OR email $LIKE :search2 OR username = :search3)";
339 $params['search1'] = "%$search%";
340 $params['search2'] = "%$search%";
341 $params['search3'] = "$search";
345 $select .= " AND firstname $LIKE :fni";
346 $params['fni'] = "$firstinitial%";
349 $select .= " AND lastname $LIKE :lni";
350 $params['lni'] = "$lastinitial%";
354 $select .= " AND $extraselect";
355 $params = $params + (array)$extraparams;
359 $sort = " ORDER BY $sort $dir";
362 /// warning: will return UNCONFIRMED USERS
363 return $DB->get_records_sql("SELECT id, username, email, firstname, lastname, city, country, lastaccess, confirmed, mnethostid
366 $sort", $params, $page, $recordsperpage);
372 * Full list of users that have confirmed their accounts.
375 * @return array of unconfirmed users
377 function get_users_confirmed() {
379 return $DB->get_records_sql("SELECT *
381 WHERE confirmed = 1 AND deleted = 0 AND username <> ?", array('guest'));
385 /// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
389 * Returns $course object of the top-level site.
391 * @return object A {@link $COURSE} object for the site, exception if not found
393 function get_site() {
396 if (!empty($SITE->id)) { // We already have a global to use, so return that
400 if ($course = $DB->get_record('course', array('category'=>0))) {
403 // course table exists, but the site is not there,
404 // unfortunately there is no automatic way to recover
405 throw new moodle_exception('nosite', 'error');
410 * Returns list of courses, for whole site, or category
412 * Returns list of courses, for whole site, or category
413 * Important: Using c.* for fields is extremely expensive because
414 * we are using distinct. You almost _NEVER_ need all the fields
415 * in such a large SELECT
420 * @uses CONTEXT_COURSE
421 * @param string|int $categoryid Either a category id or 'all' for everything
422 * @param string $sort A field and direction to sort by
423 * @param string $fields The additional fields to return
424 * @return array Array of courses
426 function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
428 global $USER, $CFG, $DB;
432 if ($categoryid !== "all" && is_numeric($categoryid)) {
433 $categoryselect = "WHERE c.category = :catid";
434 $params['catid'] = $categoryid;
436 $categoryselect = "";
442 $sortstatement = "ORDER BY $sort";
445 $visiblecourses = array();
447 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
449 $sql = "SELECT $fields $ccselect
455 // pull out all course matching the cat
456 if ($courses = $DB->get_records_sql($sql, $params)) {
458 // loop throught them
459 foreach ($courses as $course) {
460 context_instance_preload($course);
461 if (isset($course->visible) && $course->visible <= 0) {
462 // for hidden courses, require visibility check
463 if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
464 $visiblecourses [$course->id] = $course;
467 $visiblecourses [$course->id] = $course;
471 return $visiblecourses;
476 * Returns list of courses, for whole site, or category
478 * Similar to get_courses, but allows paging
479 * Important: Using c.* for fields is extremely expensive because
480 * we are using distinct. You almost _NEVER_ need all the fields
481 * in such a large SELECT
486 * @uses CONTEXT_COURSE
487 * @param string|int $categoryid Either a category id or 'all' for everything
488 * @param string $sort A field and direction to sort by
489 * @param string $fields The additional fields to return
490 * @param int $totalcount Reference for the number of courses
491 * @param string $limitfrom The course to start from
492 * @param string $limitnum The number of courses to limit to
493 * @return array Array of courses
495 function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
496 &$totalcount, $limitfrom="", $limitnum="") {
497 global $USER, $CFG, $DB;
501 $categoryselect = "";
502 if ($categoryid != "all" && is_numeric($categoryid)) {
503 $categoryselect = "WHERE c.category = :catid";
504 $params['catid'] = $categoryid;
506 $categoryselect = "";
509 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
511 $sql = "SELECT $fields $ccselect
517 // pull out all course matching the cat
518 if (!$rs = $DB->get_recordset_sql($sql, $params)) {
527 // iteration will have to be done inside loop to keep track of the limitfrom and limitnum
528 $visiblecourses = array();
529 foreach($rs as $course) {
530 context_instance_preload($course);
531 if ($course->visible <= 0) {
532 // for hidden courses, require visibility check
533 if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
535 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
536 $visiblecourses [$course->id] = $course;
541 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
542 $visiblecourses [$course->id] = $course;
547 return $visiblecourses;
551 * Retrieve course records with the course managers and other related records
552 * that we need for print_course(). This allows print_courses() to do its job
553 * in a constant number of DB queries, regardless of the number of courses,
554 * role assignments, etc.
556 * The returned array is indexed on c.id, and each course will have
557 * - $course->managers - array containing RA objects that include a $user obj
558 * with the minimal fields needed for fullname()
563 * @uses CONTEXT_COURSE
564 * @uses CONTEXT_SYSTEM
565 * @uses CONTEXT_COURSECAT
567 * @param int|string $categoryid Either the categoryid for the courses or 'all'
568 * @param string $sort A SQL sort field and direction
569 * @param array $fields An array of additional fields to fetch
572 function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=array()) {
576 * - Grab the courses JOINed w/context
578 * - Grab the interesting course-manager RAs
579 * JOINed with a base user obj and add them to each course
581 * So as to do all the work in 2 DB queries. The RA+user JOIN
582 * ends up being pretty expensive if it happens over _all_
583 * courses on a large site. (Are we surprised!?)
585 * So this should _never_ get called with 'all' on a large site.
588 global $USER, $CFG, $DB;
591 $allcats = false; // bool flag
592 if ($categoryid === 'all') {
593 $categoryclause = '';
595 } elseif (is_numeric($categoryid)) {
596 $categoryclause = "c.category = :catid";
597 $params['catid'] = $categoryid;
599 debugging("Could not recognise categoryid = $categoryid");
600 $categoryclause = '';
603 $basefields = array('id', 'category', 'sortorder',
604 'shortname', 'fullname', 'idnumber',
605 'guest', 'startdate', 'visible',
606 'newsitems', 'cost', 'enrol',
607 'groupmode', 'groupmodeforce');
609 if (!is_null($fields) && is_string($fields)) {
610 if (empty($fields)) {
611 $fields = $basefields;
613 // turn the fields from a string to an array that
614 // get_user_courses_bycap() will like...
615 $fields = explode(',',$fields);
616 $fields = array_map('trim', $fields);
617 $fields = array_unique(array_merge($basefields, $fields));
619 } elseif (is_array($fields)) {
620 $fields = array_merge($basefields,$fields);
622 $coursefields = 'c.' .join(',c.', $fields);
627 $sortstatement = "ORDER BY $sort";
630 $where = 'WHERE c.id != ' . SITEID;
631 if ($categoryclause !== ''){
632 $where = "$where AND $categoryclause";
635 // pull out all courses matching the cat
636 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
637 $sql = "SELECT $coursefields $ccselect
645 if ($courses = $DB->get_records_sql($sql, $params)) {
646 // loop on courses materialising
647 // the context, and prepping data to fetch the
648 // managers efficiently later...
649 foreach ($courses as $k => $course) {
650 context_instance_preload($course);
651 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
652 $courses[$k] = $course;
653 $courses[$k]->managers = array();
654 if ($allcats === false) {
655 // single cat, so take just the first one...
656 if ($catpath === NULL) {
657 $catpath = preg_replace(':/\d+$:', '', $coursecontext->path);
660 // chop off the contextid of the course itself
661 // like dirname() does...
662 $catpaths[] = preg_replace(':/\d+$:', '', $coursecontext->path);
666 return array(); // no courses!
669 $CFG->coursemanager = trim($CFG->coursemanager);
670 if (empty($CFG->coursemanager)) {
674 $managerroles = split(',', $CFG->coursemanager);
676 if (count($managerroles)) {
677 if ($allcats === true) {
678 $catpaths = array_unique($catpaths);
680 foreach ($catpaths as $cpath) {
681 $ctxids = array_merge($ctxids, explode('/',substr($cpath,1)));
683 $ctxids = array_unique($ctxids);
684 $catctxids = implode( ',' , $ctxids);
688 // take the ctx path from the first course
689 // as all categories will be the same...
690 $catpath = substr($catpath,1);
691 $catpath = preg_replace(':/\d+$:','',$catpath);
692 $catctxids = str_replace('/',',',$catpath);
694 if ($categoryclause !== '') {
695 $categoryclause = "AND $categoryclause";
698 * Note: Here we use a LEFT OUTER JOIN that can
699 * "optionally" match to avoid passing a ton of context
700 * ids in an IN() clause. Perhaps a subselect is faster.
702 * In any case, this SQL is not-so-nice over large sets of
703 * courses with no $categoryclause.
706 $sql = "SELECT ctx.path, ctx.instanceid, ctx.contextlevel,
707 r.id AS roleid, r.name as rolename,
708 u.id AS userid, u.firstname, u.lastname
709 FROM {role_assignments} ra
710 JOIN {context} ctx ON ra.contextid = ctx.id
711 JOIN {user} u ON ra.userid = u.id
712 JOIN {role} r ON ra.roleid = r.id
713 LEFT OUTER JOIN {course} c
714 ON (ctx.instanceid=c.id AND ctx.contextlevel=".CONTEXT_COURSE.")
715 WHERE ( c.id IS NOT NULL";
716 // under certain conditions, $catctxids is NULL
717 if($catctxids == NULL){
720 $sql .= " OR ra.contextid IN ($catctxids) )";
723 $sql .= "AND ra.roleid IN ({$CFG->coursemanager})
725 ORDER BY r.sortorder ASC, ctx.contextlevel ASC, ra.sortorder ASC";
726 $rs = $DB->get_recordset_sql($sql, $params);
728 // This loop is fairly stupid as it stands - might get better
729 // results doing an initial pass clustering RAs by path.
730 foreach($rs as $ra) {
731 $user = new stdClass;
732 $user->id = $ra->userid; unset($ra->userid);
733 $user->firstname = $ra->firstname; unset($ra->firstname);
734 $user->lastname = $ra->lastname; unset($ra->lastname);
736 if ($ra->contextlevel == CONTEXT_SYSTEM) {
737 foreach ($courses as $k => $course) {
738 $courses[$k]->managers[] = $ra;
740 } else if ($ra->contextlevel == CONTEXT_COURSECAT) {
741 if ($allcats === false) {
743 foreach ($courses as $k => $course) {
744 $courses[$k]->managers[] = $ra;
747 foreach ($courses as $k => $course) {
748 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
749 // Note that strpos() returns 0 as "matched at pos 0"
750 if (strpos($coursecontext->path, $ra->path.'/') === 0) {
751 // Only add it to subpaths
752 $courses[$k]->managers[] = $ra;
756 } else { // course-level
757 if (!array_key_exists($ra->instanceid, $courses)) {
758 //this course is not in a list, probably a frontpage course
761 $courses[$ra->instanceid]->managers[] = $ra;
771 * Convenience function - lists courses that a user has access to view.
773 * For admins and others with access to "every" course in the system, we should
774 * try to get courses with explicit RAs.
776 * NOTE: this function is heavily geared towards the perspective of the user
777 * passed in $userid. So it will hide courses that the user cannot see
778 * (for any reason) even if called from cron or from another $USER's
781 * If you really want to know what courses are assigned to the user,
782 * without any hiding or scheming, call the lower-level
783 * get_user_courses_bycap().
786 * Notes inherited from get_user_courses_bycap():
788 * - $fields is an array of fieldnames to ADD
789 * so name the fields you really need, which will
790 * be added and uniq'd
792 * - the course records have $c->context which is a fully
793 * valid context object. Saves you a query per course!
798 * @uses CONTEXT_SYSTEM
799 * @uses CONTEXT_COURSE
800 * @uses CONTEXT_COURSECAT
801 * @param int $userid The user of interest
802 * @param string $sort the sortorder in the course table
803 * @param array $fields names of _additional_ fields to return (also accepts a string)
804 * @param bool $doanything True if using the doanything flag
805 * @param int $limit Maximum number of records to return, or 0 for unlimited
806 * @return array Array of {@link $COURSE} of course objects
808 function get_my_courses($userid, $sort='visible DESC,sortorder ASC', $fields=NULL, $doanything=false,$limit=0) {
809 global $CFG, $USER, $DB;
811 // Guest account does not have any courses
816 $basefields = array('id', 'category', 'sortorder',
817 'shortname', 'fullname', 'idnumber',
818 'guest', 'startdate', 'visible',
819 'newsitems', 'cost', 'enrol',
820 'groupmode', 'groupmodeforce');
822 if (!is_null($fields) && is_string($fields)) {
823 if (empty($fields)) {
824 $fields = $basefields;
826 // turn the fields from a string to an array that
827 // get_user_courses_bycap() will like...
828 $fields = explode(',',$fields);
829 $fields = array_map('trim', $fields);
830 $fields = array_unique(array_merge($basefields, $fields));
832 } elseif (is_array($fields)) {
833 $fields = array_unique(array_merge($basefields, $fields));
835 $fields = $basefields;
841 $rawsorts = explode(',', $sort);
843 foreach ($rawsorts as $rawsort) {
844 $rawsort = trim($rawsort);
845 if (strpos($rawsort, 'c.') === 0) {
846 $rawsort = substr($rawsort, 2);
848 $sorts[] = trim($rawsort);
850 $sort = 'c.'.implode(',c.', $sorts);
851 $orderby = "ORDER BY $sort";
855 // Logged-in user - Check cached courses
857 // NOTE! it's a _string_ because
858 // - it's all we'll ever use
859 // - it serialises much more compact than an array
860 // this a big concern here - cost of serialise
861 // and unserialise gets huge as the session grows
863 // If the courses are too many - it won't be set
864 // for large numbers of courses, caching in the session
865 // has marginal benefits (costs too much, not
866 // worthwhile...) and we may hit SQL parser limits
867 // because we use IN()
869 if ($userid === $USER->id) {
870 if (isset($USER->loginascontext)
871 && $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
872 // list _only_ this course
873 // anything else is asking for trouble...
874 $courseids = $USER->loginascontext->instanceid;
875 } elseif (isset($USER->mycourses)
876 && is_string($USER->mycourses)) {
877 if ($USER->mycourses === '') {
878 // empty str means: user has no courses
879 // ... so do the easy thing...
882 $courseids = $USER->mycourses;
885 if (isset($courseids)) {
886 // The data massaging here MUST be kept in sync with
887 // get_user_courses_bycap() so we return
889 // (but here we don't need to check has_cap)
890 $coursefields = 'c.' .join(',c.', $fields);
891 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
892 $sql = "SELECT $coursefields $ccselect, cc.path AS categorypath
894 JOIN {course_categories} cc ON c.category=cc.id
896 WHERE c.id IN ($courseids)
898 $rs = $DB->get_recordset_sql($sql);
900 $cc = 0; // keep count
901 foreach ($rs as $c) {
902 // build the context obj
903 context_instance_preload($c);
905 if ($limit > 0 && $cc >= $limit) {
909 $courses[$c->id] = $c;
917 // Non-cached - get accessinfo
918 if ($userid === $USER->id && isset($USER->access)) {
919 $accessinfo = $USER->access;
921 $accessinfo = get_user_access_sitewide($userid);
925 $courses = get_user_courses_bycap($userid, 'moodle/course:participate', $accessinfo,
926 $doanything, $sort, $fields,
930 // If we have to walk category visibility
931 // to eval course visibility, get the categories
932 if (empty($CFG->allowvisiblecoursesinhiddencategories)) {
933 list($ccselect, $ccjoin) = context_instance_preload_sql('cc.id', CONTEXT_COURSECAT, 'ctx');
934 $sql = "SELECT cc.id, cc.path, cc.visible $ccselect
935 FROM {course_categories} cc
938 $rs = $DB->get_recordset_sql($sql);
940 // Using a temporary array instead of $cats here, to avoid a "true" result when isnull($cats) further down
941 $categories = array();
942 foreach($rs as $course_cat) {
943 // build the context obj
944 context_instance_preload($course_cat);
945 $categories[$course_cat->id] = $course_cat;
949 if (!empty($categories)) {
956 // Strangely, get_my_courses() is expected to return the
957 // array keyed on id, which messes up the sorting
958 // So do that, and also cache the ids in the session if appropriate
961 $courses_count = count($courses);
963 $vcatpaths = array();
964 if ($userid === $USER->id && $courses_count < 500) {
967 for ($n=0; $n<$courses_count; $n++) {
970 // Check whether $USER (not $userid) can _actually_ see them
971 // Easy if $CFG->allowvisiblecoursesinhiddencategories
972 // is set, and we don't have to care about categories.
973 // Lots of work otherwise... (all in mem though!)
976 if (is_null($cats)) { // easy rules!
977 if ($courses[$n]->visible == true) {
979 } elseif (has_capability('moodle/course:viewhiddencourses',
980 $courses[$n]->context, $USER->id)) {
985 // Is the cat visible?
986 // we have to assume it _is_ visible
987 // so we can shortcut when we find a hidden one
990 $cpath = $courses[$n]->categorypath;
991 if (isset($vcatpaths[$cpath])) {
992 $viscat = $vcatpaths[$cpath];
994 $cpath = substr($cpath,1); // kill leading slash
995 $cpath = explode('/',$cpath);
996 $ccct = count($cpath);
997 for ($m=0;$m<$ccct;$m++) {
999 if ($cats[$ccid]->visible==false) {
1004 $vcatpaths[$courses[$n]->categorypath] = $viscat;
1008 // Perhaps it's actually visible to $USER
1009 // check moodle/category:viewhiddencategories
1011 // The name isn't obvious, but the description says
1012 // "See hidden categories" so the user shall see...
1013 // But also check if the allowvisiblecoursesinhiddencategories setting is true, and check for course visibility
1014 if ($viscat === false) {
1015 $catctx = $cats[$courses[$n]->category]->context;
1016 if (has_capability('moodle/category:viewhiddencategories', $catctx, $USER->id)) {
1017 $vcatpaths[$courses[$n]->categorypath] = true;
1019 } elseif ($CFG->allowvisiblecoursesinhiddencategories && $courses[$n]->visible == true) {
1027 if ($viscat === true) {
1028 if ($courses[$n]->visible == true) {
1030 } elseif (has_capability('moodle/course:viewhiddencourses',
1031 $courses[$n]->context, $USER->id)) {
1036 if ($cansee === true) {
1037 $kcourses[$courses[$n]->id] = $courses[$n];
1038 if (is_array($cacheids)) {
1039 $cacheids[] = $courses[$n]->id;
1043 if (is_array($cacheids)) {
1045 // - for the logged in user
1046 // - below the threshold (500)
1047 // empty string is _valid_
1048 $USER->mycourses = join(',',$cacheids);
1049 } elseif ($userid === $USER->id && isset($USER->mycourses)) {
1050 // cheap sanity check
1051 unset($USER->mycourses);
1058 * A list of courses that match a search
1062 * @param array $searchterms An array of search criteria
1063 * @param string $sort A field and direction to sort by
1064 * @param int $page The page number to get
1065 * @param int $recordsperpage The number of records per page
1066 * @param int $totalcount Passed in by reference.
1067 * @return object {@link $COURSE} records
1069 function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $recordsperpage=50, &$totalcount) {
1072 if ($DB->sql_regex_supported()) {
1073 $REGEXP = $DB->sql_regex(true);
1074 $NOTREGEXP = $DB->sql_regex(false);
1076 $LIKE = $DB->sql_ilike(); // case-insensitive
1078 $searchcond = array();
1082 $concat = $DB->sql_concat('c.summary', "' '", 'c.fullname');
1084 foreach ($searchterms as $searchterm) {
1087 $NOT = ''; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1088 /// will use it to simulate the "-" operator with LIKE clause
1090 /// Under Oracle and MSSQL, trim the + and - operators and perform
1091 /// simpler LIKE (or NOT LIKE) queries
1092 if (!$DB->sql_regex_supported()) {
1093 if (substr($searchterm, 0, 1) == '-') {
1096 $searchterm = trim($searchterm, '+-');
1099 // TODO: +- may not work for non latin languages
1101 if (substr($searchterm,0,1) == '+') {
1102 $searchterm = trim($searchterm, '+-');
1103 $searchterm = preg_quote($searchterm, '|');
1104 $searchcond[] = "$concat $REGEXP :ss$i";
1105 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1107 } else if (substr($searchterm,0,1) == "-") {
1108 $searchterm = trim($searchterm, '+-');
1109 $searchterm = preg_quote($searchterm, '|');
1110 $searchcond[] = "$concat $NOTREGEXP :ss$i";
1111 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1114 $searchcond[] = "$concat $NOT $LIKE :ss$i";
1115 $params['ss'.$i] = "%$searchterm%";
1119 if (empty($searchcond)) {
1124 $searchcond = implode(" AND ", $searchcond);
1126 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1127 $sql = "SELECT c.* $ccselect
1130 WHERE $searchcond AND c.id <> ".SITEID."
1133 $c = 0; // counts how many visible courses we've seen
1135 if ($rs = $DB->get_recordset_sql($sql, $params)) {
1137 $limitfrom = $page * $recordsperpage;
1138 $limitto = $limitfrom + $recordsperpage;
1140 foreach($rs as $course) {
1141 context_instance_preload($course);
1142 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1143 if ($course->visible || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
1144 // Don't exit this loop till the end
1145 // we need to count all the visible courses
1146 // to update $totalcount
1147 if ($c >= $limitfrom && $c < $limitto) {
1148 $courses[$course->id] = $course;
1156 // our caller expects 2 bits of data - our return
1157 // array, and an updated $totalcount
1164 * Returns a sorted list of categories. Each category object has a context
1165 * property that is a context object.
1167 * When asking for $parent='none' it will return all the categories, regardless
1168 * of depth. Wheen asking for a specific parent, the default is to return
1169 * a "shallow" resultset. Pass false to $shallow and it will return all
1170 * the child categories as well.
1173 * @uses CONTEXT_COURSECAT
1174 * @param string $parent The parent category if any
1175 * @param string $sort the sortorder
1176 * @param bool $shallow - set to false to get the children too
1177 * @return array of categories
1179 function get_categories($parent='none', $sort=NULL, $shallow=true) {
1182 if ($sort === NULL) {
1183 $sort = 'ORDER BY cc.sortorder ASC';
1184 } elseif ($sort ==='') {
1185 // leave it as empty
1187 $sort = "ORDER BY $sort";
1190 list($ccselect, $ccjoin) = context_instance_preload_sql('cc.id', CONTEXT_COURSECAT, 'ctx');
1192 if ($parent === 'none') {
1193 $sql = "SELECT cc.* $ccselect
1194 FROM {course_categories} cc
1199 } elseif ($shallow) {
1200 $sql = "SELECT cc.* $ccselect
1201 FROM {course_categories} cc
1205 $params = array($parent);
1208 $sql = "SELECT cc.* $ccselect
1209 FROM {course_categories} cc
1211 JOIN {course_categories} ccp
1212 ON (cc.path LIKE ".$DB->sql_concat('ccp.path',"'%'").")
1215 $params = array($parent);
1217 $categories = array();
1219 if( $rs = $DB->get_recordset_sql($sql, $params) ){
1220 foreach($rs as $cat) {
1221 context_instance_preload($cat);
1222 $catcontext = get_context_instance(CONTEXT_COURSECAT, $cat->id);
1223 if ($cat->visible || has_capability('moodle/category:viewhiddencategories', $catcontext)) {
1224 $categories[$cat->id] = $cat;
1234 * Returns an array of category ids of all the subcategories for a given
1238 * @param int $catid - The id of the category whose subcategories we want to find.
1239 * @return array of category ids.
1241 function get_all_subcategories($catid) {
1246 if ($categories = $DB->get_records('course_categories', array('parent'=>$catid))) {
1247 foreach ($categories as $cat) {
1248 array_push($subcats, $cat->id);
1249 $subcats = array_merge($subcats, get_all_subcategories($cat->id));
1256 * Return specified category, default if given does not exist
1259 * @uses MAX_COURSES_IN_CATEGORY
1260 * @uses CONTEXT_COURSECAT
1261 * @uses SYSCONTEXTID
1262 * @param int $catid course category id
1263 * @return object caregory
1265 function get_course_category($catid=0) {
1270 if (!empty($catid)) {
1271 $category = $DB->get_record('course_categories', array('id'=>$catid));
1275 // the first category is considered default for now
1276 if ($category = $DB->get_records('course_categories', null, 'sortorder', '*', 0, 1)) {
1277 $category = reset($category);
1280 $cat = new object();
1281 $cat->name = get_string('miscellaneous');
1283 $cat->sortorder = MAX_COURSES_IN_CATEGORY;
1284 $cat->timemodified = time();
1285 $catid = $DB->insert_record('course_categories', $cat);
1286 // make sure category context exists
1287 get_context_instance(CONTEXT_COURSECAT, $catid);
1288 mark_context_dirty('/'.SYSCONTEXTID);
1289 fix_course_sortorder(); // Required to build course_categories.depth and .path.
1290 $category = $DB->get_record('course_categories', array('id'=>$catid));
1298 * Fixes course category and course sortorder, also verifies category and course parents and paths.
1299 * (circular references are not fixed)
1303 * @uses MAX_COURSES_IN_CATEGORY
1304 * @uses MAX_COURSE_CATEGORIES
1306 * @uses CONTEXT_COURSE
1309 function fix_course_sortorder() {
1312 //WARNING: this is PHP5 only code!
1314 if ($unsorted = $DB->get_records('course_categories', array('sortorder'=>0))) {
1315 //move all categories that are not sorted yet to the end
1316 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('sortorder'=>0));
1319 $allcats = $DB->get_records('course_categories', null, 'sortorder, id', 'id, sortorder, parent, depth, path');
1321 $brokencats = array();
1322 foreach ($allcats as $cat) {
1323 $sortorder = (int)$cat->sortorder;
1324 if (!$cat->parent) {
1325 while(isset($topcats[$sortorder])) {
1328 $topcats[$sortorder] = $cat;
1331 if (!isset($allcats[$cat->parent])) {
1332 $brokencats[] = $cat;
1335 if (!isset($allcats[$cat->parent]->children)) {
1336 $allcats[$cat->parent]->children = array();
1338 while(isset($allcats[$cat->parent]->children[$sortorder])) {
1341 $allcats[$cat->parent]->children[$sortorder] = $cat;
1345 // add broken cats to category tree
1347 $defaultcat = reset($topcats);
1348 foreach ($brokencats as $cat) {
1353 // now walk recursively the tree and fix any problems found
1355 $fixcontexts = array();
1356 _fix_course_cats($topcats, $sortorder, 0, 0, '', $fixcontexts);
1358 // detect if there are "multiple" frontpage courses and fix them if needed
1359 $frontcourses = $DB->get_records('course', array('category'=>0), 'id');
1360 if (count($frontcourses) > 1) {
1361 if (isset($frontcourses[SITEID])) {
1362 $frontcourse = $frontcourses[SITEID];
1363 unset($frontcourses[SITEID]);
1365 $frontcourse = array_shift($frontcourses);
1367 $defaultcat = reset($topcats);
1368 foreach ($frontcourses as $course) {
1369 $DB->set_field('course', 'category', $defaultcat->id, array('id'=>$course->id));
1370 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1371 $fixcontexts[$context->id] = $context;
1373 unset($frontcourses);
1375 $frontcourse = reset($frontcourses);
1378 // now fix the paths and depths in context table if needed
1380 rebuild_contexts($fixcontexts);
1386 unset($fixcontexts);
1388 // fix frontpage course sortorder
1389 if ($frontcourse->sortorder != 1) {
1390 $DB->set_field('course', 'sortorder', 1, array('id'=>$frontcourse->id));
1393 // now fix the course counts in category records if needed
1394 $sql = "SELECT cc.id, cc.coursecount, COUNT(c.id) AS newcount
1395 FROM {course_categories} cc
1396 LEFT JOIN {course} c ON c.category = cc.id
1397 GROUP BY cc.id, cc.coursecount
1398 HAVING cc.coursecount <> COUNT(c.id)";
1400 if ($updatecounts = $DB->get_records_sql($sql)) {
1401 foreach ($updatecounts as $cat) {
1402 $cat->coursecount = $cat->newcount;
1403 unset($cat->newcount);
1404 $DB->update_record_raw('course_categories', $cat, true);
1408 // now make sure that sortorders in course table are withing the category sortorder ranges
1409 $sql = "SELECT DISTINCT cc.id, cc.sortorder
1410 FROM {course_categories} cc
1411 JOIN {course} c ON c.category = cc.id
1412 WHERE c.sortorder < cc.sortorder OR c.sortorder > cc.sortorder + ".MAX_COURSES_IN_CATEGORY;
1414 if ($fixcategories = $DB->get_records_sql($sql)) {
1415 //fix the course sortorder ranges
1416 foreach ($fixcategories as $cat) {
1417 $sql = "UPDATE {course}
1418 SET sortorder = ".$DB->sql_modulo('sortorder', MAX_COURSES_IN_CATEGORY)." + ?
1419 WHERE category = ?";
1420 $DB->execute($sql, array($cat->sortorder, $cat->id));
1423 unset($fixcategories);
1425 // categories having courses with sortorder duplicates or having gaps in sortorder
1426 $sql = "SELECT DISTINCT c1.category AS id , cc.sortorder
1428 JOIN {course} c2 ON c1.sortorder = c2.sortorder
1429 JOIN {course_categories} cc ON (c1.category = cc.id)
1430 WHERE c1.id <> c2.id";
1431 $fixcategories = $DB->get_records_sql($sql);
1433 $sql = "SELECT cc.id, cc.sortorder, cc.coursecount, MAX(c.sortorder) AS maxsort, MIN(c.sortorder) AS minsort
1434 FROM {course_categories} cc
1435 JOIN {course} c ON c.category = cc.id
1436 GROUP BY cc.id, cc.sortorder, cc.coursecount
1437 HAVING (MAX(c.sortorder) <> cc.sortorder + cc.coursecount) OR (MIN(c.sortorder) <> cc.sortorder + 1)";
1438 $gapcategories = $DB->get_records_sql($sql);
1440 foreach ($gapcategories as $cat) {
1441 if (isset($fixcategories[$cat->id])) {
1442 // duplicates detected already
1444 } else if ($cat->minsort == $cat->sortorder and $cat->maxsort == $cat->sortorder + $cat->coursecount - 1) {
1445 // easy - new course inserted with sortorder 0, the rest is ok
1446 $sql = "UPDATE {course}
1447 SET sortorder = sortorder + 1
1448 WHERE category = ?";
1449 $DB->execute($sql, array($cat->id));
1452 // it needs full resorting
1453 $fixcategories[$cat->id] = $cat;
1456 unset($gapcategories);
1458 // fix course sortorders in problematic categories only
1459 foreach ($fixcategories as $cat) {
1461 $courses = $DB->get_records('course', array('category'=>$cat->id), 'sortorder ASC, id DESC', 'id, sortorder');
1462 foreach ($courses as $course) {
1463 if ($course->sortorder != $cat->sortorder + $i) {
1464 $course->sortorder = $cat->sortorder + $i;
1465 $DB->update_record_raw('course', $course, true);
1473 * Internal recursive category verification function, do not use directly!
1475 * @todo Document the arguments of this function better
1478 * @uses MAX_COURSES_IN_CATEGORY
1479 * @uses CONTEXT_COURSECAT
1480 * @param array $children
1481 * @param int $sortorder
1482 * @param string $parent
1484 * @param string $path
1485 * @param array $fixcontexts
1488 function _fix_course_cats($children, &$sortorder, $parent, $depth, $path, &$fixcontexts) {
1493 foreach ($children as $cat) {
1494 $sortorder = $sortorder + MAX_COURSES_IN_CATEGORY;
1496 if ($parent != $cat->parent or $depth != $cat->depth or $path.'/'.$cat->id != $cat->path) {
1497 $cat->parent = $parent;
1498 $cat->depth = $depth;
1499 $cat->path = $path.'/'.$cat->id;
1502 // make sure context caches are rebuild and dirty contexts marked
1503 $context = get_context_instance(CONTEXT_COURSECAT, $cat->id);
1504 $fixcontexts[$context->id] = $context;
1506 if ($cat->sortorder != $sortorder) {
1507 $cat->sortorder = $sortorder;
1511 $DB->update_record('course_categories', $cat, true);
1513 if (isset($cat->children)) {
1514 _fix_course_cats($cat->children, $sortorder, $cat->id, $cat->depth, $cat->path, $fixcontexts);
1520 * List of remote courses that a user has access to via MNET.
1521 * Works only on the IDP
1525 * @param int @userid The user id to get remote courses for
1526 * @return array Array of {@link $COURSE} of course objects
1528 function get_my_remotecourses($userid=0) {
1531 if (empty($userid)) {
1532 $userid = $USER->id;
1535 $sql = "SELECT c.id, c.remoteid, c.shortname, c.fullname,
1536 c.hostid, c.summary, c.cat_name,
1538 FROM {mnet_enrol_course} c
1539 JOIN {mnet_enrol_assignments} a ON c.id=a.courseid
1540 JOIN {mnet_host} h ON c.hostid=h.id
1543 return $DB->get_records_sql($sql, array($userid));
1547 * List of remote hosts that a user has access to via MNET.
1552 * @return array|bool Array of host objects or false
1554 function get_my_remotehosts() {
1557 if ($USER->mnethostid == $CFG->mnet_localhost_id) {
1558 return false; // Return nothing on the IDP
1560 if (!empty($USER->mnet_foreign_host_array) && is_array($USER->mnet_foreign_host_array)) {
1561 return $USER->mnet_foreign_host_array;
1567 * This function creates a default separated/connected scale
1569 * This function creates a default separated/connected scale
1570 * so there's something in the database. The locations of
1571 * strings and files is a bit odd, but this is because we
1572 * need to maintain backward compatibility with many different
1573 * existing language translations and older sites.
1579 function make_default_scale() {
1582 $defaultscale = NULL;
1583 $defaultscale->courseid = 0;
1584 $defaultscale->userid = 0;
1585 $defaultscale->name = get_string('separateandconnected');
1586 $defaultscale->scale = get_string('postrating1', 'forum').','.
1587 get_string('postrating2', 'forum').','.
1588 get_string('postrating3', 'forum');
1589 $defaultscale->timemodified = time();
1591 /// Read in the big description from the file. Note this is not
1592 /// HTML (despite the file extension) but Moodle format text.
1593 $parentlang = get_parent_language();
1594 if (is_readable($CFG->dataroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) {
1595 $file = file($CFG->dataroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html');
1596 } else if (is_readable($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) {
1597 $file = file($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html');
1598 } else if ($parentlang and is_readable($CFG->dataroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) {
1599 $file = file($CFG->dataroot .'/lang/'. $parentlang .'/help/forum/ratings.html');
1600 } else if ($parentlang and is_readable($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) {
1601 $file = file($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html');
1602 } else if (is_readable($CFG->dirroot .'/lang/en/help/forum/ratings.html')) {
1603 $file = file($CFG->dirroot .'/lang/en/help/forum/ratings.html');
1608 $defaultscale->description = implode('', $file);
1610 if ($defaultscale->id = $DB->insert_record('scale', $defaultscale)) {
1611 $DB->execute("UPDATE {forum} SET scale = ?", array($defaultscale->id));
1617 * Returns a menu of all available scales from the site as well as the given course
1620 * @param int $courseid The id of the course as found in the 'course' table.
1623 function get_scales_menu($courseid=0) {
1626 $sql = "SELECT id, name
1628 WHERE courseid = 0 or courseid = ?
1629 ORDER BY courseid ASC, name ASC";
1630 $params = array($courseid);
1632 if ($scales = $DB->get_records_sql_menu($sql, $params)) {
1636 make_default_scale();
1638 return $DB->get_records_sql_menu($sql, $params);
1644 * Given a set of timezone records, put them in the database, replacing what is there
1647 * @param array $timezones An array of timezone records
1650 function update_timezone_records($timezones) {
1653 /// Clear out all the old stuff
1654 $DB->delete_records('timezone');
1656 /// Insert all the new stuff
1657 foreach ($timezones as $timezone) {
1658 if (is_array($timezone)) {
1659 $timezone = (object)$timezone;
1661 $DB->insert_record('timezone', $timezone);
1666 /// MODULE FUNCTIONS /////////////////////////////////////////////////
1669 * Just gets a raw list of all modules in a course
1672 * @param int $courseid The id of the course as found in the 'course' table.
1675 function get_course_mods($courseid) {
1678 if (empty($courseid)) {
1679 return false; // avoid warnings
1682 return $DB->get_records_sql("SELECT cm.*, m.name as modname
1683 FROM {modules} m, {course_modules} cm
1684 WHERE cm.course = ? AND cm.module = m.id AND m.visible = 1",
1685 array($courseid)); // no disabled mods
1690 * Given an id of a course module, finds the coursemodule description
1693 * @param string $modulename name of module type, eg. resource, assignment,... (optional, slower and less safe if not specified)
1694 * @param int $cmid course module id (id in course_modules table)
1695 * @param int $courseid optional course id for extra validation
1696 * @param bool $sectionnum include relative section number (0,1,2 ...)
1697 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1698 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1699 * MUST_EXIST means throw exception if no record or multiple records found
1700 * @return array Array of results
1702 function get_coursemodule_from_id($modulename, $cmid, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1705 $params = array('cmid'=>$cmid);
1708 if (!$modulename = $DB->get_field_sql("SELECT md.name
1710 JOIN {course_modules} cm ON cm.module = md.id
1711 WHERE cm.id = :cmid", $params, $strictness)) {
1716 $params['modulename'] = $modulename;
1723 $courseselect = "AND cm.course = :courseid";
1724 $params['courseid'] = $courseid;
1728 $sectionfield = ", cw.section AS sectionnum";
1729 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1732 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1733 FROM {course_modules} cm
1734 JOIN {modules} md ON md.id = cm.module
1735 JOIN {".$modulename."} m ON m.id = cm.instance
1737 WHERE cm.id = :cmid AND md.name = :modulename
1740 return $DB->get_record_sql($sql, $params, $strictness);
1744 * Given an instance number of a module, finds the coursemodule description
1747 * @param string $modulename name of module type, eg. resource, assignment,...
1748 * @param int $instance module instance number (id in resource, assignment etc. table)
1749 * @param int $courseid optional course id for extra validation
1750 * @param bool $sectionnum include relative section number (0,1,2 ...)
1751 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1752 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1753 * MUST_EXIST means throw exception if no record or multiple records found
1754 * @return array Array of results
1756 function get_coursemodule_from_instance($modulename, $instance, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1759 $params = array('instance'=>$instance, 'modulename'=>$modulename);
1766 $courseselect = "AND cm.course = :courseid";
1767 $params['courseid'] = $courseid;
1771 $sectionfield = ", cw.section AS sectionnum";
1772 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1775 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1776 FROM {course_modules} cm
1777 JOIN {modules} md ON md.id = cm.module
1778 JOIN {".$modulename."} m ON m.id = cm.instance
1780 WHERE m.id = :instance AND md.name = :modulename
1783 return $DB->get_record_sql($sql, $params, $strictness);
1787 * Returns all course modules of given activity in course
1789 * @param string $modulename The module name (forum, quiz, etc.)
1790 * @param int $courseid The course id to get modules for
1791 * @param string $extrafields extra fields starting with m.
1792 * @return array Array of results
1794 function get_coursemodules_in_course($modulename, $courseid, $extrafields='') {
1797 if (!empty($extrafields)) {
1798 $extrafields = ", $extrafields";
1801 $params['courseid'] = $courseid;
1802 $params['modulename'] = $modulename;
1805 return $DB->get_records_sql("SELECT cm.*, m.name, md.name as modname $extrafields
1806 FROM {course_modules} cm, {modules} md, {".$modulename."} m
1807 WHERE cm.course = :courseid AND
1808 cm.instance = m.id AND
1809 md.name = :modulename AND
1810 md.id = cm.module", $params);
1814 * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1816 * Returns an array of all the active instances of a particular
1817 * module in given courses, sorted in the order they are defined
1818 * in the course. Returns an empty array on any errors.
1820 * The returned objects includle the columns cw.section, cm.visible,
1821 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1825 * @param string $modulename The name of the module to get instances for
1826 * @param array $courses an array of course objects.
1827 * @param int $userid
1828 * @param int $includeinvisible
1829 * @return array of module instance objects, including some extra fields from the course_modules
1830 * and course_sections tables, or an empty array if an error occurred.
1832 function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
1835 $outputarray = array();
1837 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1838 return $outputarray;
1841 list($coursessql, $params) = $DB->get_in_or_equal(array_keys($courses), SQL_PARAMS_NAMED, 'c0');
1842 $params['modulename'] = $modulename;
1844 if (!$rawmods = $DB->get_records_sql("SELECT cm.id AS coursemodule, m.*, cw.section, cm.visible AS visible,
1845 cm.groupmode, cm.groupingid, cm.groupmembersonly
1846 FROM {course_modules} cm, {course_sections} cw, {modules} md,
1848 WHERE cm.course $coursessql AND
1849 cm.instance = m.id AND
1850 cm.section = cw.id AND
1851 md.name = :modulename AND
1852 md.id = cm.module", $params)) {
1853 return $outputarray;
1856 foreach ($courses as $course) {
1857 $modinfo = get_fast_modinfo($course, $userid);
1859 if (empty($modinfo->instances[$modulename])) {
1863 foreach ($modinfo->instances[$modulename] as $cm) {
1864 if (!$includeinvisible and !$cm->uservisible) {
1867 if (!isset($rawmods[$cm->id])) {
1870 $instance = $rawmods[$cm->id];
1871 if (!empty($cm->extra)) {
1872 $instance->extra = $cm->extra;
1874 $outputarray[] = $instance;
1878 return $outputarray;
1882 * Returns an array of all the active instances of a particular module in a given course,
1883 * sorted in the order they are defined.
1885 * Returns an array of all the active instances of a particular
1886 * module in a given course, sorted in the order they are defined
1887 * in the course. Returns an empty array on any errors.
1889 * The returned objects includle the columns cw.section, cm.visible,
1890 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1892 * Simply calls {@link all_instances_in_courses()} with a single provided course
1894 * @param string $modulename The name of the module to get instances for
1895 * @param object $course The course obect.
1896 * @return array of module instance objects, including some extra fields from the course_modules
1897 * and course_sections tables, or an empty array if an error occurred.
1898 * @param int $userid
1899 * @param int $includeinvisible
1901 function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
1902 return get_all_instances_in_courses($modulename, array($course->id => $course), $userid, $includeinvisible);
1907 * Determine whether a module instance is visible within a course
1909 * Given a valid module object with info about the id and course,
1910 * and the module's type (eg "forum") returns whether the object
1911 * is visible or not, groupmembersonly visibility not tested
1915 * @param $moduletype Name of the module eg 'forum'
1916 * @param $module Object which is the instance of the module
1917 * @return bool Success
1919 function instance_is_visible($moduletype, $module) {
1922 if (!empty($module->id)) {
1923 $params = array('courseid'=>$module->course, 'moduletype'=>$moduletype, 'moduleid'=>$module->id);
1924 if ($records = $DB->get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.groupmembersonly, cm.course
1925 FROM {course_modules} cm, {modules} m
1926 WHERE cm.course = :courseid AND
1927 cm.module = m.id AND
1928 m.name = :moduletype AND
1929 cm.instance = :moduleid", $params)) {
1931 foreach ($records as $record) { // there should only be one - use the first one
1932 return $record->visible;
1936 return true; // visible by default!
1940 * Determine whether a course module is visible within a course,
1941 * this is different from instance_is_visible() - faster and visibility for user
1945 * @uses DEBUG_DEVELOPER
1946 * @uses CONTEXT_MODULE
1947 * @uses CONDITION_MISSING_EXTRATABLE
1948 * @param object $cm object
1949 * @param int $userid empty means current user
1950 * @return bool Success
1952 function coursemodule_visible_for_user($cm, $userid=0) {
1955 if (empty($cm->id)) {
1956 debugging("Incorrect course module parameter!", DEBUG_DEVELOPER);
1959 if (empty($userid)) {
1960 $userid = $USER->id;
1962 if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_MODULE, $cm->id), $userid)) {
1965 if ($CFG->enableavailability) {
1966 require_once($CFG->libdir.'/conditionlib.php');
1967 $ci=new condition_info($cm,CONDITION_MISSING_EXTRATABLE);
1968 if(!$ci->is_available($cm->availableinfo,false,$userid) and
1969 !has_capability('moodle/course:viewhiddenactivities',
1970 get_context_instance(CONTEXT_MODULE, $cm->id), $userid)) {
1974 return groups_course_module_visible($cm, $userid);
1980 /// LOG FUNCTIONS /////////////////////////////////////////////////////
1984 * Add an entry to the log table.
1986 * Add an entry to the log table. These are "action" focussed rather
1987 * than web server hits, and provide a way to easily reconstruct what
1988 * any particular student has been doing.
1994 * @uses DEBUG_DEVELOPER
1996 * @param int $courseid The course id
1997 * @param string $module The module name - e.g. forum, journal, resource, course, user etc
1998 * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
1999 * @param string $url The file and parameters used to see the results of the action
2000 * @param string $info Additional description information
2001 * @param string $cm The course_module->id if there is one
2002 * @param string $user If log regards $user other than $USER
2005 function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
2006 // Note that this function intentionally does not follow the normal Moodle DB access idioms.
2007 // This is for a good reason: it is the most frequently used DB update function,
2008 // so it has been optimised for speed.
2009 global $DB, $CFG, $USER;
2011 if ($cm === '' || is_null($cm)) { // postgres won't translate empty string to its default
2018 if (session_is_loggedinas()) { // Don't log
2021 $userid = empty($USER->id) ? '0' : $USER->id;
2024 $REMOTE_ADDR = getremoteaddr();
2025 if (empty($REMOTE_ADDR)) {
2026 $REMOTE_ADDR = '0.0.0.0';
2031 if (!empty($url)) { // could break doing html_entity_decode on an empty var.
2032 $url = html_entity_decode($url); // for php < 4.3.0 this is defined in moodlelib.php
2035 // Restrict length of log lines to the space actually available in the
2036 // database so that it doesn't cause a DB error. Log a warning so that
2037 // developers can avoid doing things which are likely to cause this on a
2039 $tl = textlib_get_instance();
2040 if(!empty($info) && $tl->strlen($info)>255) {
2041 $info = $tl->substr($info,0,252).'...';
2042 debugging('Warning: logged very long info',DEBUG_DEVELOPER);
2045 // If the 100 field size is changed, also need to alter print_log in course/lib.php
2046 if(!empty($url) && $tl->strlen($url)>100) {
2047 $url=$tl->substr($url,0,97).'...';
2048 debugging('Warning: logged very long URL',DEBUG_DEVELOPER);
2051 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->logwrites++;};
2053 $log = array('time'=>$timenow, 'userid'=>$userid, 'course'=>$courseid, 'ip'=>$REMOTE_ADDR, 'module'=>$module,
2054 'cmid'=>$cm, 'action'=>$action, 'url'=>$url, 'info'=>$info);
2055 $result = $DB->insert_record_raw('log', $log, false);
2057 // MDL-11893, alert $CFG->supportemail if insert into log failed
2058 if (!$result and $CFG->supportemail and empty($CFG->noemailever)) {
2059 // email_to_user is not usable because email_to_user tries to write to the logs table,
2060 // and this will get caught in an infinite loop, if disk is full
2062 $subject = 'Insert into log failed at your moodle site '.$site->fullname;
2063 $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";
2064 $message .= "The failed query parameters are:\n\n" . var_export($log, true);
2066 $lasttime = get_config('admin', 'lastloginserterrormail');
2067 if(empty($lasttime) || time() - $lasttime > 60*60*24) { // limit to 1 email per day
2068 mail($CFG->supportemail, $subject, $message);
2069 set_config('lastloginserterrormail', time(), 'admin');
2074 debugging('Error: Could not insert a new entry to the Moodle log', DEBUG_ALL);
2080 * Store user last access times - called when use enters a course or site
2085 * @uses LASTACCESS_UPDATE_SECS
2087 * @param int $courseid, empty means site
2090 function user_accesstime_log($courseid=0) {
2091 global $USER, $CFG, $DB;
2093 if (!isloggedin() or session_is_loggedinas()) {
2094 // no access tracking
2098 if (empty($courseid)) {
2104 /// Store site lastaccess time for the current user
2105 if ($timenow - $USER->lastaccess > LASTACCESS_UPDATE_SECS) {
2106 /// Update $USER->lastaccess for next checks
2107 $USER->lastaccess = $timenow;
2109 $last = new object();
2110 $last->id = $USER->id;
2111 $last->lastip = getremoteaddr();
2112 $last->lastaccess = $timenow;
2114 $DB->update_record_raw('user', $last);
2117 if ($courseid == SITEID) {
2118 /// no user_lastaccess for frontpage
2122 /// Store course lastaccess times for the current user
2123 if (empty($USER->currentcourseaccess[$courseid]) or ($timenow - $USER->currentcourseaccess[$courseid] > LASTACCESS_UPDATE_SECS)) {
2125 $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid'=>$USER->id, 'courseid'=>$courseid));
2127 if ($lastaccess === false) {
2128 // Update course lastaccess for next checks
2129 $USER->currentcourseaccess[$courseid] = $timenow;
2131 $last = new object();
2132 $last->userid = $USER->id;
2133 $last->courseid = $courseid;
2134 $last->timeaccess = $timenow;
2135 $DB->insert_record_raw('user_lastaccess', $last, false);
2137 } else if ($timenow - $lastaccess < LASTACCESS_UPDATE_SECS) {
2138 // no need to update now, it was updated recently in concurrent login ;-)
2141 // Update course lastaccess for next checks
2142 $USER->currentcourseaccess[$courseid] = $timenow;
2144 $DB->set_field('user_lastaccess', 'timeaccess', $timenow, array('userid'=>$USER->id, 'courseid'=>$courseid));
2150 * Select all log records based on SQL criteria
2152 * @todo Finish documenting this function
2155 * @param string $select SQL select criteria
2156 * @param array $params named sql type params
2157 * @param string $order SQL order by clause to sort the records returned
2158 * @param string $limitfrom ?
2159 * @param int $limitnum ?
2160 * @param int $totalcount Passed in by reference.
2163 function get_logs($select, array $params=null, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
2167 $order = "ORDER BY $order";
2174 $select = "WHERE $select";
2177 $sql = "SELECT COUNT(*)
2181 $totalcount = $DB->count_records_sql($sql, $params);
2183 $sql = "SELECT l.*, u.firstname, u.lastname, u.picture
2185 LEFT JOIN {user} u ON l.userid = u.id
2189 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum) ;
2194 * Select all log records for a given course and user
2196 * @todo Finish documenting this function
2200 * @param int $userid The id of the user as found in the 'user' table.
2201 * @param int $courseid The id of the course as found in the 'course' table.
2202 * @param string $coursestart ?
2204 function get_logs_usercourse($userid, $courseid, $coursestart) {
2211 $courseselect = "AND course = :courseid";
2212 $params['courseid'] = $courseid;
2214 $params['userid'] = $userid;
2215 $params['coursestart'] = $coursestart;
2217 return $DB->get_records_sql("SELECT FLOOR((time - :coursestart)/". DAYSECS .") AS day, COUNT(*) AS num
2219 WHERE userid = :userid
2220 AND time > :coursestart $courseselect
2221 GROUP BY FLOOR((time - :coursestart)/". DAYSECS .")", $params);
2225 * Select all log records for a given course, user, and day
2229 * @param int $userid The id of the user as found in the 'user' table.
2230 * @param int $courseid The id of the course as found in the 'course' table.
2231 * @param string $daystart ?
2234 function get_logs_userday($userid, $courseid, $daystart) {
2237 $params = array($daystart, $userid, $daystart);
2241 $courseselect = "AND course = ?";
2242 $params[] = $courseid;
2244 $params[] = $daystart;
2246 return $DB->get_records_sql("SELECT FLOOR((time - ?)/". HOURSECS .") AS hour, COUNT(*) AS num
2249 AND time > ? $courseselect
2250 GROUP BY FLOOR((time - ?)/". HOURSECS .") ", $params);
2254 * Returns an object with counts of failed login attempts
2256 * Returns information about failed login attempts. If the current user is
2257 * an admin, then two numbers are returned: the number of attempts and the
2258 * number of accounts. For non-admins, only the attempts on the given user
2262 * @uses CONTEXT_SYSTEM
2263 * @param string $mode Either 'admin' or 'everybody'
2264 * @param string $username The username we are searching for
2265 * @param string $lastlogin The date from which we are searching
2268 function count_login_failures($mode, $username, $lastlogin) {
2271 $params = array('mode'=>$mode, 'username'=>$username, 'lastlogin'=>$lastlogin);
2272 $select = "module='login' AND action='error' AND time > :lastlogin";
2274 $count = new object();
2276 if (is_siteadmin()) {
2277 if ($count->attempts = $DB->count_records_select('log', $select, $params)) {
2278 $count->accounts = $DB->count_records_select('log', $select, $params, 'COUNT(DISTINCT info)');
2281 } else if ($mode == 'everybody') {
2282 if ($count->attempts = $DB->count_records_select('log', "$select AND info = :username", $params)) {
2290 /// GENERAL HELPFUL THINGS ///////////////////////////////////
2293 * Dump a given object's information in a PRE block.
2295 * Mostly just used for debugging.
2297 * @param mixed $object The data to be printed
2298 * @return void OUtput is echo'd
2300 function print_object($object) {
2301 echo '<pre class="notifytiny">' . htmlspecialchars(print_r($object,true)) . '</pre>';
2305 * Check whether a course is visible through its parents
2310 * - All we need from the course is ->category. _However_
2311 * if the course object has a categorypath property,
2312 * we'll save a dbquery
2314 * - If we return false, you'll still need to check if
2315 * the user can has the 'moodle/category:viewhiddencategories'
2318 * - Will generate 2 DB calls.
2320 * - It does have a small local cache, however...
2322 * - Do NOT call this over many courses as it'll generate
2323 * DB traffic. Instead, see what get_my_courses() does.
2327 * @staticvar array $mycache
2328 * @param object $course A course object
2331 function course_parent_visible($course = null) {
2336 if (!is_object($course)) {
2339 if (!empty($CFG->allowvisiblecoursesinhiddencategories)) {
2343 if (!isset($mycache)) {
2346 // cast to force assoc array
2347 $k = (string)$course->category;
2348 if (isset($mycache[$k])) {
2349 return $mycache[$k];
2353 if (isset($course->categorypath)) {
2354 $path = $course->categorypath;
2356 $path = $DB->get_field('course_categories', 'path', array('id'=>$course->category));
2358 $catids = substr($path,1); // strip leading slash
2359 $catids = str_replace('/',',',$catids);
2361 $sql = "SELECT MIN(visible)
2362 FROM {course_categories}
2363 WHERE id IN ($catids)";
2364 $vis = $DB->get_field_sql($sql);
2366 // cast to force assoc array
2367 $k = (string)$course->category;
2368 $mycache[$k] = $vis;
2374 * This function is the official hook inside XMLDB stuff to delegate its debug to one
2375 * external function.
2377 * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
2378 * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
2380 * @uses DEBUG_DEVELOPER
2381 * @param string $message string contains the error message
2382 * @param object $object object XMLDB object that fired the debug
2384 function xmldb_debug($message, $object) {
2386 debugging($message, DEBUG_DEVELOPER);
2391 * @uses CONTEXT_COURSECAT
2392 * @return boolean Whether the user can create courses in any category in the system.
2394 function user_can_create_courses() {
2396 $catsrs = $DB->get_recordset('course_categories');
2397 foreach ($catsrs as $cat) {
2398 if (has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $cat->id))) {